(() => {
  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 __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  var __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
  var __esm = (fn3, res) => function __init() {
    return fn3 && (res = (0, fn3[__getOwnPropNames(fn3)[0]])(fn3 = 0)), res;
  };
  var __commonJS = (cb, mod) => function __require() {
    return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
  };
  var __export = (target, all) => {
    for (var name in all)
      __defProp(target, name, { get: all[name], enumerable: true });
  };
  var __reExport = (target, module, copyDefault, desc) => {
    if (module && typeof module === "object" || typeof module === "function") {
      for (let key of __getOwnPropNames(module))
        if (!__hasOwnProp.call(target, key) && (copyDefault || key !== "default"))
          __defProp(target, key, { get: () => module[key], enumerable: !(desc = __getOwnPropDesc(module, key)) || desc.enumerable });
    }
    return target;
  };
  var __toESM = (module, isNodeMode) => {
    return __reExport(__markAsModule(__defProp(module != null ? __create(__getProtoOf(module)) : {}, "default", !isNodeMode && module && module.__esModule ? { get: () => module.default, enumerable: true } : { value: module, enumerable: true })), module);
  };
  var __publicField = (obj, key, value) => {
    __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
    return value;
  };

  // ../../node_modules/@hotwired/turbo-rails/node_modules/@rails/actioncable/src/adapters.js
  var adapters_default;
  var init_adapters = __esm({
    "../../node_modules/@hotwired/turbo-rails/node_modules/@rails/actioncable/src/adapters.js"() {
      adapters_default = {
        logger: self.console,
        WebSocket: self.WebSocket
      };
    }
  });

  // ../../node_modules/@hotwired/turbo-rails/node_modules/@rails/actioncable/src/logger.js
  var logger_default;
  var init_logger = __esm({
    "../../node_modules/@hotwired/turbo-rails/node_modules/@rails/actioncable/src/logger.js"() {
      init_adapters();
      logger_default = {
        log(...messages) {
          if (this.enabled) {
            messages.push(Date.now());
            adapters_default.logger.log("[ActionCable]", ...messages);
          }
        }
      };
    }
  });

  // ../../node_modules/@hotwired/turbo-rails/node_modules/@rails/actioncable/src/connection_monitor.js
  var now, secondsSince, ConnectionMonitor, connection_monitor_default;
  var init_connection_monitor = __esm({
    "../../node_modules/@hotwired/turbo-rails/node_modules/@rails/actioncable/src/connection_monitor.js"() {
      init_logger();
      now = () => new Date().getTime();
      secondsSince = (time) => (now() - time) / 1e3;
      ConnectionMonitor = class {
        constructor(connection) {
          this.visibilityDidChange = this.visibilityDidChange.bind(this);
          this.connection = connection;
          this.reconnectAttempts = 0;
        }
        start() {
          if (!this.isRunning()) {
            this.startedAt = now();
            delete this.stoppedAt;
            this.startPolling();
            addEventListener("visibilitychange", this.visibilityDidChange);
            logger_default.log(`ConnectionMonitor started. stale threshold = ${this.constructor.staleThreshold} s`);
          }
        }
        stop() {
          if (this.isRunning()) {
            this.stoppedAt = now();
            this.stopPolling();
            removeEventListener("visibilitychange", this.visibilityDidChange);
            logger_default.log("ConnectionMonitor stopped");
          }
        }
        isRunning() {
          return this.startedAt && !this.stoppedAt;
        }
        recordPing() {
          this.pingedAt = now();
        }
        recordConnect() {
          this.reconnectAttempts = 0;
          this.recordPing();
          delete this.disconnectedAt;
          logger_default.log("ConnectionMonitor recorded connect");
        }
        recordDisconnect() {
          this.disconnectedAt = now();
          logger_default.log("ConnectionMonitor recorded disconnect");
        }
        startPolling() {
          this.stopPolling();
          this.poll();
        }
        stopPolling() {
          clearTimeout(this.pollTimeout);
        }
        poll() {
          this.pollTimeout = setTimeout(() => {
            this.reconnectIfStale();
            this.poll();
          }, this.getPollInterval());
        }
        getPollInterval() {
          const { staleThreshold, reconnectionBackoffRate } = this.constructor;
          const backoff = Math.pow(1 + reconnectionBackoffRate, Math.min(this.reconnectAttempts, 10));
          const jitterMax = this.reconnectAttempts === 0 ? 1 : reconnectionBackoffRate;
          const jitter = jitterMax * Math.random();
          return staleThreshold * 1e3 * backoff * (1 + jitter);
        }
        reconnectIfStale() {
          if (this.connectionIsStale()) {
            logger_default.log(`ConnectionMonitor detected stale connection. reconnectAttempts = ${this.reconnectAttempts}, time stale = ${secondsSince(this.refreshedAt)} s, stale threshold = ${this.constructor.staleThreshold} s`);
            this.reconnectAttempts++;
            if (this.disconnectedRecently()) {
              logger_default.log(`ConnectionMonitor skipping reopening recent disconnect. time disconnected = ${secondsSince(this.disconnectedAt)} s`);
            } else {
              logger_default.log("ConnectionMonitor reopening");
              this.connection.reopen();
            }
          }
        }
        get refreshedAt() {
          return this.pingedAt ? this.pingedAt : this.startedAt;
        }
        connectionIsStale() {
          return secondsSince(this.refreshedAt) > this.constructor.staleThreshold;
        }
        disconnectedRecently() {
          return this.disconnectedAt && secondsSince(this.disconnectedAt) < this.constructor.staleThreshold;
        }
        visibilityDidChange() {
          if (document.visibilityState === "visible") {
            setTimeout(() => {
              if (this.connectionIsStale() || !this.connection.isOpen()) {
                logger_default.log(`ConnectionMonitor reopening stale connection on visibilitychange. visibilityState = ${document.visibilityState}`);
                this.connection.reopen();
              }
            }, 200);
          }
        }
      };
      ConnectionMonitor.staleThreshold = 6;
      ConnectionMonitor.reconnectionBackoffRate = 0.15;
      connection_monitor_default = ConnectionMonitor;
    }
  });

  // ../../node_modules/@hotwired/turbo-rails/node_modules/@rails/actioncable/src/internal.js
  var internal_default;
  var init_internal = __esm({
    "../../node_modules/@hotwired/turbo-rails/node_modules/@rails/actioncable/src/internal.js"() {
      internal_default = {
        "message_types": {
          "welcome": "welcome",
          "disconnect": "disconnect",
          "ping": "ping",
          "confirmation": "confirm_subscription",
          "rejection": "reject_subscription"
        },
        "disconnect_reasons": {
          "unauthorized": "unauthorized",
          "invalid_request": "invalid_request",
          "server_restart": "server_restart"
        },
        "default_mount_path": "/cable",
        "protocols": [
          "actioncable-v1-json",
          "actioncable-unsupported"
        ]
      };
    }
  });

  // ../../node_modules/@hotwired/turbo-rails/node_modules/@rails/actioncable/src/connection.js
  var message_types, protocols, supportedProtocols, indexOf, Connection, connection_default;
  var init_connection = __esm({
    "../../node_modules/@hotwired/turbo-rails/node_modules/@rails/actioncable/src/connection.js"() {
      init_adapters();
      init_connection_monitor();
      init_internal();
      init_logger();
      ({ message_types, protocols } = internal_default);
      supportedProtocols = protocols.slice(0, protocols.length - 1);
      indexOf = [].indexOf;
      Connection = class {
        constructor(consumer2) {
          this.open = this.open.bind(this);
          this.consumer = consumer2;
          this.subscriptions = this.consumer.subscriptions;
          this.monitor = new connection_monitor_default(this);
          this.disconnected = true;
        }
        send(data) {
          if (this.isOpen()) {
            this.webSocket.send(JSON.stringify(data));
            return true;
          } else {
            return false;
          }
        }
        open() {
          if (this.isActive()) {
            logger_default.log(`Attempted to open WebSocket, but existing socket is ${this.getState()}`);
            return false;
          } else {
            logger_default.log(`Opening WebSocket, current state is ${this.getState()}, subprotocols: ${protocols}`);
            if (this.webSocket) {
              this.uninstallEventHandlers();
            }
            this.webSocket = new adapters_default.WebSocket(this.consumer.url, protocols);
            this.installEventHandlers();
            this.monitor.start();
            return true;
          }
        }
        close({ allowReconnect } = { allowReconnect: true }) {
          if (!allowReconnect) {
            this.monitor.stop();
          }
          if (this.isOpen()) {
            return this.webSocket.close();
          }
        }
        reopen() {
          logger_default.log(`Reopening WebSocket, current state is ${this.getState()}`);
          if (this.isActive()) {
            try {
              return this.close();
            } catch (error3) {
              logger_default.log("Failed to reopen WebSocket", error3);
            } finally {
              logger_default.log(`Reopening WebSocket in ${this.constructor.reopenDelay}ms`);
              setTimeout(this.open, this.constructor.reopenDelay);
            }
          } else {
            return this.open();
          }
        }
        getProtocol() {
          if (this.webSocket) {
            return this.webSocket.protocol;
          }
        }
        isOpen() {
          return this.isState("open");
        }
        isActive() {
          return this.isState("open", "connecting");
        }
        isProtocolSupported() {
          return indexOf.call(supportedProtocols, this.getProtocol()) >= 0;
        }
        isState(...states) {
          return indexOf.call(states, this.getState()) >= 0;
        }
        getState() {
          if (this.webSocket) {
            for (let state in adapters_default.WebSocket) {
              if (adapters_default.WebSocket[state] === this.webSocket.readyState) {
                return state.toLowerCase();
              }
            }
          }
          return null;
        }
        installEventHandlers() {
          for (let eventName in this.events) {
            const handler = this.events[eventName].bind(this);
            this.webSocket[`on${eventName}`] = handler;
          }
        }
        uninstallEventHandlers() {
          for (let eventName in this.events) {
            this.webSocket[`on${eventName}`] = function() {
            };
          }
        }
      };
      Connection.reopenDelay = 500;
      Connection.prototype.events = {
        message(event) {
          if (!this.isProtocolSupported()) {
            return;
          }
          const { identifier, message, reason, reconnect, type } = JSON.parse(event.data);
          switch (type) {
            case message_types.welcome:
              this.monitor.recordConnect();
              return this.subscriptions.reload();
            case message_types.disconnect:
              logger_default.log(`Disconnecting. Reason: ${reason}`);
              return this.close({ allowReconnect: reconnect });
            case message_types.ping:
              return this.monitor.recordPing();
            case message_types.confirmation:
              this.subscriptions.confirmSubscription(identifier);
              return this.subscriptions.notify(identifier, "connected");
            case message_types.rejection:
              return this.subscriptions.reject(identifier);
            default:
              return this.subscriptions.notify(identifier, "received", message);
          }
        },
        open() {
          logger_default.log(`WebSocket onopen event, using '${this.getProtocol()}' subprotocol`);
          this.disconnected = false;
          if (!this.isProtocolSupported()) {
            logger_default.log("Protocol is unsupported. Stopping monitor and disconnecting.");
            return this.close({ allowReconnect: false });
          }
        },
        close(event) {
          logger_default.log("WebSocket onclose event");
          if (this.disconnected) {
            return;
          }
          this.disconnected = true;
          this.monitor.recordDisconnect();
          return this.subscriptions.notifyAll("disconnected", { willAttemptReconnect: this.monitor.isRunning() });
        },
        error() {
          logger_default.log("WebSocket onerror event");
        }
      };
      connection_default = Connection;
    }
  });

  // ../../node_modules/@hotwired/turbo-rails/node_modules/@rails/actioncable/src/subscription.js
  var extend, Subscription;
  var init_subscription = __esm({
    "../../node_modules/@hotwired/turbo-rails/node_modules/@rails/actioncable/src/subscription.js"() {
      extend = function(object, properties) {
        if (properties != null) {
          for (let key in properties) {
            const value = properties[key];
            object[key] = value;
          }
        }
        return object;
      };
      Subscription = class {
        constructor(consumer2, params = {}, mixin) {
          this.consumer = consumer2;
          this.identifier = JSON.stringify(params);
          extend(this, mixin);
        }
        perform(action, data = {}) {
          data.action = action;
          return this.send(data);
        }
        send(data) {
          return this.consumer.send({ command: "message", identifier: this.identifier, data: JSON.stringify(data) });
        }
        unsubscribe() {
          return this.consumer.subscriptions.remove(this);
        }
      };
    }
  });

  // ../../node_modules/@hotwired/turbo-rails/node_modules/@rails/actioncable/src/subscription_guarantor.js
  var SubscriptionGuarantor, subscription_guarantor_default;
  var init_subscription_guarantor = __esm({
    "../../node_modules/@hotwired/turbo-rails/node_modules/@rails/actioncable/src/subscription_guarantor.js"() {
      init_logger();
      SubscriptionGuarantor = class {
        constructor(subscriptions) {
          this.subscriptions = subscriptions;
          this.pendingSubscriptions = [];
        }
        guarantee(subscription) {
          if (this.pendingSubscriptions.indexOf(subscription) == -1) {
            logger_default.log(`SubscriptionGuarantor guaranteeing ${subscription.identifier}`);
            this.pendingSubscriptions.push(subscription);
          } else {
            logger_default.log(`SubscriptionGuarantor already guaranteeing ${subscription.identifier}`);
          }
          this.startGuaranteeing();
        }
        forget(subscription) {
          logger_default.log(`SubscriptionGuarantor forgetting ${subscription.identifier}`);
          this.pendingSubscriptions = this.pendingSubscriptions.filter((s2) => s2 !== subscription);
        }
        startGuaranteeing() {
          this.stopGuaranteeing();
          this.retrySubscribing();
        }
        stopGuaranteeing() {
          clearTimeout(this.retryTimeout);
        }
        retrySubscribing() {
          this.retryTimeout = setTimeout(() => {
            if (this.subscriptions && typeof this.subscriptions.subscribe === "function") {
              this.pendingSubscriptions.map((subscription) => {
                logger_default.log(`SubscriptionGuarantor resubscribing ${subscription.identifier}`);
                this.subscriptions.subscribe(subscription);
              });
            }
          }, 500);
        }
      };
      subscription_guarantor_default = SubscriptionGuarantor;
    }
  });

  // ../../node_modules/@hotwired/turbo-rails/node_modules/@rails/actioncable/src/subscriptions.js
  var Subscriptions;
  var init_subscriptions = __esm({
    "../../node_modules/@hotwired/turbo-rails/node_modules/@rails/actioncable/src/subscriptions.js"() {
      init_subscription();
      init_subscription_guarantor();
      init_logger();
      Subscriptions = class {
        constructor(consumer2) {
          this.consumer = consumer2;
          this.guarantor = new subscription_guarantor_default(this);
          this.subscriptions = [];
        }
        create(channelName, mixin) {
          const channel = channelName;
          const params = typeof channel === "object" ? channel : { channel };
          const subscription = new Subscription(this.consumer, params, mixin);
          return this.add(subscription);
        }
        add(subscription) {
          this.subscriptions.push(subscription);
          this.consumer.ensureActiveConnection();
          this.notify(subscription, "initialized");
          this.subscribe(subscription);
          return subscription;
        }
        remove(subscription) {
          this.forget(subscription);
          if (!this.findAll(subscription.identifier).length) {
            this.sendCommand(subscription, "unsubscribe");
          }
          return subscription;
        }
        reject(identifier) {
          return this.findAll(identifier).map((subscription) => {
            this.forget(subscription);
            this.notify(subscription, "rejected");
            return subscription;
          });
        }
        forget(subscription) {
          this.guarantor.forget(subscription);
          this.subscriptions = this.subscriptions.filter((s2) => s2 !== subscription);
          return subscription;
        }
        findAll(identifier) {
          return this.subscriptions.filter((s2) => s2.identifier === identifier);
        }
        reload() {
          return this.subscriptions.map((subscription) => this.subscribe(subscription));
        }
        notifyAll(callbackName, ...args) {
          return this.subscriptions.map((subscription) => this.notify(subscription, callbackName, ...args));
        }
        notify(subscription, callbackName, ...args) {
          let subscriptions;
          if (typeof subscription === "string") {
            subscriptions = this.findAll(subscription);
          } else {
            subscriptions = [subscription];
          }
          return subscriptions.map((subscription2) => typeof subscription2[callbackName] === "function" ? subscription2[callbackName](...args) : void 0);
        }
        subscribe(subscription) {
          if (this.sendCommand(subscription, "subscribe")) {
            this.guarantor.guarantee(subscription);
          }
        }
        confirmSubscription(identifier) {
          logger_default.log(`Subscription confirmed ${identifier}`);
          this.findAll(identifier).map((subscription) => this.guarantor.forget(subscription));
        }
        sendCommand(subscription, command) {
          const { identifier } = subscription;
          return this.consumer.send({ command, identifier });
        }
      };
    }
  });

  // ../../node_modules/@hotwired/turbo-rails/node_modules/@rails/actioncable/src/consumer.js
  function createWebSocketURL(url) {
    if (typeof url === "function") {
      url = url();
    }
    if (url && !/^wss?:/i.test(url)) {
      const a2 = document.createElement("a");
      a2.href = url;
      a2.href = a2.href;
      a2.protocol = a2.protocol.replace("http", "ws");
      return a2.href;
    } else {
      return url;
    }
  }
  var Consumer;
  var init_consumer = __esm({
    "../../node_modules/@hotwired/turbo-rails/node_modules/@rails/actioncable/src/consumer.js"() {
      init_connection();
      init_subscriptions();
      Consumer = class {
        constructor(url) {
          this._url = url;
          this.subscriptions = new Subscriptions(this);
          this.connection = new connection_default(this);
        }
        get url() {
          return createWebSocketURL(this._url);
        }
        send(data) {
          return this.connection.send(data);
        }
        connect() {
          return this.connection.open();
        }
        disconnect() {
          return this.connection.close({ allowReconnect: false });
        }
        ensureActiveConnection() {
          if (!this.connection.isActive()) {
            return this.connection.open();
          }
        }
      };
    }
  });

  // ../../node_modules/@hotwired/turbo-rails/node_modules/@rails/actioncable/src/index.js
  var src_exports = {};
  __export(src_exports, {
    Connection: () => connection_default,
    ConnectionMonitor: () => connection_monitor_default,
    Consumer: () => Consumer,
    INTERNAL: () => internal_default,
    Subscription: () => Subscription,
    SubscriptionGuarantor: () => subscription_guarantor_default,
    Subscriptions: () => Subscriptions,
    adapters: () => adapters_default,
    createConsumer: () => createConsumer,
    createWebSocketURL: () => createWebSocketURL,
    getConfig: () => getConfig,
    logger: () => logger_default
  });
  function createConsumer(url = getConfig("url") || internal_default.default_mount_path) {
    return new Consumer(url);
  }
  function getConfig(name) {
    const element = document.head.querySelector(`meta[name='action-cable-${name}']`);
    if (element) {
      return element.getAttribute("content");
    }
  }
  var init_src = __esm({
    "../../node_modules/@hotwired/turbo-rails/node_modules/@rails/actioncable/src/index.js"() {
      init_connection();
      init_connection_monitor();
      init_consumer();
      init_internal();
      init_subscription();
      init_subscriptions();
      init_subscription_guarantor();
      init_adapters();
      init_logger();
    }
  });

  // ../../node_modules/@rails/ujs/lib/assets/compiled/rails-ujs.js
  var require_rails_ujs = __commonJS({
    "../../node_modules/@rails/ujs/lib/assets/compiled/rails-ujs.js"(exports, module) {
      (function() {
        var context = this;
        (function() {
          (function() {
            this.Rails = {
              linkClickSelector: "a[data-confirm], a[data-method], a[data-remote]:not([disabled]), a[data-disable-with], a[data-disable]",
              buttonClickSelector: {
                selector: "button[data-remote]:not([form]), button[data-confirm]:not([form])",
                exclude: "form button"
              },
              inputChangeSelector: "select[data-remote], input[data-remote], textarea[data-remote]",
              formSubmitSelector: "form:not([data-turbo=true])",
              formInputClickSelector: "form:not([data-turbo=true]) input[type=submit], form:not([data-turbo=true]) input[type=image], form:not([data-turbo=true]) button[type=submit], form:not([data-turbo=true]) button:not([type]), input[type=submit][form], input[type=image][form], button[type=submit][form], button[form]:not([type])",
              formDisableSelector: "input[data-disable-with]:enabled, button[data-disable-with]:enabled, textarea[data-disable-with]:enabled, input[data-disable]:enabled, button[data-disable]:enabled, textarea[data-disable]:enabled",
              formEnableSelector: "input[data-disable-with]:disabled, button[data-disable-with]:disabled, textarea[data-disable-with]:disabled, input[data-disable]:disabled, button[data-disable]:disabled, textarea[data-disable]:disabled",
              fileInputSelector: "input[name][type=file]:not([disabled])",
              linkDisableSelector: "a[data-disable-with], a[data-disable]",
              buttonDisableSelector: "button[data-remote][data-disable-with], button[data-remote][data-disable]"
            };
          }).call(this);
        }).call(context);
        var Rails2 = context.Rails;
        (function() {
          (function() {
            var nonce;
            nonce = null;
            Rails2.loadCSPNonce = function() {
              var ref;
              return nonce = (ref = document.querySelector("meta[name=csp-nonce]")) != null ? ref.content : void 0;
            };
            Rails2.cspNonce = function() {
              return nonce != null ? nonce : Rails2.loadCSPNonce();
            };
          }).call(this);
          (function() {
            var expando, m2;
            m2 = Element.prototype.matches || Element.prototype.matchesSelector || Element.prototype.mozMatchesSelector || Element.prototype.msMatchesSelector || Element.prototype.oMatchesSelector || Element.prototype.webkitMatchesSelector;
            Rails2.matches = function(element, selector) {
              if (selector.exclude != null) {
                return m2.call(element, selector.selector) && !m2.call(element, selector.exclude);
              } else {
                return m2.call(element, selector);
              }
            };
            expando = "_ujsData";
            Rails2.getData = function(element, key) {
              var ref;
              return (ref = element[expando]) != null ? ref[key] : void 0;
            };
            Rails2.setData = function(element, key, value) {
              if (element[expando] == null) {
                element[expando] = {};
              }
              return element[expando][key] = value;
            };
            Rails2.$ = function(selector) {
              return Array.prototype.slice.call(document.querySelectorAll(selector));
            };
          }).call(this);
          (function() {
            var $2, csrfParam, csrfToken;
            $2 = Rails2.$;
            csrfToken = Rails2.csrfToken = function() {
              var meta;
              meta = document.querySelector("meta[name=csrf-token]");
              return meta && meta.content;
            };
            csrfParam = Rails2.csrfParam = function() {
              var meta;
              meta = document.querySelector("meta[name=csrf-param]");
              return meta && meta.content;
            };
            Rails2.CSRFProtection = function(xhr) {
              var token;
              token = csrfToken();
              if (token != null) {
                return xhr.setRequestHeader("X-CSRF-Token", token);
              }
            };
            Rails2.refreshCSRFTokens = function() {
              var param, token;
              token = csrfToken();
              param = csrfParam();
              if (token != null && param != null) {
                return $2('form input[name="' + param + '"]').forEach(function(input) {
                  return input.value = token;
                });
              }
            };
          }).call(this);
          (function() {
            var CustomEvent2, fire, matches, preventDefault;
            matches = Rails2.matches;
            CustomEvent2 = window.CustomEvent;
            if (typeof CustomEvent2 !== "function") {
              CustomEvent2 = function(event, params) {
                var evt;
                evt = document.createEvent("CustomEvent");
                evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
                return evt;
              };
              CustomEvent2.prototype = window.Event.prototype;
              preventDefault = CustomEvent2.prototype.preventDefault;
              CustomEvent2.prototype.preventDefault = function() {
                var result;
                result = preventDefault.call(this);
                if (this.cancelable && !this.defaultPrevented) {
                  Object.defineProperty(this, "defaultPrevented", {
                    get: function() {
                      return true;
                    }
                  });
                }
                return result;
              };
            }
            fire = Rails2.fire = function(obj, name, data) {
              var event;
              event = new CustomEvent2(name, {
                bubbles: true,
                cancelable: true,
                detail: data
              });
              obj.dispatchEvent(event);
              return !event.defaultPrevented;
            };
            Rails2.stopEverything = function(e2) {
              fire(e2.target, "ujs:everythingStopped");
              e2.preventDefault();
              e2.stopPropagation();
              return e2.stopImmediatePropagation();
            };
            Rails2.delegate = function(element, selector, eventType, handler) {
              return element.addEventListener(eventType, function(e2) {
                var target;
                target = e2.target;
                while (!(!(target instanceof Element) || matches(target, selector))) {
                  target = target.parentNode;
                }
                if (target instanceof Element && handler.call(target, e2) === false) {
                  e2.preventDefault();
                  return e2.stopPropagation();
                }
              });
            };
          }).call(this);
          (function() {
            var AcceptHeaders, CSRFProtection, createXHR, cspNonce, fire, prepareOptions, processResponse;
            cspNonce = Rails2.cspNonce, CSRFProtection = Rails2.CSRFProtection, fire = Rails2.fire;
            AcceptHeaders = {
              "*": "*/*",
              text: "text/plain",
              html: "text/html",
              xml: "application/xml, text/xml",
              json: "application/json, text/javascript",
              script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
            };
            Rails2.ajax = function(options) {
              var xhr;
              options = prepareOptions(options);
              xhr = createXHR(options, function() {
                var ref, response;
                response = processResponse((ref = xhr.response) != null ? ref : xhr.responseText, xhr.getResponseHeader("Content-Type"));
                if (Math.floor(xhr.status / 100) === 2) {
                  if (typeof options.success === "function") {
                    options.success(response, xhr.statusText, xhr);
                  }
                } else {
                  if (typeof options.error === "function") {
                    options.error(response, xhr.statusText, xhr);
                  }
                }
                return typeof options.complete === "function" ? options.complete(xhr, xhr.statusText) : void 0;
              });
              if (options.beforeSend != null && !options.beforeSend(xhr, options)) {
                return false;
              }
              if (xhr.readyState === XMLHttpRequest.OPENED) {
                return xhr.send(options.data);
              }
            };
            prepareOptions = function(options) {
              options.url = options.url || location.href;
              options.type = options.type.toUpperCase();
              if (options.type === "GET" && options.data) {
                if (options.url.indexOf("?") < 0) {
                  options.url += "?" + options.data;
                } else {
                  options.url += "&" + options.data;
                }
              }
              if (AcceptHeaders[options.dataType] == null) {
                options.dataType = "*";
              }
              options.accept = AcceptHeaders[options.dataType];
              if (options.dataType !== "*") {
                options.accept += ", */*; q=0.01";
              }
              return options;
            };
            createXHR = function(options, done) {
              var xhr;
              xhr = new XMLHttpRequest();
              xhr.open(options.type, options.url, true);
              xhr.setRequestHeader("Accept", options.accept);
              if (typeof options.data === "string") {
                xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
              }
              if (!options.crossDomain) {
                xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
                CSRFProtection(xhr);
              }
              xhr.withCredentials = !!options.withCredentials;
              xhr.onreadystatechange = function() {
                if (xhr.readyState === XMLHttpRequest.DONE) {
                  return done(xhr);
                }
              };
              return xhr;
            };
            processResponse = function(response, type) {
              var parser, script;
              if (typeof response === "string" && typeof type === "string") {
                if (type.match(/\bjson\b/)) {
                  try {
                    response = JSON.parse(response);
                  } catch (error3) {
                  }
                } else if (type.match(/\b(?:java|ecma)script\b/)) {
                  script = document.createElement("script");
                  script.setAttribute("nonce", cspNonce());
                  script.text = response;
                  document.head.appendChild(script).parentNode.removeChild(script);
                } else if (type.match(/\b(xml|html|svg)\b/)) {
                  parser = new DOMParser();
                  type = type.replace(/;.+/, "");
                  try {
                    response = parser.parseFromString(response, type);
                  } catch (error3) {
                  }
                }
              }
              return response;
            };
            Rails2.href = function(element) {
              return element.href;
            };
            Rails2.isCrossDomain = function(url) {
              var e2, originAnchor, urlAnchor;
              originAnchor = document.createElement("a");
              originAnchor.href = location.href;
              urlAnchor = document.createElement("a");
              try {
                urlAnchor.href = url;
                return !((!urlAnchor.protocol || urlAnchor.protocol === ":") && !urlAnchor.host || originAnchor.protocol + "//" + originAnchor.host === urlAnchor.protocol + "//" + urlAnchor.host);
              } catch (error3) {
                e2 = error3;
                return true;
              }
            };
          }).call(this);
          (function() {
            var matches, toArray2;
            matches = Rails2.matches;
            toArray2 = function(e2) {
              return Array.prototype.slice.call(e2);
            };
            Rails2.serializeElement = function(element, additionalParam) {
              var inputs, params;
              inputs = [element];
              if (matches(element, "form")) {
                inputs = toArray2(element.elements);
              }
              params = [];
              inputs.forEach(function(input) {
                if (!input.name || input.disabled) {
                  return;
                }
                if (matches(input, "fieldset[disabled] *")) {
                  return;
                }
                if (matches(input, "select")) {
                  return toArray2(input.options).forEach(function(option) {
                    if (option.selected) {
                      return params.push({
                        name: input.name,
                        value: option.value
                      });
                    }
                  });
                } else if (input.checked || ["radio", "checkbox", "submit"].indexOf(input.type) === -1) {
                  return params.push({
                    name: input.name,
                    value: input.value
                  });
                }
              });
              if (additionalParam) {
                params.push(additionalParam);
              }
              return params.map(function(param) {
                if (param.name != null) {
                  return encodeURIComponent(param.name) + "=" + encodeURIComponent(param.value);
                } else {
                  return param;
                }
              }).join("&");
            };
            Rails2.formElements = function(form, selector) {
              if (matches(form, "form")) {
                return toArray2(form.elements).filter(function(el) {
                  return matches(el, selector);
                });
              } else {
                return toArray2(form.querySelectorAll(selector));
              }
            };
          }).call(this);
          (function() {
            var allowAction, fire, stopEverything;
            fire = Rails2.fire, stopEverything = Rails2.stopEverything;
            Rails2.handleConfirm = function(e2) {
              if (!allowAction(this)) {
                return stopEverything(e2);
              }
            };
            Rails2.confirm = function(message, element) {
              return confirm(message);
            };
            allowAction = function(element) {
              var answer, callback2, message;
              message = element.getAttribute("data-confirm");
              if (!message) {
                return true;
              }
              answer = false;
              if (fire(element, "confirm")) {
                try {
                  answer = Rails2.confirm(message, element);
                } catch (error3) {
                }
                callback2 = fire(element, "confirm:complete", [answer]);
              }
              return answer && callback2;
            };
          }).call(this);
          (function() {
            var disableFormElement, disableFormElements, disableLinkElement, enableFormElement, enableFormElements, enableLinkElement, formElements, getData, isXhrRedirect, matches, setData, stopEverything;
            matches = Rails2.matches, getData = Rails2.getData, setData = Rails2.setData, stopEverything = Rails2.stopEverything, formElements = Rails2.formElements;
            Rails2.handleDisabledElement = function(e2) {
              var element;
              element = this;
              if (element.disabled) {
                return stopEverything(e2);
              }
            };
            Rails2.enableElement = function(e2) {
              var element;
              if (e2 instanceof Event) {
                if (isXhrRedirect(e2)) {
                  return;
                }
                element = e2.target;
              } else {
                element = e2;
              }
              if (matches(element, Rails2.linkDisableSelector)) {
                return enableLinkElement(element);
              } else if (matches(element, Rails2.buttonDisableSelector) || matches(element, Rails2.formEnableSelector)) {
                return enableFormElement(element);
              } else if (matches(element, Rails2.formSubmitSelector)) {
                return enableFormElements(element);
              }
            };
            Rails2.disableElement = function(e2) {
              var element;
              element = e2 instanceof Event ? e2.target : e2;
              if (matches(element, Rails2.linkDisableSelector)) {
                return disableLinkElement(element);
              } else if (matches(element, Rails2.buttonDisableSelector) || matches(element, Rails2.formDisableSelector)) {
                return disableFormElement(element);
              } else if (matches(element, Rails2.formSubmitSelector)) {
                return disableFormElements(element);
              }
            };
            disableLinkElement = function(element) {
              var replacement;
              if (getData(element, "ujs:disabled")) {
                return;
              }
              replacement = element.getAttribute("data-disable-with");
              if (replacement != null) {
                setData(element, "ujs:enable-with", element.innerHTML);
                element.innerHTML = replacement;
              }
              element.addEventListener("click", stopEverything);
              return setData(element, "ujs:disabled", true);
            };
            enableLinkElement = function(element) {
              var originalText;
              originalText = getData(element, "ujs:enable-with");
              if (originalText != null) {
                element.innerHTML = originalText;
                setData(element, "ujs:enable-with", null);
              }
              element.removeEventListener("click", stopEverything);
              return setData(element, "ujs:disabled", null);
            };
            disableFormElements = function(form) {
              return formElements(form, Rails2.formDisableSelector).forEach(disableFormElement);
            };
            disableFormElement = function(element) {
              var replacement;
              if (getData(element, "ujs:disabled")) {
                return;
              }
              replacement = element.getAttribute("data-disable-with");
              if (replacement != null) {
                if (matches(element, "button")) {
                  setData(element, "ujs:enable-with", element.innerHTML);
                  element.innerHTML = replacement;
                } else {
                  setData(element, "ujs:enable-with", element.value);
                  element.value = replacement;
                }
              }
              element.disabled = true;
              return setData(element, "ujs:disabled", true);
            };
            enableFormElements = function(form) {
              return formElements(form, Rails2.formEnableSelector).forEach(enableFormElement);
            };
            enableFormElement = function(element) {
              var originalText;
              originalText = getData(element, "ujs:enable-with");
              if (originalText != null) {
                if (matches(element, "button")) {
                  element.innerHTML = originalText;
                } else {
                  element.value = originalText;
                }
                setData(element, "ujs:enable-with", null);
              }
              element.disabled = false;
              return setData(element, "ujs:disabled", null);
            };
            isXhrRedirect = function(event) {
              var ref, xhr;
              xhr = (ref = event.detail) != null ? ref[0] : void 0;
              return (xhr != null ? xhr.getResponseHeader("X-Xhr-Redirect") : void 0) != null;
            };
          }).call(this);
          (function() {
            var stopEverything;
            stopEverything = Rails2.stopEverything;
            Rails2.handleMethod = function(e2) {
              var csrfParam, csrfToken, form, formContent, href, link, method;
              link = this;
              method = link.getAttribute("data-method");
              if (!method) {
                return;
              }
              href = Rails2.href(link);
              csrfToken = Rails2.csrfToken();
              csrfParam = Rails2.csrfParam();
              form = document.createElement("form");
              formContent = "<input name='_method' value='" + method + "' type='hidden' />";
              if (csrfParam != null && csrfToken != null && !Rails2.isCrossDomain(href)) {
                formContent += "<input name='" + csrfParam + "' value='" + csrfToken + "' type='hidden' />";
              }
              formContent += '<input type="submit" />';
              form.method = "post";
              form.action = href;
              form.target = link.target;
              form.innerHTML = formContent;
              form.style.display = "none";
              document.body.appendChild(form);
              form.querySelector('[type="submit"]').click();
              return stopEverything(e2);
            };
          }).call(this);
          (function() {
            var ajax, fire, getData, isCrossDomain, isRemote, matches, serializeElement, setData, stopEverything, slice = [].slice;
            matches = Rails2.matches, getData = Rails2.getData, setData = Rails2.setData, fire = Rails2.fire, stopEverything = Rails2.stopEverything, ajax = Rails2.ajax, isCrossDomain = Rails2.isCrossDomain, serializeElement = Rails2.serializeElement;
            isRemote = function(element) {
              var value;
              value = element.getAttribute("data-remote");
              return value != null && value !== "false";
            };
            Rails2.handleRemote = function(e2) {
              var button, data, dataType, element, method, url, withCredentials;
              element = this;
              if (!isRemote(element)) {
                return true;
              }
              if (!fire(element, "ajax:before")) {
                fire(element, "ajax:stopped");
                return false;
              }
              withCredentials = element.getAttribute("data-with-credentials");
              dataType = element.getAttribute("data-type") || "script";
              if (matches(element, Rails2.formSubmitSelector)) {
                button = getData(element, "ujs:submit-button");
                method = getData(element, "ujs:submit-button-formmethod") || element.method;
                url = getData(element, "ujs:submit-button-formaction") || element.getAttribute("action") || location.href;
                if (method.toUpperCase() === "GET") {
                  url = url.replace(/\?.*$/, "");
                }
                if (element.enctype === "multipart/form-data") {
                  data = new FormData(element);
                  if (button != null) {
                    data.append(button.name, button.value);
                  }
                } else {
                  data = serializeElement(element, button);
                }
                setData(element, "ujs:submit-button", null);
                setData(element, "ujs:submit-button-formmethod", null);
                setData(element, "ujs:submit-button-formaction", null);
              } else if (matches(element, Rails2.buttonClickSelector) || matches(element, Rails2.inputChangeSelector)) {
                method = element.getAttribute("data-method");
                url = element.getAttribute("data-url");
                data = serializeElement(element, element.getAttribute("data-params"));
              } else {
                method = element.getAttribute("data-method");
                url = Rails2.href(element);
                data = element.getAttribute("data-params");
              }
              ajax({
                type: method || "GET",
                url,
                data,
                dataType,
                beforeSend: function(xhr, options) {
                  if (fire(element, "ajax:beforeSend", [xhr, options])) {
                    return fire(element, "ajax:send", [xhr]);
                  } else {
                    fire(element, "ajax:stopped");
                    return false;
                  }
                },
                success: function() {
                  var args;
                  args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
                  return fire(element, "ajax:success", args);
                },
                error: function() {
                  var args;
                  args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
                  return fire(element, "ajax:error", args);
                },
                complete: function() {
                  var args;
                  args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
                  return fire(element, "ajax:complete", args);
                },
                crossDomain: isCrossDomain(url),
                withCredentials: withCredentials != null && withCredentials !== "false"
              });
              return stopEverything(e2);
            };
            Rails2.formSubmitButtonClick = function(e2) {
              var button, form;
              button = this;
              form = button.form;
              if (!form) {
                return;
              }
              if (button.name) {
                setData(form, "ujs:submit-button", {
                  name: button.name,
                  value: button.value
                });
              }
              setData(form, "ujs:formnovalidate-button", button.formNoValidate);
              setData(form, "ujs:submit-button-formaction", button.getAttribute("formaction"));
              return setData(form, "ujs:submit-button-formmethod", button.getAttribute("formmethod"));
            };
            Rails2.preventInsignificantClick = function(e2) {
              var data, insignificantMetaClick, link, metaClick, method, nonPrimaryMouseClick;
              link = this;
              method = (link.getAttribute("data-method") || "GET").toUpperCase();
              data = link.getAttribute("data-params");
              metaClick = e2.metaKey || e2.ctrlKey;
              insignificantMetaClick = metaClick && method === "GET" && !data;
              nonPrimaryMouseClick = e2.button != null && e2.button !== 0;
              if (nonPrimaryMouseClick || insignificantMetaClick) {
                return e2.stopImmediatePropagation();
              }
            };
          }).call(this);
          (function() {
            var $2, CSRFProtection, delegate, disableElement, enableElement, fire, formSubmitButtonClick, getData, handleConfirm, handleDisabledElement, handleMethod, handleRemote, loadCSPNonce, preventInsignificantClick, refreshCSRFTokens;
            fire = Rails2.fire, delegate = Rails2.delegate, getData = Rails2.getData, $2 = Rails2.$, refreshCSRFTokens = Rails2.refreshCSRFTokens, CSRFProtection = Rails2.CSRFProtection, loadCSPNonce = Rails2.loadCSPNonce, enableElement = Rails2.enableElement, disableElement = Rails2.disableElement, handleDisabledElement = Rails2.handleDisabledElement, handleConfirm = Rails2.handleConfirm, preventInsignificantClick = Rails2.preventInsignificantClick, handleRemote = Rails2.handleRemote, formSubmitButtonClick = Rails2.formSubmitButtonClick, handleMethod = Rails2.handleMethod;
            if (typeof jQuery !== "undefined" && jQuery !== null && jQuery.ajax != null) {
              if (jQuery.rails) {
                throw new Error("If you load both jquery_ujs and rails-ujs, use rails-ujs only.");
              }
              jQuery.rails = Rails2;
              jQuery.ajaxPrefilter(function(options, originalOptions, xhr) {
                if (!options.crossDomain) {
                  return CSRFProtection(xhr);
                }
              });
            }
            Rails2.start = function() {
              if (window._rails_loaded) {
                throw new Error("rails-ujs has already been loaded!");
              }
              window.addEventListener("pageshow", function() {
                $2(Rails2.formEnableSelector).forEach(function(el) {
                  if (getData(el, "ujs:disabled")) {
                    return enableElement(el);
                  }
                });
                return $2(Rails2.linkDisableSelector).forEach(function(el) {
                  if (getData(el, "ujs:disabled")) {
                    return enableElement(el);
                  }
                });
              });
              delegate(document, Rails2.linkDisableSelector, "ajax:complete", enableElement);
              delegate(document, Rails2.linkDisableSelector, "ajax:stopped", enableElement);
              delegate(document, Rails2.buttonDisableSelector, "ajax:complete", enableElement);
              delegate(document, Rails2.buttonDisableSelector, "ajax:stopped", enableElement);
              delegate(document, Rails2.linkClickSelector, "click", preventInsignificantClick);
              delegate(document, Rails2.linkClickSelector, "click", handleDisabledElement);
              delegate(document, Rails2.linkClickSelector, "click", handleConfirm);
              delegate(document, Rails2.linkClickSelector, "click", disableElement);
              delegate(document, Rails2.linkClickSelector, "click", handleRemote);
              delegate(document, Rails2.linkClickSelector, "click", handleMethod);
              delegate(document, Rails2.buttonClickSelector, "click", preventInsignificantClick);
              delegate(document, Rails2.buttonClickSelector, "click", handleDisabledElement);
              delegate(document, Rails2.buttonClickSelector, "click", handleConfirm);
              delegate(document, Rails2.buttonClickSelector, "click", disableElement);
              delegate(document, Rails2.buttonClickSelector, "click", handleRemote);
              delegate(document, Rails2.inputChangeSelector, "change", handleDisabledElement);
              delegate(document, Rails2.inputChangeSelector, "change", handleConfirm);
              delegate(document, Rails2.inputChangeSelector, "change", handleRemote);
              delegate(document, Rails2.formSubmitSelector, "submit", handleDisabledElement);
              delegate(document, Rails2.formSubmitSelector, "submit", handleConfirm);
              delegate(document, Rails2.formSubmitSelector, "submit", handleRemote);
              delegate(document, Rails2.formSubmitSelector, "submit", function(e2) {
                return setTimeout(function() {
                  return disableElement(e2);
                }, 13);
              });
              delegate(document, Rails2.formSubmitSelector, "ajax:send", disableElement);
              delegate(document, Rails2.formSubmitSelector, "ajax:complete", enableElement);
              delegate(document, Rails2.formInputClickSelector, "click", preventInsignificantClick);
              delegate(document, Rails2.formInputClickSelector, "click", handleDisabledElement);
              delegate(document, Rails2.formInputClickSelector, "click", handleConfirm);
              delegate(document, Rails2.formInputClickSelector, "click", formSubmitButtonClick);
              document.addEventListener("DOMContentLoaded", refreshCSRFTokens);
              document.addEventListener("DOMContentLoaded", loadCSPNonce);
              return window._rails_loaded = true;
            };
            if (window.Rails === Rails2 && fire(document, "rails:attachBindings")) {
              Rails2.start();
            }
          }).call(this);
        }).call(this);
        if (typeof module === "object" && module.exports) {
          module.exports = Rails2;
        } else if (typeof define === "function" && define.amd) {
          define(Rails2);
        }
      }).call(exports);
    }
  });

  // ../../node_modules/tinymce/tinymce.js
  var require_tinymce = __commonJS({
    "../../node_modules/tinymce/tinymce.js"(exports, module) {
      (function() {
        "use strict";
        var typeOf$1 = function(x2) {
          if (x2 === null) {
            return "null";
          }
          if (x2 === void 0) {
            return "undefined";
          }
          var t2 = typeof x2;
          if (t2 === "object" && (Array.prototype.isPrototypeOf(x2) || x2.constructor && x2.constructor.name === "Array")) {
            return "array";
          }
          if (t2 === "object" && (String.prototype.isPrototypeOf(x2) || x2.constructor && x2.constructor.name === "String")) {
            return "string";
          }
          return t2;
        };
        var isEquatableType = function(x2) {
          return [
            "undefined",
            "boolean",
            "number",
            "string",
            "function",
            "xml",
            "null"
          ].indexOf(x2) !== -1;
        };
        var sort$1 = function(xs, compareFn) {
          var clone3 = Array.prototype.slice.call(xs);
          return clone3.sort(compareFn);
        };
        var contramap = function(eqa, f2) {
          return eq$2(function(x2, y2) {
            return eqa.eq(f2(x2), f2(y2));
          });
        };
        var eq$2 = function(f2) {
          return { eq: f2 };
        };
        var tripleEq = eq$2(function(x2, y2) {
          return x2 === y2;
        });
        var eqString = tripleEq;
        var eqArray = function(eqa) {
          return eq$2(function(x2, y2) {
            if (x2.length !== y2.length) {
              return false;
            }
            var len = x2.length;
            for (var i2 = 0; i2 < len; i2++) {
              if (!eqa.eq(x2[i2], y2[i2])) {
                return false;
              }
            }
            return true;
          });
        };
        var eqSortedArray = function(eqa, compareFn) {
          return contramap(eqArray(eqa), function(xs) {
            return sort$1(xs, compareFn);
          });
        };
        var eqRecord = function(eqa) {
          return eq$2(function(x2, y2) {
            var kx = Object.keys(x2);
            var ky = Object.keys(y2);
            if (!eqSortedArray(eqString).eq(kx, ky)) {
              return false;
            }
            var len = kx.length;
            for (var i2 = 0; i2 < len; i2++) {
              var q2 = kx[i2];
              if (!eqa.eq(x2[q2], y2[q2])) {
                return false;
              }
            }
            return true;
          });
        };
        var eqAny = eq$2(function(x2, y2) {
          if (x2 === y2) {
            return true;
          }
          var tx = typeOf$1(x2);
          var ty = typeOf$1(y2);
          if (tx !== ty) {
            return false;
          }
          if (isEquatableType(tx)) {
            return x2 === y2;
          } else if (tx === "array") {
            return eqArray(eqAny).eq(x2, y2);
          } else if (tx === "object") {
            return eqRecord(eqAny).eq(x2, y2);
          }
          return false;
        });
        var typeOf = function(x2) {
          var t2 = typeof x2;
          if (x2 === null) {
            return "null";
          } else if (t2 === "object" && (Array.prototype.isPrototypeOf(x2) || x2.constructor && x2.constructor.name === "Array")) {
            return "array";
          } else if (t2 === "object" && (String.prototype.isPrototypeOf(x2) || x2.constructor && x2.constructor.name === "String")) {
            return "string";
          } else {
            return t2;
          }
        };
        var isType$1 = function(type2) {
          return function(value2) {
            return typeOf(value2) === type2;
          };
        };
        var isSimpleType = function(type2) {
          return function(value2) {
            return typeof value2 === type2;
          };
        };
        var eq$1 = function(t2) {
          return function(a2) {
            return t2 === a2;
          };
        };
        var isString$1 = isType$1("string");
        var isObject2 = isType$1("object");
        var isArray$1 = isType$1("array");
        var isNull = eq$1(null);
        var isBoolean = isSimpleType("boolean");
        var isUndefined = eq$1(void 0);
        var isNullable = function(a2) {
          return a2 === null || a2 === void 0;
        };
        var isNonNullable = function(a2) {
          return !isNullable(a2);
        };
        var isFunction2 = isSimpleType("function");
        var isNumber2 = isSimpleType("number");
        var noop3 = function() {
        };
        var compose = function(fa, fb) {
          return function() {
            var args = [];
            for (var _i2 = 0; _i2 < arguments.length; _i2++) {
              args[_i2] = arguments[_i2];
            }
            return fa(fb.apply(null, args));
          };
        };
        var compose1 = function(fbc, fab) {
          return function(a2) {
            return fbc(fab(a2));
          };
        };
        var constant = function(value2) {
          return function() {
            return value2;
          };
        };
        var identity = function(x2) {
          return x2;
        };
        var tripleEquals = function(a2, b2) {
          return a2 === b2;
        };
        function curry(fn3) {
          var initialArgs = [];
          for (var _i2 = 1; _i2 < arguments.length; _i2++) {
            initialArgs[_i2 - 1] = arguments[_i2];
          }
          return function() {
            var restArgs = [];
            for (var _i3 = 0; _i3 < arguments.length; _i3++) {
              restArgs[_i3] = arguments[_i3];
            }
            var all2 = initialArgs.concat(restArgs);
            return fn3.apply(null, all2);
          };
        }
        var not = function(f2) {
          return function(t2) {
            return !f2(t2);
          };
        };
        var die = function(msg) {
          return function() {
            throw new Error(msg);
          };
        };
        var apply = function(f2) {
          return f2();
        };
        var call = function(f2) {
          f2();
        };
        var never = constant(false);
        var always = constant(true);
        var none = function() {
          return NONE;
        };
        var NONE = function() {
          var call2 = function(thunk) {
            return thunk();
          };
          var id2 = identity;
          var me2 = {
            fold: function(n2, _s) {
              return n2();
            },
            isSome: never,
            isNone: always,
            getOr: id2,
            getOrThunk: call2,
            getOrDie: function(msg) {
              throw new Error(msg || "error: getOrDie called on none.");
            },
            getOrNull: constant(null),
            getOrUndefined: constant(void 0),
            or: id2,
            orThunk: call2,
            map: none,
            each: noop3,
            bind: none,
            exists: never,
            forall: always,
            filter: function() {
              return none();
            },
            toArray: function() {
              return [];
            },
            toString: constant("none()")
          };
          return me2;
        }();
        var some = function(a2) {
          var constant_a = constant(a2);
          var self2 = function() {
            return me2;
          };
          var bind2 = function(f2) {
            return f2(a2);
          };
          var me2 = {
            fold: function(n2, s2) {
              return s2(a2);
            },
            isSome: always,
            isNone: never,
            getOr: constant_a,
            getOrThunk: constant_a,
            getOrDie: constant_a,
            getOrNull: constant_a,
            getOrUndefined: constant_a,
            or: self2,
            orThunk: self2,
            map: function(f2) {
              return some(f2(a2));
            },
            each: function(f2) {
              f2(a2);
            },
            bind: bind2,
            exists: bind2,
            forall: bind2,
            filter: function(f2) {
              return f2(a2) ? me2 : NONE;
            },
            toArray: function() {
              return [a2];
            },
            toString: function() {
              return "some(" + a2 + ")";
            }
          };
          return me2;
        };
        var from$1 = function(value2) {
          return value2 === null || value2 === void 0 ? NONE : some(value2);
        };
        var Optional = {
          some,
          none,
          from: from$1
        };
        var nativeSlice = Array.prototype.slice;
        var nativeIndexOf = Array.prototype.indexOf;
        var nativePush = Array.prototype.push;
        var rawIndexOf = function(ts, t2) {
          return nativeIndexOf.call(ts, t2);
        };
        var indexOf$2 = function(xs, x2) {
          var r3 = rawIndexOf(xs, x2);
          return r3 === -1 ? Optional.none() : Optional.some(r3);
        };
        var contains$3 = function(xs, x2) {
          return rawIndexOf(xs, x2) > -1;
        };
        var exists = function(xs, pred) {
          for (var i2 = 0, len = xs.length; i2 < len; i2++) {
            var x2 = xs[i2];
            if (pred(x2, i2)) {
              return true;
            }
          }
          return false;
        };
        var map$3 = function(xs, f2) {
          var len = xs.length;
          var r3 = new Array(len);
          for (var i2 = 0; i2 < len; i2++) {
            var x2 = xs[i2];
            r3[i2] = f2(x2, i2);
          }
          return r3;
        };
        var each$k = function(xs, f2) {
          for (var i2 = 0, len = xs.length; i2 < len; i2++) {
            var x2 = xs[i2];
            f2(x2, i2);
          }
        };
        var eachr = function(xs, f2) {
          for (var i2 = xs.length - 1; i2 >= 0; i2--) {
            var x2 = xs[i2];
            f2(x2, i2);
          }
        };
        var partition = function(xs, pred) {
          var pass = [];
          var fail = [];
          for (var i2 = 0, len = xs.length; i2 < len; i2++) {
            var x2 = xs[i2];
            var arr2 = pred(x2, i2) ? pass : fail;
            arr2.push(x2);
          }
          return {
            pass,
            fail
          };
        };
        var filter$4 = function(xs, pred) {
          var r3 = [];
          for (var i2 = 0, len = xs.length; i2 < len; i2++) {
            var x2 = xs[i2];
            if (pred(x2, i2)) {
              r3.push(x2);
            }
          }
          return r3;
        };
        var foldr = function(xs, f2, acc) {
          eachr(xs, function(x2, i2) {
            acc = f2(acc, x2, i2);
          });
          return acc;
        };
        var foldl = function(xs, f2, acc) {
          each$k(xs, function(x2, i2) {
            acc = f2(acc, x2, i2);
          });
          return acc;
        };
        var findUntil$1 = function(xs, pred, until) {
          for (var i2 = 0, len = xs.length; i2 < len; i2++) {
            var x2 = xs[i2];
            if (pred(x2, i2)) {
              return Optional.some(x2);
            } else if (until(x2, i2)) {
              break;
            }
          }
          return Optional.none();
        };
        var find$3 = function(xs, pred) {
          return findUntil$1(xs, pred, never);
        };
        var findIndex$2 = function(xs, pred) {
          for (var i2 = 0, len = xs.length; i2 < len; i2++) {
            var x2 = xs[i2];
            if (pred(x2, i2)) {
              return Optional.some(i2);
            }
          }
          return Optional.none();
        };
        var flatten = function(xs) {
          var r3 = [];
          for (var i2 = 0, len = xs.length; i2 < len; ++i2) {
            if (!isArray$1(xs[i2])) {
              throw new Error("Arr.flatten item " + i2 + " was not an array, input: " + xs);
            }
            nativePush.apply(r3, xs[i2]);
          }
          return r3;
        };
        var bind = function(xs, f2) {
          return flatten(map$3(xs, f2));
        };
        var forall = function(xs, pred) {
          for (var i2 = 0, len = xs.length; i2 < len; ++i2) {
            var x2 = xs[i2];
            if (pred(x2, i2) !== true) {
              return false;
            }
          }
          return true;
        };
        var reverse = function(xs) {
          var r3 = nativeSlice.call(xs, 0);
          r3.reverse();
          return r3;
        };
        var difference = function(a1, a2) {
          return filter$4(a1, function(x2) {
            return !contains$3(a2, x2);
          });
        };
        var mapToObject = function(xs, f2) {
          var r3 = {};
          for (var i2 = 0, len = xs.length; i2 < len; i2++) {
            var x2 = xs[i2];
            r3[String(x2)] = f2(x2, i2);
          }
          return r3;
        };
        var sort = function(xs, comparator) {
          var copy = nativeSlice.call(xs, 0);
          copy.sort(comparator);
          return copy;
        };
        var get$a = function(xs, i2) {
          return i2 >= 0 && i2 < xs.length ? Optional.some(xs[i2]) : Optional.none();
        };
        var head = function(xs) {
          return get$a(xs, 0);
        };
        var last$2 = function(xs) {
          return get$a(xs, xs.length - 1);
        };
        var from = isFunction2(Array.from) ? Array.from : function(x2) {
          return nativeSlice.call(x2);
        };
        var findMap = function(arr2, f2) {
          for (var i2 = 0; i2 < arr2.length; i2++) {
            var r3 = f2(arr2[i2], i2);
            if (r3.isSome()) {
              return r3;
            }
          }
          return Optional.none();
        };
        var keys = Object.keys;
        var hasOwnProperty$1 = Object.hasOwnProperty;
        var each$j = function(obj, f2) {
          var props = keys(obj);
          for (var k2 = 0, len = props.length; k2 < len; k2++) {
            var i2 = props[k2];
            var x2 = obj[i2];
            f2(x2, i2);
          }
        };
        var map$2 = function(obj, f2) {
          return tupleMap(obj, function(x2, i2) {
            return {
              k: i2,
              v: f2(x2, i2)
            };
          });
        };
        var tupleMap = function(obj, f2) {
          var r3 = {};
          each$j(obj, function(x2, i2) {
            var tuple = f2(x2, i2);
            r3[tuple.k] = tuple.v;
          });
          return r3;
        };
        var objAcc = function(r3) {
          return function(x2, i2) {
            r3[i2] = x2;
          };
        };
        var internalFilter = function(obj, pred, onTrue, onFalse) {
          var r3 = {};
          each$j(obj, function(x2, i2) {
            (pred(x2, i2) ? onTrue : onFalse)(x2, i2);
          });
          return r3;
        };
        var bifilter = function(obj, pred) {
          var t2 = {};
          var f2 = {};
          internalFilter(obj, pred, objAcc(t2), objAcc(f2));
          return {
            t: t2,
            f: f2
          };
        };
        var filter$3 = function(obj, pred) {
          var t2 = {};
          internalFilter(obj, pred, objAcc(t2), noop3);
          return t2;
        };
        var mapToArray = function(obj, f2) {
          var r3 = [];
          each$j(obj, function(value2, name2) {
            r3.push(f2(value2, name2));
          });
          return r3;
        };
        var values = function(obj) {
          return mapToArray(obj, identity);
        };
        var get$9 = function(obj, key) {
          return has$2(obj, key) ? Optional.from(obj[key]) : Optional.none();
        };
        var has$2 = function(obj, key) {
          return hasOwnProperty$1.call(obj, key);
        };
        var hasNonNullableKey = function(obj, key) {
          return has$2(obj, key) && obj[key] !== void 0 && obj[key] !== null;
        };
        var equal$1 = function(a1, a2, eq3) {
          if (eq3 === void 0) {
            eq3 = eqAny;
          }
          return eqRecord(eq3).eq(a1, a2);
        };
        var isArray2 = Array.isArray;
        var toArray$1 = function(obj) {
          if (!isArray2(obj)) {
            var array = [];
            for (var i2 = 0, l2 = obj.length; i2 < l2; i2++) {
              array[i2] = obj[i2];
            }
            return array;
          } else {
            return obj;
          }
        };
        var each$i = function(o2, cb, s2) {
          var n2, l2;
          if (!o2) {
            return false;
          }
          s2 = s2 || o2;
          if (o2.length !== void 0) {
            for (n2 = 0, l2 = o2.length; n2 < l2; n2++) {
              if (cb.call(s2, o2[n2], n2, o2) === false) {
                return false;
              }
            }
          } else {
            for (n2 in o2) {
              if (has$2(o2, n2)) {
                if (cb.call(s2, o2[n2], n2, o2) === false) {
                  return false;
                }
              }
            }
          }
          return true;
        };
        var map$12 = function(array, callback2) {
          var out = [];
          each$i(array, function(item, index) {
            out.push(callback2(item, index, array));
          });
          return out;
        };
        var filter$2 = function(a2, f2) {
          var o2 = [];
          each$i(a2, function(v2, index) {
            if (!f2 || f2(v2, index, a2)) {
              o2.push(v2);
            }
          });
          return o2;
        };
        var indexOf$1 = function(a2, v2) {
          if (a2) {
            for (var i2 = 0, l2 = a2.length; i2 < l2; i2++) {
              if (a2[i2] === v2) {
                return i2;
              }
            }
          }
          return -1;
        };
        var reduce = function(collection, iteratee, accumulator, thisArg) {
          var acc = isUndefined(accumulator) ? collection[0] : accumulator;
          for (var i2 = 0; i2 < collection.length; i2++) {
            acc = iteratee.call(thisArg, acc, collection[i2], i2);
          }
          return acc;
        };
        var findIndex$1 = function(array, predicate, thisArg) {
          var i2, l2;
          for (i2 = 0, l2 = array.length; i2 < l2; i2++) {
            if (predicate.call(thisArg, array[i2], i2, array)) {
              return i2;
            }
          }
          return -1;
        };
        var last$1 = function(collection) {
          return collection[collection.length - 1];
        };
        var __assign = function() {
          __assign = Object.assign || function __assign2(t2) {
            for (var s2, i2 = 1, n2 = arguments.length; i2 < n2; i2++) {
              s2 = arguments[i2];
              for (var p2 in s2)
                if (Object.prototype.hasOwnProperty.call(s2, p2))
                  t2[p2] = s2[p2];
            }
            return t2;
          };
          return __assign.apply(this, arguments);
        };
        function __rest(s2, e2) {
          var t2 = {};
          for (var p2 in s2)
            if (Object.prototype.hasOwnProperty.call(s2, p2) && e2.indexOf(p2) < 0)
              t2[p2] = s2[p2];
          if (s2 != null && typeof Object.getOwnPropertySymbols === "function")
            for (var i2 = 0, p2 = Object.getOwnPropertySymbols(s2); i2 < p2.length; i2++) {
              if (e2.indexOf(p2[i2]) < 0 && Object.prototype.propertyIsEnumerable.call(s2, p2[i2]))
                t2[p2[i2]] = s2[p2[i2]];
            }
          return t2;
        }
        function __spreadArray(to2, from2, pack) {
          if (pack || arguments.length === 2)
            for (var i2 = 0, l2 = from2.length, ar; i2 < l2; i2++) {
              if (ar || !(i2 in from2)) {
                if (!ar)
                  ar = Array.prototype.slice.call(from2, 0, i2);
                ar[i2] = from2[i2];
              }
            }
          return to2.concat(ar || Array.prototype.slice.call(from2));
        }
        var cached = function(f2) {
          var called = false;
          var r3;
          return function() {
            var args = [];
            for (var _i2 = 0; _i2 < arguments.length; _i2++) {
              args[_i2] = arguments[_i2];
            }
            if (!called) {
              called = true;
              r3 = f2.apply(null, args);
            }
            return r3;
          };
        };
        var DeviceType = function(os2, browser2, userAgent2, mediaMatch2) {
          var isiPad = os2.isiOS() && /ipad/i.test(userAgent2) === true;
          var isiPhone = os2.isiOS() && !isiPad;
          var isMobile = os2.isiOS() || os2.isAndroid();
          var isTouch2 = isMobile || mediaMatch2("(pointer:coarse)");
          var isTablet2 = isiPad || !isiPhone && isMobile && mediaMatch2("(min-device-width:768px)");
          var isPhone2 = isiPhone || isMobile && !isTablet2;
          var iOSwebview = browser2.isSafari() && os2.isiOS() && /safari/i.test(userAgent2) === false;
          var isDesktop = !isPhone2 && !isTablet2 && !iOSwebview;
          return {
            isiPad: constant(isiPad),
            isiPhone: constant(isiPhone),
            isTablet: constant(isTablet2),
            isPhone: constant(isPhone2),
            isTouch: constant(isTouch2),
            isAndroid: os2.isAndroid,
            isiOS: os2.isiOS,
            isWebView: constant(iOSwebview),
            isDesktop: constant(isDesktop)
          };
        };
        var firstMatch = function(regexes, s2) {
          for (var i2 = 0; i2 < regexes.length; i2++) {
            var x2 = regexes[i2];
            if (x2.test(s2)) {
              return x2;
            }
          }
          return void 0;
        };
        var find$2 = function(regexes, agent) {
          var r3 = firstMatch(regexes, agent);
          if (!r3) {
            return {
              major: 0,
              minor: 0
            };
          }
          var group = function(i2) {
            return Number(agent.replace(r3, "$" + i2));
          };
          return nu$4(group(1), group(2));
        };
        var detect$3 = function(versionRegexes, agent) {
          var cleanedAgent = String(agent).toLowerCase();
          if (versionRegexes.length === 0) {
            return unknown$2();
          }
          return find$2(versionRegexes, cleanedAgent);
        };
        var unknown$2 = function() {
          return nu$4(0, 0);
        };
        var nu$4 = function(major, minor) {
          return {
            major,
            minor
          };
        };
        var Version = {
          nu: nu$4,
          detect: detect$3,
          unknown: unknown$2
        };
        var detectBrowser$1 = function(browsers2, userAgentData) {
          return findMap(userAgentData.brands, function(uaBrand) {
            var lcBrand = uaBrand.brand.toLowerCase();
            return find$3(browsers2, function(browser2) {
              var _a;
              return lcBrand === ((_a = browser2.brand) === null || _a === void 0 ? void 0 : _a.toLowerCase());
            }).map(function(info) {
              return {
                current: info.name,
                version: Version.nu(parseInt(uaBrand.version, 10), 0)
              };
            });
          });
        };
        var detect$2 = function(candidates, userAgent2) {
          var agent = String(userAgent2).toLowerCase();
          return find$3(candidates, function(candidate) {
            return candidate.search(agent);
          });
        };
        var detectBrowser = function(browsers2, userAgent2) {
          return detect$2(browsers2, userAgent2).map(function(browser2) {
            var version2 = Version.detect(browser2.versionRegexes, userAgent2);
            return {
              current: browser2.name,
              version: version2
            };
          });
        };
        var detectOs = function(oses2, userAgent2) {
          return detect$2(oses2, userAgent2).map(function(os2) {
            var version2 = Version.detect(os2.versionRegexes, userAgent2);
            return {
              current: os2.name,
              version: version2
            };
          });
        };
        var removeFromStart = function(str, numChars) {
          return str.substring(numChars);
        };
        var checkRange = function(str, substr, start5) {
          return substr === "" || str.length >= substr.length && str.substr(start5, start5 + substr.length) === substr;
        };
        var removeLeading = function(str, prefix) {
          return startsWith(str, prefix) ? removeFromStart(str, prefix.length) : str;
        };
        var contains$2 = function(str, substr) {
          return str.indexOf(substr) !== -1;
        };
        var startsWith = function(str, prefix) {
          return checkRange(str, prefix, 0);
        };
        var blank = function(r3) {
          return function(s2) {
            return s2.replace(r3, "");
          };
        };
        var trim$4 = blank(/^\s+|\s+$/g);
        var lTrim = blank(/^\s+/g);
        var rTrim = blank(/\s+$/g);
        var isNotEmpty = function(s2) {
          return s2.length > 0;
        };
        var isEmpty$3 = function(s2) {
          return !isNotEmpty(s2);
        };
        var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/;
        var checkContains = function(target) {
          return function(uastring) {
            return contains$2(uastring, target);
          };
        };
        var browsers = [
          {
            name: "Edge",
            versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],
            search: function(uastring) {
              return contains$2(uastring, "edge/") && contains$2(uastring, "chrome") && contains$2(uastring, "safari") && contains$2(uastring, "applewebkit");
            }
          },
          {
            name: "Chrome",
            brand: "Chromium",
            versionRegexes: [
              /.*?chrome\/([0-9]+)\.([0-9]+).*/,
              normalVersionRegex
            ],
            search: function(uastring) {
              return contains$2(uastring, "chrome") && !contains$2(uastring, "chromeframe");
            }
          },
          {
            name: "IE",
            versionRegexes: [
              /.*?msie\ ?([0-9]+)\.([0-9]+).*/,
              /.*?rv:([0-9]+)\.([0-9]+).*/
            ],
            search: function(uastring) {
              return contains$2(uastring, "msie") || contains$2(uastring, "trident");
            }
          },
          {
            name: "Opera",
            versionRegexes: [
              normalVersionRegex,
              /.*?opera\/([0-9]+)\.([0-9]+).*/
            ],
            search: checkContains("opera")
          },
          {
            name: "Firefox",
            versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],
            search: checkContains("firefox")
          },
          {
            name: "Safari",
            versionRegexes: [
              normalVersionRegex,
              /.*?cpu os ([0-9]+)_([0-9]+).*/
            ],
            search: function(uastring) {
              return (contains$2(uastring, "safari") || contains$2(uastring, "mobile/")) && contains$2(uastring, "applewebkit");
            }
          }
        ];
        var oses = [
          {
            name: "Windows",
            search: checkContains("win"),
            versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]
          },
          {
            name: "iOS",
            search: function(uastring) {
              return contains$2(uastring, "iphone") || contains$2(uastring, "ipad");
            },
            versionRegexes: [
              /.*?version\/\ ?([0-9]+)\.([0-9]+).*/,
              /.*cpu os ([0-9]+)_([0-9]+).*/,
              /.*cpu iphone os ([0-9]+)_([0-9]+).*/
            ]
          },
          {
            name: "Android",
            search: checkContains("android"),
            versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/]
          },
          {
            name: "OSX",
            search: checkContains("mac os x"),
            versionRegexes: [/.*?mac\ os\ x\ ?([0-9]+)_([0-9]+).*/]
          },
          {
            name: "Linux",
            search: checkContains("linux"),
            versionRegexes: []
          },
          {
            name: "Solaris",
            search: checkContains("sunos"),
            versionRegexes: []
          },
          {
            name: "FreeBSD",
            search: checkContains("freebsd"),
            versionRegexes: []
          },
          {
            name: "ChromeOS",
            search: checkContains("cros"),
            versionRegexes: [/.*?chrome\/([0-9]+)\.([0-9]+).*/]
          }
        ];
        var PlatformInfo = {
          browsers: constant(browsers),
          oses: constant(oses)
        };
        var edge = "Edge";
        var chrome = "Chrome";
        var ie$1 = "IE";
        var opera = "Opera";
        var firefox = "Firefox";
        var safari = "Safari";
        var unknown$1 = function() {
          return nu$3({
            current: void 0,
            version: Version.unknown()
          });
        };
        var nu$3 = function(info) {
          var current = info.current;
          var version2 = info.version;
          var isBrowser = function(name2) {
            return function() {
              return current === name2;
            };
          };
          return {
            current,
            version: version2,
            isEdge: isBrowser(edge),
            isChrome: isBrowser(chrome),
            isIE: isBrowser(ie$1),
            isOpera: isBrowser(opera),
            isFirefox: isBrowser(firefox),
            isSafari: isBrowser(safari)
          };
        };
        var Browser = {
          unknown: unknown$1,
          nu: nu$3,
          edge: constant(edge),
          chrome: constant(chrome),
          ie: constant(ie$1),
          opera: constant(opera),
          firefox: constant(firefox),
          safari: constant(safari)
        };
        var windows = "Windows";
        var ios = "iOS";
        var android = "Android";
        var linux = "Linux";
        var osx = "OSX";
        var solaris = "Solaris";
        var freebsd = "FreeBSD";
        var chromeos = "ChromeOS";
        var unknown = function() {
          return nu$2({
            current: void 0,
            version: Version.unknown()
          });
        };
        var nu$2 = function(info) {
          var current = info.current;
          var version2 = info.version;
          var isOS = function(name2) {
            return function() {
              return current === name2;
            };
          };
          return {
            current,
            version: version2,
            isWindows: isOS(windows),
            isiOS: isOS(ios),
            isAndroid: isOS(android),
            isOSX: isOS(osx),
            isLinux: isOS(linux),
            isSolaris: isOS(solaris),
            isFreeBSD: isOS(freebsd),
            isChromeOS: isOS(chromeos)
          };
        };
        var OperatingSystem = {
          unknown,
          nu: nu$2,
          windows: constant(windows),
          ios: constant(ios),
          android: constant(android),
          linux: constant(linux),
          osx: constant(osx),
          solaris: constant(solaris),
          freebsd: constant(freebsd),
          chromeos: constant(chromeos)
        };
        var detect$1 = function(userAgent2, userAgentDataOpt, mediaMatch2) {
          var browsers2 = PlatformInfo.browsers();
          var oses2 = PlatformInfo.oses();
          var browser2 = userAgentDataOpt.bind(function(userAgentData) {
            return detectBrowser$1(browsers2, userAgentData);
          }).orThunk(function() {
            return detectBrowser(browsers2, userAgent2);
          }).fold(Browser.unknown, Browser.nu);
          var os2 = detectOs(oses2, userAgent2).fold(OperatingSystem.unknown, OperatingSystem.nu);
          var deviceType2 = DeviceType(os2, browser2, userAgent2, mediaMatch2);
          return {
            browser: browser2,
            os: os2,
            deviceType: deviceType2
          };
        };
        var PlatformDetection = { detect: detect$1 };
        var mediaMatch = function(query) {
          return window.matchMedia(query).matches;
        };
        var platform$2 = cached(function() {
          return PlatformDetection.detect(navigator.userAgent, Optional.from(navigator.userAgentData), mediaMatch);
        });
        var detect = function() {
          return platform$2();
        };
        var userAgent = navigator.userAgent;
        var platform$1 = detect();
        var browser$4 = platform$1.browser;
        var os = platform$1.os;
        var deviceType = platform$1.deviceType;
        var webkit = /WebKit/.test(userAgent) && !browser$4.isEdge();
        var fileApi = "FormData" in window && "FileReader" in window && "URL" in window && !!URL.createObjectURL;
        var windowsPhone = userAgent.indexOf("Windows Phone") !== -1;
        var Env = {
          opera: browser$4.isOpera(),
          webkit,
          ie: browser$4.isIE() || browser$4.isEdge() ? browser$4.version.major : false,
          gecko: browser$4.isFirefox(),
          mac: os.isOSX() || os.isiOS(),
          iOS: deviceType.isiPad() || deviceType.isiPhone(),
          android: os.isAndroid(),
          contentEditable: true,
          transparentSrc: "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",
          caretAfter: true,
          range: window.getSelection && "Range" in window,
          documentMode: browser$4.isIE() ? document.documentMode || 7 : 10,
          fileApi,
          ceFalse: true,
          cacheSuffix: null,
          container: null,
          experimentalShadowDom: false,
          canHaveCSP: !browser$4.isIE(),
          desktop: deviceType.isDesktop(),
          windowsPhone,
          browser: {
            current: browser$4.current,
            version: browser$4.version,
            isChrome: browser$4.isChrome,
            isEdge: browser$4.isEdge,
            isFirefox: browser$4.isFirefox,
            isIE: browser$4.isIE,
            isOpera: browser$4.isOpera,
            isSafari: browser$4.isSafari
          },
          os: {
            current: os.current,
            version: os.version,
            isAndroid: os.isAndroid,
            isChromeOS: os.isChromeOS,
            isFreeBSD: os.isFreeBSD,
            isiOS: os.isiOS,
            isLinux: os.isLinux,
            isOSX: os.isOSX,
            isSolaris: os.isSolaris,
            isWindows: os.isWindows
          },
          deviceType: {
            isDesktop: deviceType.isDesktop,
            isiPad: deviceType.isiPad,
            isiPhone: deviceType.isiPhone,
            isPhone: deviceType.isPhone,
            isTablet: deviceType.isTablet,
            isTouch: deviceType.isTouch,
            isWebView: deviceType.isWebView
          }
        };
        var whiteSpaceRegExp$2 = /^\s*|\s*$/g;
        var trim$3 = function(str) {
          return str === null || str === void 0 ? "" : ("" + str).replace(whiteSpaceRegExp$2, "");
        };
        var is$3 = function(obj, type2) {
          if (!type2) {
            return obj !== void 0;
          }
          if (type2 === "array" && isArray2(obj)) {
            return true;
          }
          return typeof obj === type2;
        };
        var makeMap$4 = function(items, delim, map4) {
          var i2;
          items = items || [];
          delim = delim || ",";
          if (typeof items === "string") {
            items = items.split(delim);
          }
          map4 = map4 || {};
          i2 = items.length;
          while (i2--) {
            map4[items[i2]] = {};
          }
          return map4;
        };
        var hasOwnProperty = has$2;
        var create$9 = function(s2, p2, root) {
          var self2 = this;
          var sp, scn, c2, de2 = 0;
          s2 = /^((static) )?([\w.]+)(:([\w.]+))?/.exec(s2);
          var cn2 = s2[3].match(/(^|\.)(\w+)$/i)[2];
          var ns = self2.createNS(s2[3].replace(/\.\w+$/, ""), root);
          if (ns[cn2]) {
            return;
          }
          if (s2[2] === "static") {
            ns[cn2] = p2;
            if (this.onCreate) {
              this.onCreate(s2[2], s2[3], ns[cn2]);
            }
            return;
          }
          if (!p2[cn2]) {
            p2[cn2] = function() {
            };
            de2 = 1;
          }
          ns[cn2] = p2[cn2];
          self2.extend(ns[cn2].prototype, p2);
          if (s2[5]) {
            sp = self2.resolve(s2[5]).prototype;
            scn = s2[5].match(/\.(\w+)$/i)[1];
            c2 = ns[cn2];
            if (de2) {
              ns[cn2] = function() {
                return sp[scn].apply(this, arguments);
              };
            } else {
              ns[cn2] = function() {
                this.parent = sp[scn];
                return c2.apply(this, arguments);
              };
            }
            ns[cn2].prototype[cn2] = ns[cn2];
            self2.each(sp, function(f2, n2) {
              ns[cn2].prototype[n2] = sp[n2];
            });
            self2.each(p2, function(f2, n2) {
              if (sp[n2]) {
                ns[cn2].prototype[n2] = function() {
                  this.parent = sp[n2];
                  return f2.apply(this, arguments);
                };
              } else {
                if (n2 !== cn2) {
                  ns[cn2].prototype[n2] = f2;
                }
              }
            });
          }
          self2.each(p2.static, function(f2, n2) {
            ns[cn2][n2] = f2;
          });
        };
        var extend$6 = function(obj) {
          var exts = [];
          for (var _i2 = 1; _i2 < arguments.length; _i2++) {
            exts[_i2 - 1] = arguments[_i2];
          }
          for (var i2 = 0; i2 < exts.length; i2++) {
            var ext = exts[i2];
            for (var name_1 in ext) {
              if (has$2(ext, name_1)) {
                var value2 = ext[name_1];
                if (value2 !== void 0) {
                  obj[name_1] = value2;
                }
              }
            }
          }
          return obj;
        };
        var walk$3 = function(o2, f2, n2, s2) {
          s2 = s2 || this;
          if (o2) {
            if (n2) {
              o2 = o2[n2];
            }
            each$i(o2, function(o3, i2) {
              if (f2.call(s2, o3, i2, n2) === false) {
                return false;
              }
              walk$3(o3, f2, n2, s2);
            });
          }
        };
        var createNS = function(n2, o2) {
          var i2, v2;
          o2 = o2 || window;
          n2 = n2.split(".");
          for (i2 = 0; i2 < n2.length; i2++) {
            v2 = n2[i2];
            if (!o2[v2]) {
              o2[v2] = {};
            }
            o2 = o2[v2];
          }
          return o2;
        };
        var resolve$3 = function(n2, o2) {
          var i2, l2;
          o2 = o2 || window;
          n2 = n2.split(".");
          for (i2 = 0, l2 = n2.length; i2 < l2; i2++) {
            o2 = o2[n2[i2]];
            if (!o2) {
              break;
            }
          }
          return o2;
        };
        var explode$4 = function(s2, d2) {
          if (!s2 || is$3(s2, "array")) {
            return s2;
          }
          return map$12(s2.split(d2 || ","), trim$3);
        };
        var _addCacheSuffix = function(url) {
          var cacheSuffix = Env.cacheSuffix;
          if (cacheSuffix) {
            url += (url.indexOf("?") === -1 ? "?" : "&") + cacheSuffix;
          }
          return url;
        };
        var Tools = {
          trim: trim$3,
          isArray: isArray2,
          is: is$3,
          toArray: toArray$1,
          makeMap: makeMap$4,
          each: each$i,
          map: map$12,
          grep: filter$2,
          inArray: indexOf$1,
          hasOwn: hasOwnProperty,
          extend: extend$6,
          create: create$9,
          walk: walk$3,
          createNS,
          resolve: resolve$3,
          explode: explode$4,
          _addCacheSuffix
        };
        var fromHtml$1 = function(html, scope) {
          var doc2 = scope || document;
          var div = doc2.createElement("div");
          div.innerHTML = html;
          if (!div.hasChildNodes() || div.childNodes.length > 1) {
            console.error("HTML does not have a single root node", html);
            throw new Error("HTML must have a single root node");
          }
          return fromDom$2(div.childNodes[0]);
        };
        var fromTag = function(tag, scope) {
          var doc2 = scope || document;
          var node = doc2.createElement(tag);
          return fromDom$2(node);
        };
        var fromText = function(text, scope) {
          var doc2 = scope || document;
          var node = doc2.createTextNode(text);
          return fromDom$2(node);
        };
        var fromDom$2 = function(node) {
          if (node === null || node === void 0) {
            throw new Error("Node cannot be null or undefined");
          }
          return { dom: node };
        };
        var fromPoint$1 = function(docElm, x2, y2) {
          return Optional.from(docElm.dom.elementFromPoint(x2, y2)).map(fromDom$2);
        };
        var SugarElement = {
          fromHtml: fromHtml$1,
          fromTag,
          fromText,
          fromDom: fromDom$2,
          fromPoint: fromPoint$1
        };
        var toArray2 = function(target, f2) {
          var r3 = [];
          var recurse = function(e2) {
            r3.push(e2);
            return f2(e2);
          };
          var cur = f2(target);
          do {
            cur = cur.bind(recurse);
          } while (cur.isSome());
          return r3;
        };
        var compareDocumentPosition = function(a2, b2, match3) {
          return (a2.compareDocumentPosition(b2) & match3) !== 0;
        };
        var documentPositionContainedBy = function(a2, b2) {
          return compareDocumentPosition(a2, b2, Node.DOCUMENT_POSITION_CONTAINED_BY);
        };
        var COMMENT = 8;
        var DOCUMENT = 9;
        var DOCUMENT_FRAGMENT = 11;
        var ELEMENT = 1;
        var TEXT = 3;
        var is$2 = function(element, selector) {
          var dom2 = element.dom;
          if (dom2.nodeType !== ELEMENT) {
            return false;
          } else {
            var elem = dom2;
            if (elem.matches !== void 0) {
              return elem.matches(selector);
            } else if (elem.msMatchesSelector !== void 0) {
              return elem.msMatchesSelector(selector);
            } else if (elem.webkitMatchesSelector !== void 0) {
              return elem.webkitMatchesSelector(selector);
            } else if (elem.mozMatchesSelector !== void 0) {
              return elem.mozMatchesSelector(selector);
            } else {
              throw new Error("Browser lacks native selectors");
            }
          }
        };
        var bypassSelector = function(dom2) {
          return dom2.nodeType !== ELEMENT && dom2.nodeType !== DOCUMENT && dom2.nodeType !== DOCUMENT_FRAGMENT || dom2.childElementCount === 0;
        };
        var all = function(selector, scope) {
          var base = scope === void 0 ? document : scope.dom;
          return bypassSelector(base) ? [] : map$3(base.querySelectorAll(selector), SugarElement.fromDom);
        };
        var one = function(selector, scope) {
          var base = scope === void 0 ? document : scope.dom;
          return bypassSelector(base) ? Optional.none() : Optional.from(base.querySelector(selector)).map(SugarElement.fromDom);
        };
        var eq2 = function(e1, e2) {
          return e1.dom === e2.dom;
        };
        var regularContains = function(e1, e2) {
          var d1 = e1.dom;
          var d2 = e2.dom;
          return d1 === d2 ? false : d1.contains(d2);
        };
        var ieContains = function(e1, e2) {
          return documentPositionContainedBy(e1.dom, e2.dom);
        };
        var contains$1 = function(e1, e2) {
          return detect().browser.isIE() ? ieContains(e1, e2) : regularContains(e1, e2);
        };
        typeof window !== "undefined" ? window : Function("return this;")();
        var name = function(element) {
          var r3 = element.dom.nodeName;
          return r3.toLowerCase();
        };
        var type = function(element) {
          return element.dom.nodeType;
        };
        var isType = function(t2) {
          return function(element) {
            return type(element) === t2;
          };
        };
        var isComment$1 = function(element) {
          return type(element) === COMMENT || name(element) === "#comment";
        };
        var isElement$6 = isType(ELEMENT);
        var isText$8 = isType(TEXT);
        var isDocument$2 = isType(DOCUMENT);
        var isDocumentFragment$1 = isType(DOCUMENT_FRAGMENT);
        var isTag = function(tag) {
          return function(e2) {
            return isElement$6(e2) && name(e2) === tag;
          };
        };
        var owner$1 = function(element) {
          return SugarElement.fromDom(element.dom.ownerDocument);
        };
        var documentOrOwner = function(dos) {
          return isDocument$2(dos) ? dos : owner$1(dos);
        };
        var documentElement = function(element) {
          return SugarElement.fromDom(documentOrOwner(element).dom.documentElement);
        };
        var defaultView = function(element) {
          return SugarElement.fromDom(documentOrOwner(element).dom.defaultView);
        };
        var parent = function(element) {
          return Optional.from(element.dom.parentNode).map(SugarElement.fromDom);
        };
        var parents$1 = function(element, isRoot) {
          var stop2 = isFunction2(isRoot) ? isRoot : never;
          var dom2 = element.dom;
          var ret = [];
          while (dom2.parentNode !== null && dom2.parentNode !== void 0) {
            var rawParent = dom2.parentNode;
            var p2 = SugarElement.fromDom(rawParent);
            ret.push(p2);
            if (stop2(p2) === true) {
              break;
            } else {
              dom2 = rawParent;
            }
          }
          return ret;
        };
        var siblings = function(element) {
          var filterSelf = function(elements2) {
            return filter$4(elements2, function(x2) {
              return !eq2(element, x2);
            });
          };
          return parent(element).map(children).map(filterSelf).getOr([]);
        };
        var prevSibling = function(element) {
          return Optional.from(element.dom.previousSibling).map(SugarElement.fromDom);
        };
        var nextSibling = function(element) {
          return Optional.from(element.dom.nextSibling).map(SugarElement.fromDom);
        };
        var prevSiblings = function(element) {
          return reverse(toArray2(element, prevSibling));
        };
        var nextSiblings = function(element) {
          return toArray2(element, nextSibling);
        };
        var children = function(element) {
          return map$3(element.dom.childNodes, SugarElement.fromDom);
        };
        var child$1 = function(element, index) {
          var cs = element.dom.childNodes;
          return Optional.from(cs[index]).map(SugarElement.fromDom);
        };
        var firstChild = function(element) {
          return child$1(element, 0);
        };
        var lastChild = function(element) {
          return child$1(element, element.dom.childNodes.length - 1);
        };
        var childNodesCount = function(element) {
          return element.dom.childNodes.length;
        };
        var getHead = function(doc2) {
          var b2 = doc2.dom.head;
          if (b2 === null || b2 === void 0) {
            throw new Error("Head is not available yet");
          }
          return SugarElement.fromDom(b2);
        };
        var isShadowRoot2 = function(dos) {
          return isDocumentFragment$1(dos) && isNonNullable(dos.dom.host);
        };
        var supported = isFunction2(Element.prototype.attachShadow) && isFunction2(Node.prototype.getRootNode);
        var isSupported$1 = constant(supported);
        var getRootNode = supported ? function(e2) {
          return SugarElement.fromDom(e2.dom.getRootNode());
        } : documentOrOwner;
        var getStyleContainer = function(dos) {
          return isShadowRoot2(dos) ? dos : getHead(documentOrOwner(dos));
        };
        var getShadowRoot = function(e2) {
          var r3 = getRootNode(e2);
          return isShadowRoot2(r3) ? Optional.some(r3) : Optional.none();
        };
        var getShadowHost = function(e2) {
          return SugarElement.fromDom(e2.dom.host);
        };
        var getOriginalEventTarget = function(event) {
          if (isSupported$1() && isNonNullable(event.target)) {
            var el = SugarElement.fromDom(event.target);
            if (isElement$6(el) && isOpenShadowHost(el)) {
              if (event.composed && event.composedPath) {
                var composedPath = event.composedPath();
                if (composedPath) {
                  return head(composedPath);
                }
              }
            }
          }
          return Optional.from(event.target);
        };
        var isOpenShadowHost = function(element) {
          return isNonNullable(element.dom.shadowRoot);
        };
        var before$4 = function(marker, element) {
          var parent$1 = parent(marker);
          parent$1.each(function(v2) {
            v2.dom.insertBefore(element.dom, marker.dom);
          });
        };
        var after$3 = function(marker, element) {
          var sibling2 = nextSibling(marker);
          sibling2.fold(function() {
            var parent$1 = parent(marker);
            parent$1.each(function(v2) {
              append$1(v2, element);
            });
          }, function(v2) {
            before$4(v2, element);
          });
        };
        var prepend = function(parent2, element) {
          var firstChild$1 = firstChild(parent2);
          firstChild$1.fold(function() {
            append$1(parent2, element);
          }, function(v2) {
            parent2.dom.insertBefore(element.dom, v2.dom);
          });
        };
        var append$1 = function(parent2, element) {
          parent2.dom.appendChild(element.dom);
        };
        var wrap$3 = function(element, wrapper) {
          before$4(element, wrapper);
          append$1(wrapper, element);
        };
        var before$3 = function(marker, elements2) {
          each$k(elements2, function(x2) {
            before$4(marker, x2);
          });
        };
        var append = function(parent2, elements2) {
          each$k(elements2, function(x2) {
            append$1(parent2, x2);
          });
        };
        var empty = function(element) {
          element.dom.textContent = "";
          each$k(children(element), function(rogue) {
            remove$7(rogue);
          });
        };
        var remove$7 = function(element) {
          var dom2 = element.dom;
          if (dom2.parentNode !== null) {
            dom2.parentNode.removeChild(dom2);
          }
        };
        var unwrap = function(wrapper) {
          var children$1 = children(wrapper);
          if (children$1.length > 0) {
            before$3(wrapper, children$1);
          }
          remove$7(wrapper);
        };
        var inBody = function(element) {
          var dom2 = isText$8(element) ? element.dom.parentNode : element.dom;
          if (dom2 === void 0 || dom2 === null || dom2.ownerDocument === null) {
            return false;
          }
          var doc2 = dom2.ownerDocument;
          return getShadowRoot(SugarElement.fromDom(dom2)).fold(function() {
            return doc2.body.contains(dom2);
          }, compose1(inBody, getShadowHost));
        };
        var r2 = function(left2, top2) {
          var translate2 = function(x2, y2) {
            return r2(left2 + x2, top2 + y2);
          };
          return {
            left: left2,
            top: top2,
            translate: translate2
          };
        };
        var SugarPosition = r2;
        var boxPosition = function(dom2) {
          var box = dom2.getBoundingClientRect();
          return SugarPosition(box.left, box.top);
        };
        var firstDefinedOrZero = function(a2, b2) {
          if (a2 !== void 0) {
            return a2;
          } else {
            return b2 !== void 0 ? b2 : 0;
          }
        };
        var absolute = function(element) {
          var doc2 = element.dom.ownerDocument;
          var body = doc2.body;
          var win = doc2.defaultView;
          var html = doc2.documentElement;
          if (body === element.dom) {
            return SugarPosition(body.offsetLeft, body.offsetTop);
          }
          var scrollTop = firstDefinedOrZero(win === null || win === void 0 ? void 0 : win.pageYOffset, html.scrollTop);
          var scrollLeft = firstDefinedOrZero(win === null || win === void 0 ? void 0 : win.pageXOffset, html.scrollLeft);
          var clientTop = firstDefinedOrZero(html.clientTop, body.clientTop);
          var clientLeft = firstDefinedOrZero(html.clientLeft, body.clientLeft);
          return viewport2(element).translate(scrollLeft - clientLeft, scrollTop - clientTop);
        };
        var viewport2 = function(element) {
          var dom2 = element.dom;
          var doc2 = dom2.ownerDocument;
          var body = doc2.body;
          if (body === dom2) {
            return SugarPosition(body.offsetLeft, body.offsetTop);
          }
          if (!inBody(element)) {
            return SugarPosition(0, 0);
          }
          return boxPosition(dom2);
        };
        var get$8 = function(_DOC) {
          var doc2 = _DOC !== void 0 ? _DOC.dom : document;
          var x2 = doc2.body.scrollLeft || doc2.documentElement.scrollLeft;
          var y2 = doc2.body.scrollTop || doc2.documentElement.scrollTop;
          return SugarPosition(x2, y2);
        };
        var to = function(x2, y2, _DOC) {
          var doc2 = _DOC !== void 0 ? _DOC.dom : document;
          var win = doc2.defaultView;
          if (win) {
            win.scrollTo(x2, y2);
          }
        };
        var intoView = function(element, alignToTop) {
          var isSafari = detect().browser.isSafari();
          if (isSafari && isFunction2(element.dom.scrollIntoViewIfNeeded)) {
            element.dom.scrollIntoViewIfNeeded(false);
          } else {
            element.dom.scrollIntoView(alignToTop);
          }
        };
        var get$7 = function(_win) {
          var win = _win === void 0 ? window : _win;
          if (detect().browser.isFirefox()) {
            return Optional.none();
          } else {
            return Optional.from(win["visualViewport"]);
          }
        };
        var bounds = function(x2, y2, width, height) {
          return {
            x: x2,
            y: y2,
            width,
            height,
            right: x2 + width,
            bottom: y2 + height
          };
        };
        var getBounds2 = function(_win) {
          var win = _win === void 0 ? window : _win;
          var doc2 = win.document;
          var scroll = get$8(SugarElement.fromDom(doc2));
          return get$7(win).fold(function() {
            var html = win.document.documentElement;
            var width = html.clientWidth;
            var height = html.clientHeight;
            return bounds(scroll.left, scroll.top, width, height);
          }, function(visualViewport) {
            return bounds(Math.max(visualViewport.pageLeft, scroll.left), Math.max(visualViewport.pageTop, scroll.top), visualViewport.width, visualViewport.height);
          });
        };
        var isNodeType = function(type2) {
          return function(node) {
            return !!node && node.nodeType === type2;
          };
        };
        var isRestrictedNode = function(node) {
          return !!node && !Object.getPrototypeOf(node);
        };
        var isElement$5 = isNodeType(1);
        var matchNodeNames = function(names2) {
          var lowercasedNames = names2.map(function(s2) {
            return s2.toLowerCase();
          });
          return function(node) {
            if (node && node.nodeName) {
              var nodeName = node.nodeName.toLowerCase();
              return contains$3(lowercasedNames, nodeName);
            }
            return false;
          };
        };
        var matchStyleValues = function(name2, values2) {
          var items = values2.toLowerCase().split(" ");
          return function(node) {
            if (isElement$5(node)) {
              for (var i2 = 0; i2 < items.length; i2++) {
                var computed = node.ownerDocument.defaultView.getComputedStyle(node, null);
                var cssValue = computed ? computed.getPropertyValue(name2) : null;
                if (cssValue === items[i2]) {
                  return true;
                }
              }
            }
            return false;
          };
        };
        var hasAttribute2 = function(attrName) {
          return function(node) {
            return isElement$5(node) && node.hasAttribute(attrName);
          };
        };
        var hasAttributeValue = function(attrName, attrValue) {
          return function(node) {
            return isElement$5(node) && node.getAttribute(attrName) === attrValue;
          };
        };
        var isBogus$2 = function(node) {
          return isElement$5(node) && node.hasAttribute("data-mce-bogus");
        };
        var isBogusAll$1 = function(node) {
          return isElement$5(node) && node.getAttribute("data-mce-bogus") === "all";
        };
        var isTable$3 = function(node) {
          return isElement$5(node) && node.tagName === "TABLE";
        };
        var hasContentEditableState = function(value2) {
          return function(node) {
            if (isElement$5(node)) {
              if (node.contentEditable === value2) {
                return true;
              }
              if (node.getAttribute("data-mce-contenteditable") === value2) {
                return true;
              }
            }
            return false;
          };
        };
        var isTextareaOrInput = matchNodeNames([
          "textarea",
          "input"
        ]);
        var isText$7 = isNodeType(3);
        var isComment = isNodeType(8);
        var isDocument$1 = isNodeType(9);
        var isDocumentFragment = isNodeType(11);
        var isBr$5 = matchNodeNames(["br"]);
        var isImg = matchNodeNames(["img"]);
        var isContentEditableTrue$4 = hasContentEditableState("true");
        var isContentEditableFalse$b = hasContentEditableState("false");
        var isTableCell$5 = matchNodeNames([
          "td",
          "th"
        ]);
        var isMedia$2 = matchNodeNames([
          "video",
          "audio",
          "object",
          "embed"
        ]);
        var is$1 = function(lhs, rhs, comparator) {
          if (comparator === void 0) {
            comparator = tripleEquals;
          }
          return lhs.exists(function(left2) {
            return comparator(left2, rhs);
          });
        };
        var cat = function(arr2) {
          var r3 = [];
          var push2 = function(x2) {
            r3.push(x2);
          };
          for (var i2 = 0; i2 < arr2.length; i2++) {
            arr2[i2].each(push2);
          }
          return r3;
        };
        var lift2 = function(oa, ob, f2) {
          return oa.isSome() && ob.isSome() ? Optional.some(f2(oa.getOrDie(), ob.getOrDie())) : Optional.none();
        };
        var lift3 = function(oa, ob, oc, f2) {
          return oa.isSome() && ob.isSome() && oc.isSome() ? Optional.some(f2(oa.getOrDie(), ob.getOrDie(), oc.getOrDie())) : Optional.none();
        };
        var someIf = function(b2, a2) {
          return b2 ? Optional.some(a2) : Optional.none();
        };
        var isSupported = function(dom2) {
          return dom2.style !== void 0 && isFunction2(dom2.style.getPropertyValue);
        };
        var rawSet = function(dom2, key, value2) {
          if (isString$1(value2) || isBoolean(value2) || isNumber2(value2)) {
            dom2.setAttribute(key, value2 + "");
          } else {
            console.error("Invalid call to Attribute.set. Key ", key, ":: Value ", value2, ":: Element ", dom2);
            throw new Error("Attribute value was not simple");
          }
        };
        var set$1 = function(element, key, value2) {
          rawSet(element.dom, key, value2);
        };
        var setAll$1 = function(element, attrs) {
          var dom2 = element.dom;
          each$j(attrs, function(v2, k2) {
            rawSet(dom2, k2, v2);
          });
        };
        var get$6 = function(element, key) {
          var v2 = element.dom.getAttribute(key);
          return v2 === null ? void 0 : v2;
        };
        var getOpt = function(element, key) {
          return Optional.from(get$6(element, key));
        };
        var has$1 = function(element, key) {
          var dom2 = element.dom;
          return dom2 && dom2.hasAttribute ? dom2.hasAttribute(key) : false;
        };
        var remove$6 = function(element, key) {
          element.dom.removeAttribute(key);
        };
        var clone$3 = function(element) {
          return foldl(element.dom.attributes, function(acc, attr) {
            acc[attr.name] = attr.value;
            return acc;
          }, {});
        };
        var internalSet = function(dom2, property, value2) {
          if (!isString$1(value2)) {
            console.error("Invalid call to CSS.set. Property ", property, ":: Value ", value2, ":: Element ", dom2);
            throw new Error("CSS value must be a string: " + value2);
          }
          if (isSupported(dom2)) {
            dom2.style.setProperty(property, value2);
          }
        };
        var setAll = function(element, css) {
          var dom2 = element.dom;
          each$j(css, function(v2, k2) {
            internalSet(dom2, k2, v2);
          });
        };
        var get$5 = function(element, property) {
          var dom2 = element.dom;
          var styles = window.getComputedStyle(dom2);
          var r3 = styles.getPropertyValue(property);
          return r3 === "" && !inBody(element) ? getUnsafeProperty(dom2, property) : r3;
        };
        var getUnsafeProperty = function(dom2, property) {
          return isSupported(dom2) ? dom2.style.getPropertyValue(property) : "";
        };
        var getRaw = function(element, property) {
          var dom2 = element.dom;
          var raw = getUnsafeProperty(dom2, property);
          return Optional.from(raw).filter(function(r3) {
            return r3.length > 0;
          });
        };
        var getAllRaw = function(element) {
          var css = {};
          var dom2 = element.dom;
          if (isSupported(dom2)) {
            for (var i2 = 0; i2 < dom2.style.length; i2++) {
              var ruleName = dom2.style.item(i2);
              css[ruleName] = dom2.style[ruleName];
            }
          }
          return css;
        };
        var reflow2 = function(e2) {
          return e2.dom.offsetWidth;
        };
        var browser$3 = detect().browser;
        var firstElement = function(nodes) {
          return find$3(nodes, isElement$6);
        };
        var getTableCaptionDeltaY = function(elm) {
          if (browser$3.isFirefox() && name(elm) === "table") {
            return firstElement(children(elm)).filter(function(elm2) {
              return name(elm2) === "caption";
            }).bind(function(caption) {
              return firstElement(nextSiblings(caption)).map(function(body) {
                var bodyTop = body.dom.offsetTop;
                var captionTop = caption.dom.offsetTop;
                var captionHeight = caption.dom.offsetHeight;
                return bodyTop <= captionTop ? -captionHeight : 0;
              });
            }).getOr(0);
          } else {
            return 0;
          }
        };
        var hasChild = function(elm, child2) {
          return elm.children && contains$3(elm.children, child2);
        };
        var getPos = function(body, elm, rootElm) {
          var x2 = 0, y2 = 0;
          var doc2 = body.ownerDocument;
          rootElm = rootElm ? rootElm : body;
          if (elm) {
            if (rootElm === body && elm.getBoundingClientRect && get$5(SugarElement.fromDom(body), "position") === "static") {
              var pos = elm.getBoundingClientRect();
              x2 = pos.left + (doc2.documentElement.scrollLeft || body.scrollLeft) - doc2.documentElement.clientLeft;
              y2 = pos.top + (doc2.documentElement.scrollTop || body.scrollTop) - doc2.documentElement.clientTop;
              return {
                x: x2,
                y: y2
              };
            }
            var offsetParent = elm;
            while (offsetParent && offsetParent !== rootElm && offsetParent.nodeType && !hasChild(offsetParent, rootElm)) {
              var castOffsetParent = offsetParent;
              x2 += castOffsetParent.offsetLeft || 0;
              y2 += castOffsetParent.offsetTop || 0;
              offsetParent = castOffsetParent.offsetParent;
            }
            offsetParent = elm.parentNode;
            while (offsetParent && offsetParent !== rootElm && offsetParent.nodeType && !hasChild(offsetParent, rootElm)) {
              x2 -= offsetParent.scrollLeft || 0;
              y2 -= offsetParent.scrollTop || 0;
              offsetParent = offsetParent.parentNode;
            }
            y2 += getTableCaptionDeltaY(SugarElement.fromDom(elm));
          }
          return {
            x: x2,
            y: y2
          };
        };
        var exports$1 = {}, module$1 = { exports: exports$1 };
        (function(define2, exports2, module2, require2) {
          (function(global2, factory) {
            typeof exports2 === "object" && typeof module2 !== "undefined" ? module2.exports = factory() : typeof define2 === "function" && define2.amd ? define2(factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, global2.EphoxContactWrapper = factory());
          })(this, function() {
            var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
            var promise = { exports: {} };
            (function(module3) {
              (function(root) {
                var setTimeoutFunc = setTimeout;
                function noop4() {
                }
                function bind2(fn3, thisArg) {
                  return function() {
                    fn3.apply(thisArg, arguments);
                  };
                }
                function Promise2(fn3) {
                  if (typeof this !== "object")
                    throw new TypeError("Promises must be constructed via new");
                  if (typeof fn3 !== "function")
                    throw new TypeError("not a function");
                  this._state = 0;
                  this._handled = false;
                  this._value = void 0;
                  this._deferreds = [];
                  doResolve(fn3, this);
                }
                function handle2(self2, deferred) {
                  while (self2._state === 3) {
                    self2 = self2._value;
                  }
                  if (self2._state === 0) {
                    self2._deferreds.push(deferred);
                    return;
                  }
                  self2._handled = true;
                  Promise2._immediateFn(function() {
                    var cb = self2._state === 1 ? deferred.onFulfilled : deferred.onRejected;
                    if (cb === null) {
                      (self2._state === 1 ? resolve3 : reject)(deferred.promise, self2._value);
                      return;
                    }
                    var ret;
                    try {
                      ret = cb(self2._value);
                    } catch (e2) {
                      reject(deferred.promise, e2);
                      return;
                    }
                    resolve3(deferred.promise, ret);
                  });
                }
                function resolve3(self2, newValue) {
                  try {
                    if (newValue === self2)
                      throw new TypeError("A promise cannot be resolved with itself.");
                    if (newValue && (typeof newValue === "object" || typeof newValue === "function")) {
                      var then = newValue.then;
                      if (newValue instanceof Promise2) {
                        self2._state = 3;
                        self2._value = newValue;
                        finale(self2);
                        return;
                      } else if (typeof then === "function") {
                        doResolve(bind2(then, newValue), self2);
                        return;
                      }
                    }
                    self2._state = 1;
                    self2._value = newValue;
                    finale(self2);
                  } catch (e2) {
                    reject(self2, e2);
                  }
                }
                function reject(self2, newValue) {
                  self2._state = 2;
                  self2._value = newValue;
                  finale(self2);
                }
                function finale(self2) {
                  if (self2._state === 2 && self2._deferreds.length === 0) {
                    Promise2._immediateFn(function() {
                      if (!self2._handled) {
                        Promise2._unhandledRejectionFn(self2._value);
                      }
                    });
                  }
                  for (var i2 = 0, len = self2._deferreds.length; i2 < len; i2++) {
                    handle2(self2, self2._deferreds[i2]);
                  }
                  self2._deferreds = null;
                }
                function Handler(onFulfilled, onRejected, promise2) {
                  this.onFulfilled = typeof onFulfilled === "function" ? onFulfilled : null;
                  this.onRejected = typeof onRejected === "function" ? onRejected : null;
                  this.promise = promise2;
                }
                function doResolve(fn3, self2) {
                  var done2 = false;
                  try {
                    fn3(function(value2) {
                      if (done2)
                        return;
                      done2 = true;
                      resolve3(self2, value2);
                    }, function(reason) {
                      if (done2)
                        return;
                      done2 = true;
                      reject(self2, reason);
                    });
                  } catch (ex) {
                    if (done2)
                      return;
                    done2 = true;
                    reject(self2, ex);
                  }
                }
                Promise2.prototype["catch"] = function(onRejected) {
                  return this.then(null, onRejected);
                };
                Promise2.prototype.then = function(onFulfilled, onRejected) {
                  var prom = new this.constructor(noop4);
                  handle2(this, new Handler(onFulfilled, onRejected, prom));
                  return prom;
                };
                Promise2.all = function(arr2) {
                  var args = Array.prototype.slice.call(arr2);
                  return new Promise2(function(resolve4, reject2) {
                    if (args.length === 0)
                      return resolve4([]);
                    var remaining = args.length;
                    function res(i3, val) {
                      try {
                        if (val && (typeof val === "object" || typeof val === "function")) {
                          var then = val.then;
                          if (typeof then === "function") {
                            then.call(val, function(val2) {
                              res(i3, val2);
                            }, reject2);
                            return;
                          }
                        }
                        args[i3] = val;
                        if (--remaining === 0) {
                          resolve4(args);
                        }
                      } catch (ex) {
                        reject2(ex);
                      }
                    }
                    for (var i2 = 0; i2 < args.length; i2++) {
                      res(i2, args[i2]);
                    }
                  });
                };
                Promise2.resolve = function(value2) {
                  if (value2 && typeof value2 === "object" && value2.constructor === Promise2) {
                    return value2;
                  }
                  return new Promise2(function(resolve4) {
                    resolve4(value2);
                  });
                };
                Promise2.reject = function(value2) {
                  return new Promise2(function(resolve4, reject2) {
                    reject2(value2);
                  });
                };
                Promise2.race = function(values2) {
                  return new Promise2(function(resolve4, reject2) {
                    for (var i2 = 0, len = values2.length; i2 < len; i2++) {
                      values2[i2].then(resolve4, reject2);
                    }
                  });
                };
                Promise2._immediateFn = typeof setImmediate === "function" ? function(fn3) {
                  setImmediate(fn3);
                } : function(fn3) {
                  setTimeoutFunc(fn3, 0);
                };
                Promise2._unhandledRejectionFn = function _unhandledRejectionFn(err) {
                  if (typeof console !== "undefined" && console) {
                    console.warn("Possible Unhandled Promise Rejection:", err);
                  }
                };
                Promise2._setImmediateFn = function _setImmediateFn(fn3) {
                  Promise2._immediateFn = fn3;
                };
                Promise2._setUnhandledRejectionFn = function _setUnhandledRejectionFn(fn3) {
                  Promise2._unhandledRejectionFn = fn3;
                };
                if (module3.exports) {
                  module3.exports = Promise2;
                } else if (!root.Promise) {
                  root.Promise = Promise2;
                }
              })(commonjsGlobal);
            })(promise);
            var promisePolyfill = promise.exports;
            var Global = function() {
              if (typeof window !== "undefined") {
                return window;
              } else {
                return Function("return this;")();
              }
            }();
            var promisePolyfill_1 = { boltExport: Global.Promise || promisePolyfill };
            return promisePolyfill_1;
          });
        })(void 0, exports$1, module$1);
        var Promise$1 = module$1.exports.boltExport;
        var nu$1 = function(baseFn) {
          var data2 = Optional.none();
          var callbacks = [];
          var map4 = function(f2) {
            return nu$1(function(nCallback) {
              get2(function(data3) {
                nCallback(f2(data3));
              });
            });
          };
          var get2 = function(nCallback) {
            if (isReady()) {
              call2(nCallback);
            } else {
              callbacks.push(nCallback);
            }
          };
          var set3 = function(x2) {
            if (!isReady()) {
              data2 = Optional.some(x2);
              run(callbacks);
              callbacks = [];
            }
          };
          var isReady = function() {
            return data2.isSome();
          };
          var run = function(cbs) {
            each$k(cbs, call2);
          };
          var call2 = function(cb) {
            data2.each(function(x2) {
              setTimeout(function() {
                cb(x2);
              }, 0);
            });
          };
          baseFn(set3);
          return {
            get: get2,
            map: map4,
            isReady
          };
        };
        var pure$1 = function(a2) {
          return nu$1(function(callback2) {
            callback2(a2);
          });
        };
        var LazyValue = {
          nu: nu$1,
          pure: pure$1
        };
        var errorReporter = function(err) {
          setTimeout(function() {
            throw err;
          }, 0);
        };
        var make = function(run) {
          var get2 = function(callback2) {
            run().then(callback2, errorReporter);
          };
          var map4 = function(fab) {
            return make(function() {
              return run().then(fab);
            });
          };
          var bind2 = function(aFutureB) {
            return make(function() {
              return run().then(function(v2) {
                return aFutureB(v2).toPromise();
              });
            });
          };
          var anonBind = function(futureB) {
            return make(function() {
              return run().then(function() {
                return futureB.toPromise();
              });
            });
          };
          var toLazy = function() {
            return LazyValue.nu(get2);
          };
          var toCached = function() {
            var cache2 = null;
            return make(function() {
              if (cache2 === null) {
                cache2 = run();
              }
              return cache2;
            });
          };
          var toPromise = run;
          return {
            map: map4,
            bind: bind2,
            anonBind,
            toLazy,
            toCached,
            toPromise,
            get: get2
          };
        };
        var nu = function(baseFn) {
          return make(function() {
            return new Promise$1(baseFn);
          });
        };
        var pure = function(a2) {
          return make(function() {
            return Promise$1.resolve(a2);
          });
        };
        var Future = {
          nu,
          pure
        };
        var par$1 = function(asyncValues, nu2) {
          return nu2(function(callback2) {
            var r3 = [];
            var count2 = 0;
            var cb = function(i2) {
              return function(value2) {
                r3[i2] = value2;
                count2++;
                if (count2 >= asyncValues.length) {
                  callback2(r3);
                }
              };
            };
            if (asyncValues.length === 0) {
              callback2([]);
            } else {
              each$k(asyncValues, function(asyncValue, i2) {
                asyncValue.get(cb(i2));
              });
            }
          });
        };
        var par = function(futures) {
          return par$1(futures, Future.nu);
        };
        var value$1 = function(o2) {
          var or2 = function(_opt) {
            return value$1(o2);
          };
          var orThunk = function(_f) {
            return value$1(o2);
          };
          var map4 = function(f2) {
            return value$1(f2(o2));
          };
          var mapError = function(_f) {
            return value$1(o2);
          };
          var each3 = function(f2) {
            f2(o2);
          };
          var bind2 = function(f2) {
            return f2(o2);
          };
          var fold = function(_2, onValue) {
            return onValue(o2);
          };
          var exists2 = function(f2) {
            return f2(o2);
          };
          var forall2 = function(f2) {
            return f2(o2);
          };
          var toOptional = function() {
            return Optional.some(o2);
          };
          return {
            isValue: always,
            isError: never,
            getOr: constant(o2),
            getOrThunk: constant(o2),
            getOrDie: constant(o2),
            or: or2,
            orThunk,
            fold,
            map: map4,
            mapError,
            each: each3,
            bind: bind2,
            exists: exists2,
            forall: forall2,
            toOptional
          };
        };
        var error3 = function(message) {
          var getOrThunk = function(f2) {
            return f2();
          };
          var getOrDie = function() {
            return die(String(message))();
          };
          var or2 = identity;
          var orThunk = function(f2) {
            return f2();
          };
          var map4 = function(_f) {
            return error3(message);
          };
          var mapError = function(f2) {
            return error3(f2(message));
          };
          var bind2 = function(_f) {
            return error3(message);
          };
          var fold = function(onError, _2) {
            return onError(message);
          };
          return {
            isValue: never,
            isError: always,
            getOr: identity,
            getOrThunk,
            getOrDie,
            or: or2,
            orThunk,
            fold,
            map: map4,
            mapError,
            each: noop3,
            bind: bind2,
            exists: never,
            forall: always,
            toOptional: Optional.none
          };
        };
        var fromOption = function(opt, err) {
          return opt.fold(function() {
            return error3(err);
          }, value$1);
        };
        var Result = {
          value: value$1,
          error: error3,
          fromOption
        };
        var generate$1 = function(cases) {
          if (!isArray$1(cases)) {
            throw new Error("cases must be an array");
          }
          if (cases.length === 0) {
            throw new Error("there must be at least one case");
          }
          var constructors = [];
          var adt2 = {};
          each$k(cases, function(acase, count2) {
            var keys$1 = keys(acase);
            if (keys$1.length !== 1) {
              throw new Error("one and only one name per case");
            }
            var key = keys$1[0];
            var value2 = acase[key];
            if (adt2[key] !== void 0) {
              throw new Error("duplicate key detected:" + key);
            } else if (key === "cata") {
              throw new Error("cannot have a case named cata (sorry)");
            } else if (!isArray$1(value2)) {
              throw new Error("case arguments must be an array");
            }
            constructors.push(key);
            adt2[key] = function() {
              var args = [];
              for (var _i2 = 0; _i2 < arguments.length; _i2++) {
                args[_i2] = arguments[_i2];
              }
              var argLength = args.length;
              if (argLength !== value2.length) {
                throw new Error("Wrong number of arguments to case " + key + ". Expected " + value2.length + " (" + value2 + "), got " + argLength);
              }
              var match3 = function(branches) {
                var branchKeys = keys(branches);
                if (constructors.length !== branchKeys.length) {
                  throw new Error("Wrong number of arguments to match. Expected: " + constructors.join(",") + "\nActual: " + branchKeys.join(","));
                }
                var allReqd = forall(constructors, function(reqKey) {
                  return contains$3(branchKeys, reqKey);
                });
                if (!allReqd) {
                  throw new Error("Not all branches were specified when using match. Specified: " + branchKeys.join(", ") + "\nRequired: " + constructors.join(", "));
                }
                return branches[key].apply(null, args);
              };
              return {
                fold: function() {
                  var foldArgs = [];
                  for (var _i3 = 0; _i3 < arguments.length; _i3++) {
                    foldArgs[_i3] = arguments[_i3];
                  }
                  if (foldArgs.length !== cases.length) {
                    throw new Error("Wrong number of arguments to fold. Expected " + cases.length + ", got " + foldArgs.length);
                  }
                  var target = foldArgs[count2];
                  return target.apply(null, args);
                },
                match: match3,
                log: function(label) {
                  console.log(label, {
                    constructors,
                    constructor: key,
                    params: args
                  });
                }
              };
            };
          });
          return adt2;
        };
        var Adt = { generate: generate$1 };
        Adt.generate([
          {
            bothErrors: [
              "error1",
              "error2"
            ]
          },
          {
            firstError: [
              "error1",
              "value2"
            ]
          },
          {
            secondError: [
              "value1",
              "error2"
            ]
          },
          {
            bothValues: [
              "value1",
              "value2"
            ]
          }
        ]);
        var unite = function(result) {
          return result.fold(identity, identity);
        };
        function ClosestOrAncestor(is2, ancestor2, scope, a2, isRoot) {
          if (is2(scope, a2)) {
            return Optional.some(scope);
          } else if (isFunction2(isRoot) && isRoot(scope)) {
            return Optional.none();
          } else {
            return ancestor2(scope, a2, isRoot);
          }
        }
        var ancestor$3 = function(scope, predicate, isRoot) {
          var element = scope.dom;
          var stop2 = isFunction2(isRoot) ? isRoot : never;
          while (element.parentNode) {
            element = element.parentNode;
            var el = SugarElement.fromDom(element);
            if (predicate(el)) {
              return Optional.some(el);
            } else if (stop2(el)) {
              break;
            }
          }
          return Optional.none();
        };
        var closest$3 = function(scope, predicate, isRoot) {
          var is2 = function(s2, test2) {
            return test2(s2);
          };
          return ClosestOrAncestor(is2, ancestor$3, scope, predicate, isRoot);
        };
        var sibling$2 = function(scope, predicate) {
          var element = scope.dom;
          if (!element.parentNode) {
            return Optional.none();
          }
          return child(SugarElement.fromDom(element.parentNode), function(x2) {
            return !eq2(scope, x2) && predicate(x2);
          });
        };
        var child = function(scope, predicate) {
          var pred = function(node) {
            return predicate(SugarElement.fromDom(node));
          };
          var result = find$3(scope.dom.childNodes, pred);
          return result.map(SugarElement.fromDom);
        };
        var ancestor$2 = function(scope, selector, isRoot) {
          return ancestor$3(scope, function(e2) {
            return is$2(e2, selector);
          }, isRoot);
        };
        var descendant = function(scope, selector) {
          return one(selector, scope);
        };
        var closest$2 = function(scope, selector, isRoot) {
          var is2 = function(element, selector2) {
            return is$2(element, selector2);
          };
          return ClosestOrAncestor(is2, ancestor$2, scope, selector, isRoot);
        };
        var promiseObj = window.Promise ? window.Promise : Promise$1;
        var requestAnimationFramePromise;
        var requestAnimationFrame2 = function(callback2, element) {
          var requestAnimationFrameFunc = window.requestAnimationFrame;
          var vendors = [
            "ms",
            "moz",
            "webkit"
          ];
          var featurefill = function(cb) {
            window.setTimeout(cb, 0);
          };
          for (var i2 = 0; i2 < vendors.length && !requestAnimationFrameFunc; i2++) {
            requestAnimationFrameFunc = window[vendors[i2] + "RequestAnimationFrame"];
          }
          if (!requestAnimationFrameFunc) {
            requestAnimationFrameFunc = featurefill;
          }
          requestAnimationFrameFunc(callback2, element);
        };
        var wrappedSetTimeout = function(callback2, time) {
          if (typeof time !== "number") {
            time = 0;
          }
          return setTimeout(callback2, time);
        };
        var wrappedSetInterval = function(callback2, time) {
          if (typeof time !== "number") {
            time = 1;
          }
          return setInterval(callback2, time);
        };
        var wrappedClearTimeout = function(id2) {
          return clearTimeout(id2);
        };
        var wrappedClearInterval = function(id2) {
          return clearInterval(id2);
        };
        var debounce4 = function(callback2, time) {
          var timer;
          var func = function() {
            var args = [];
            for (var _i2 = 0; _i2 < arguments.length; _i2++) {
              args[_i2] = arguments[_i2];
            }
            clearTimeout(timer);
            timer = wrappedSetTimeout(function() {
              callback2.apply(this, args);
            }, time);
          };
          func.stop = function() {
            clearTimeout(timer);
          };
          return func;
        };
        var Delay = {
          requestAnimationFrame: function(callback2, element) {
            if (requestAnimationFramePromise) {
              requestAnimationFramePromise.then(callback2);
              return;
            }
            requestAnimationFramePromise = new promiseObj(function(resolve3) {
              if (!element) {
                element = document.body;
              }
              requestAnimationFrame2(resolve3, element);
            }).then(callback2);
          },
          setTimeout: wrappedSetTimeout,
          setInterval: wrappedSetInterval,
          setEditorTimeout: function(editor, callback2, time) {
            return wrappedSetTimeout(function() {
              if (!editor.removed) {
                callback2();
              }
            }, time);
          },
          setEditorInterval: function(editor, callback2, time) {
            var timer = wrappedSetInterval(function() {
              if (!editor.removed) {
                callback2();
              } else {
                clearInterval(timer);
              }
            }, time);
            return timer;
          },
          debounce: debounce4,
          throttle: debounce4,
          clearInterval: wrappedClearInterval,
          clearTimeout: wrappedClearTimeout
        };
        var StyleSheetLoader = function(documentOrShadowRoot, settings) {
          if (settings === void 0) {
            settings = {};
          }
          var idCount = 0;
          var loadedStates = {};
          var edos = SugarElement.fromDom(documentOrShadowRoot);
          var doc2 = documentOrOwner(edos);
          var maxLoadTime = settings.maxLoadTime || 5e3;
          var _setReferrerPolicy = function(referrerPolicy) {
            settings.referrerPolicy = referrerPolicy;
          };
          var addStyle = function(element) {
            append$1(getStyleContainer(edos), element);
          };
          var removeStyle = function(id2) {
            var styleContainer = getStyleContainer(edos);
            descendant(styleContainer, "#" + id2).each(remove$7);
          };
          var getOrCreateState = function(url) {
            return get$9(loadedStates, url).getOrThunk(function() {
              return {
                id: "mce-u" + idCount++,
                passed: [],
                failed: [],
                count: 0
              };
            });
          };
          var load = function(url, success, failure) {
            var link;
            var urlWithSuffix = Tools._addCacheSuffix(url);
            var state = getOrCreateState(urlWithSuffix);
            loadedStates[urlWithSuffix] = state;
            state.count++;
            var resolve3 = function(callbacks, status) {
              var i2 = callbacks.length;
              while (i2--) {
                callbacks[i2]();
              }
              state.status = status;
              state.passed = [];
              state.failed = [];
              if (link) {
                link.onload = null;
                link.onerror = null;
                link = null;
              }
            };
            var passed = function() {
              return resolve3(state.passed, 2);
            };
            var failed = function() {
              return resolve3(state.failed, 3);
            };
            var wait = function(testCallback, waitCallback) {
              if (!testCallback()) {
                if (Date.now() - startTime < maxLoadTime) {
                  Delay.setTimeout(waitCallback);
                } else {
                  failed();
                }
              }
            };
            var waitForWebKitLinkLoaded = function() {
              wait(function() {
                var styleSheets = documentOrShadowRoot.styleSheets;
                var i2 = styleSheets.length;
                while (i2--) {
                  var styleSheet = styleSheets[i2];
                  var owner2 = styleSheet.ownerNode;
                  if (owner2 && owner2.id === link.id) {
                    passed();
                    return true;
                  }
                }
                return false;
              }, waitForWebKitLinkLoaded);
            };
            if (success) {
              state.passed.push(success);
            }
            if (failure) {
              state.failed.push(failure);
            }
            if (state.status === 1) {
              return;
            }
            if (state.status === 2) {
              passed();
              return;
            }
            if (state.status === 3) {
              failed();
              return;
            }
            state.status = 1;
            var linkElem = SugarElement.fromTag("link", doc2.dom);
            setAll$1(linkElem, {
              rel: "stylesheet",
              type: "text/css",
              id: state.id
            });
            var startTime = Date.now();
            if (settings.contentCssCors) {
              set$1(linkElem, "crossOrigin", "anonymous");
            }
            if (settings.referrerPolicy) {
              set$1(linkElem, "referrerpolicy", settings.referrerPolicy);
            }
            link = linkElem.dom;
            link.onload = waitForWebKitLinkLoaded;
            link.onerror = failed;
            addStyle(linkElem);
            set$1(linkElem, "href", urlWithSuffix);
          };
          var loadF = function(url) {
            return Future.nu(function(resolve3) {
              load(url, compose(resolve3, constant(Result.value(url))), compose(resolve3, constant(Result.error(url))));
            });
          };
          var loadAll = function(urls, success, failure) {
            par(map$3(urls, loadF)).get(function(result) {
              var parts = partition(result, function(r3) {
                return r3.isValue();
              });
              if (parts.fail.length > 0) {
                failure(parts.fail.map(unite));
              } else {
                success(parts.pass.map(unite));
              }
            });
          };
          var unload = function(url) {
            var urlWithSuffix = Tools._addCacheSuffix(url);
            get$9(loadedStates, urlWithSuffix).each(function(state) {
              var count2 = --state.count;
              if (count2 === 0) {
                delete loadedStates[urlWithSuffix];
                removeStyle(state.id);
              }
            });
          };
          var unloadAll = function(urls) {
            each$k(urls, function(url) {
              unload(url);
            });
          };
          return {
            load,
            loadAll,
            unload,
            unloadAll,
            _setReferrerPolicy
          };
        };
        var create$8 = function() {
          var map4 = /* @__PURE__ */ new WeakMap();
          var forElement = function(referenceElement, settings) {
            var root = getRootNode(referenceElement);
            var rootDom = root.dom;
            return Optional.from(map4.get(rootDom)).getOrThunk(function() {
              var sl = StyleSheetLoader(rootDom, settings);
              map4.set(rootDom, sl);
              return sl;
            });
          };
          return { forElement };
        };
        var instance = create$8();
        var DomTreeWalker = function() {
          function DomTreeWalker2(startNode, rootNode) {
            this.node = startNode;
            this.rootNode = rootNode;
            this.current = this.current.bind(this);
            this.next = this.next.bind(this);
            this.prev = this.prev.bind(this);
            this.prev2 = this.prev2.bind(this);
          }
          DomTreeWalker2.prototype.current = function() {
            return this.node;
          };
          DomTreeWalker2.prototype.next = function(shallow2) {
            this.node = this.findSibling(this.node, "firstChild", "nextSibling", shallow2);
            return this.node;
          };
          DomTreeWalker2.prototype.prev = function(shallow2) {
            this.node = this.findSibling(this.node, "lastChild", "previousSibling", shallow2);
            return this.node;
          };
          DomTreeWalker2.prototype.prev2 = function(shallow2) {
            this.node = this.findPreviousNode(this.node, "lastChild", "previousSibling", shallow2);
            return this.node;
          };
          DomTreeWalker2.prototype.findSibling = function(node, startName, siblingName, shallow2) {
            var sibling2, parent2;
            if (node) {
              if (!shallow2 && node[startName]) {
                return node[startName];
              }
              if (node !== this.rootNode) {
                sibling2 = node[siblingName];
                if (sibling2) {
                  return sibling2;
                }
                for (parent2 = node.parentNode; parent2 && parent2 !== this.rootNode; parent2 = parent2.parentNode) {
                  sibling2 = parent2[siblingName];
                  if (sibling2) {
                    return sibling2;
                  }
                }
              }
            }
          };
          DomTreeWalker2.prototype.findPreviousNode = function(node, startName, siblingName, shallow2) {
            var sibling2, parent2, child2;
            if (node) {
              sibling2 = node[siblingName];
              if (this.rootNode && sibling2 === this.rootNode) {
                return;
              }
              if (sibling2) {
                if (!shallow2) {
                  for (child2 = sibling2[startName]; child2; child2 = child2[startName]) {
                    if (!child2[startName]) {
                      return child2;
                    }
                  }
                }
                return sibling2;
              }
              parent2 = node.parentNode;
              if (parent2 && parent2 !== this.rootNode) {
                return parent2;
              }
            }
          };
          return DomTreeWalker2;
        }();
        var blocks = [
          "article",
          "aside",
          "details",
          "div",
          "dt",
          "figcaption",
          "footer",
          "form",
          "fieldset",
          "header",
          "hgroup",
          "html",
          "main",
          "nav",
          "section",
          "summary",
          "body",
          "p",
          "dl",
          "multicol",
          "dd",
          "figure",
          "address",
          "center",
          "blockquote",
          "h1",
          "h2",
          "h3",
          "h4",
          "h5",
          "h6",
          "listing",
          "xmp",
          "pre",
          "plaintext",
          "menu",
          "dir",
          "ul",
          "ol",
          "li",
          "hr",
          "table",
          "tbody",
          "thead",
          "tfoot",
          "th",
          "tr",
          "td",
          "caption"
        ];
        var tableCells = [
          "td",
          "th"
        ];
        var tableSections = [
          "thead",
          "tbody",
          "tfoot"
        ];
        var textBlocks = [
          "h1",
          "h2",
          "h3",
          "h4",
          "h5",
          "h6",
          "p",
          "div",
          "address",
          "pre",
          "form",
          "blockquote",
          "center",
          "dir",
          "fieldset",
          "header",
          "footer",
          "article",
          "section",
          "hgroup",
          "aside",
          "nav",
          "figure"
        ];
        var headings = [
          "h1",
          "h2",
          "h3",
          "h4",
          "h5",
          "h6"
        ];
        var listItems$1 = [
          "li",
          "dd",
          "dt"
        ];
        var lists = [
          "ul",
          "ol",
          "dl"
        ];
        var wsElements = [
          "pre",
          "script",
          "textarea",
          "style"
        ];
        var lazyLookup = function(items) {
          var lookup;
          return function(node) {
            lookup = lookup ? lookup : mapToObject(items, always);
            return has$2(lookup, name(node));
          };
        };
        var isHeading = lazyLookup(headings);
        var isBlock$2 = lazyLookup(blocks);
        var isTable$2 = function(node) {
          return name(node) === "table";
        };
        var isInline$1 = function(node) {
          return isElement$6(node) && !isBlock$2(node);
        };
        var isBr$4 = function(node) {
          return isElement$6(node) && name(node) === "br";
        };
        var isTextBlock$2 = lazyLookup(textBlocks);
        var isList = lazyLookup(lists);
        var isListItem = lazyLookup(listItems$1);
        var isTableSection = lazyLookup(tableSections);
        var isTableCell$4 = lazyLookup(tableCells);
        var isWsPreserveElement = lazyLookup(wsElements);
        var ancestor$1 = function(scope, selector, isRoot) {
          return ancestor$2(scope, selector, isRoot).isSome();
        };
        var zeroWidth = "\uFEFF";
        var nbsp = "\xA0";
        var isZwsp$1 = function(char) {
          return char === zeroWidth;
        };
        var removeZwsp = function(s2) {
          return s2.replace(/\uFEFF/g, "");
        };
        var ZWSP$1 = zeroWidth;
        var isZwsp = isZwsp$1;
        var trim$2 = removeZwsp;
        var isElement$4 = isElement$5;
        var isText$6 = isText$7;
        var isCaretContainerBlock$1 = function(node) {
          if (isText$6(node)) {
            node = node.parentNode;
          }
          return isElement$4(node) && node.hasAttribute("data-mce-caret");
        };
        var isCaretContainerInline = function(node) {
          return isText$6(node) && isZwsp(node.data);
        };
        var isCaretContainer$2 = function(node) {
          return isCaretContainerBlock$1(node) || isCaretContainerInline(node);
        };
        var hasContent = function(node) {
          return node.firstChild !== node.lastChild || !isBr$5(node.firstChild);
        };
        var insertInline$1 = function(node, before2) {
          var doc2 = node.ownerDocument;
          var textNode = doc2.createTextNode(ZWSP$1);
          var parentNode = node.parentNode;
          if (!before2) {
            var sibling2 = node.nextSibling;
            if (isText$6(sibling2)) {
              if (isCaretContainer$2(sibling2)) {
                return sibling2;
              }
              if (startsWithCaretContainer$1(sibling2)) {
                sibling2.splitText(1);
                return sibling2;
              }
            }
            if (node.nextSibling) {
              parentNode.insertBefore(textNode, node.nextSibling);
            } else {
              parentNode.appendChild(textNode);
            }
          } else {
            var sibling2 = node.previousSibling;
            if (isText$6(sibling2)) {
              if (isCaretContainer$2(sibling2)) {
                return sibling2;
              }
              if (endsWithCaretContainer$1(sibling2)) {
                return sibling2.splitText(sibling2.data.length - 1);
              }
            }
            parentNode.insertBefore(textNode, node);
          }
          return textNode;
        };
        var isBeforeInline = function(pos) {
          var container = pos.container();
          if (!isText$7(container)) {
            return false;
          }
          return container.data.charAt(pos.offset()) === ZWSP$1 || pos.isAtStart() && isCaretContainerInline(container.previousSibling);
        };
        var isAfterInline = function(pos) {
          var container = pos.container();
          if (!isText$7(container)) {
            return false;
          }
          return container.data.charAt(pos.offset() - 1) === ZWSP$1 || pos.isAtEnd() && isCaretContainerInline(container.nextSibling);
        };
        var createBogusBr = function() {
          var br = document.createElement("br");
          br.setAttribute("data-mce-bogus", "1");
          return br;
        };
        var insertBlock$1 = function(blockName, node, before2) {
          var doc2 = node.ownerDocument;
          var blockNode = doc2.createElement(blockName);
          blockNode.setAttribute("data-mce-caret", before2 ? "before" : "after");
          blockNode.setAttribute("data-mce-bogus", "all");
          blockNode.appendChild(createBogusBr());
          var parentNode = node.parentNode;
          if (!before2) {
            if (node.nextSibling) {
              parentNode.insertBefore(blockNode, node.nextSibling);
            } else {
              parentNode.appendChild(blockNode);
            }
          } else {
            parentNode.insertBefore(blockNode, node);
          }
          return blockNode;
        };
        var startsWithCaretContainer$1 = function(node) {
          return isText$6(node) && node.data[0] === ZWSP$1;
        };
        var endsWithCaretContainer$1 = function(node) {
          return isText$6(node) && node.data[node.data.length - 1] === ZWSP$1;
        };
        var trimBogusBr = function(elm) {
          var brs = elm.getElementsByTagName("br");
          var lastBr = brs[brs.length - 1];
          if (isBogus$2(lastBr)) {
            lastBr.parentNode.removeChild(lastBr);
          }
        };
        var showCaretContainerBlock = function(caretContainer) {
          if (caretContainer && caretContainer.hasAttribute("data-mce-caret")) {
            trimBogusBr(caretContainer);
            caretContainer.removeAttribute("data-mce-caret");
            caretContainer.removeAttribute("data-mce-bogus");
            caretContainer.removeAttribute("style");
            caretContainer.removeAttribute("_moz_abspos");
            return caretContainer;
          }
          return null;
        };
        var isRangeInCaretContainerBlock = function(range2) {
          return isCaretContainerBlock$1(range2.startContainer);
        };
        var isContentEditableTrue$3 = isContentEditableTrue$4;
        var isContentEditableFalse$a = isContentEditableFalse$b;
        var isBr$3 = isBr$5;
        var isText$5 = isText$7;
        var isInvalidTextElement = matchNodeNames([
          "script",
          "style",
          "textarea"
        ]);
        var isAtomicInline = matchNodeNames([
          "img",
          "input",
          "textarea",
          "hr",
          "iframe",
          "video",
          "audio",
          "object",
          "embed"
        ]);
        var isTable$1 = matchNodeNames(["table"]);
        var isCaretContainer$1 = isCaretContainer$2;
        var isCaretCandidate$3 = function(node) {
          if (isCaretContainer$1(node)) {
            return false;
          }
          if (isText$5(node)) {
            return !isInvalidTextElement(node.parentNode);
          }
          return isAtomicInline(node) || isBr$3(node) || isTable$1(node) || isNonUiContentEditableFalse(node);
        };
        var isUnselectable = function(node) {
          return isElement$5(node) && node.getAttribute("unselectable") === "true";
        };
        var isNonUiContentEditableFalse = function(node) {
          return isUnselectable(node) === false && isContentEditableFalse$a(node);
        };
        var isInEditable = function(node, root) {
          for (node = node.parentNode; node && node !== root; node = node.parentNode) {
            if (isNonUiContentEditableFalse(node)) {
              return false;
            }
            if (isContentEditableTrue$3(node)) {
              return true;
            }
          }
          return true;
        };
        var isAtomicContentEditableFalse = function(node) {
          if (!isNonUiContentEditableFalse(node)) {
            return false;
          }
          return foldl(from(node.getElementsByTagName("*")), function(result, elm) {
            return result || isContentEditableTrue$3(elm);
          }, false) !== true;
        };
        var isAtomic$1 = function(node) {
          return isAtomicInline(node) || isAtomicContentEditableFalse(node);
        };
        var isEditableCaretCandidate$1 = function(node, root) {
          return isCaretCandidate$3(node) && isInEditable(node, root);
        };
        var whiteSpaceRegExp$1 = /^[ \t\r\n]*$/;
        var isWhitespaceText = function(text) {
          return whiteSpaceRegExp$1.test(text);
        };
        var hasWhitespacePreserveParent = function(node, rootNode) {
          var rootElement = SugarElement.fromDom(rootNode);
          var startNode = SugarElement.fromDom(node);
          return ancestor$1(startNode, "pre,code", curry(eq2, rootElement));
        };
        var isWhitespace = function(node, rootNode) {
          return isText$7(node) && isWhitespaceText(node.data) && hasWhitespacePreserveParent(node, rootNode) === false;
        };
        var isNamedAnchor = function(node) {
          return isElement$5(node) && node.nodeName === "A" && !node.hasAttribute("href") && (node.hasAttribute("name") || node.hasAttribute("id"));
        };
        var isContent$1 = function(node, rootNode) {
          return isCaretCandidate$3(node) && isWhitespace(node, rootNode) === false || isNamedAnchor(node) || isBookmark(node);
        };
        var isBookmark = hasAttribute2("data-mce-bookmark");
        var isBogus$1 = hasAttribute2("data-mce-bogus");
        var isBogusAll = hasAttributeValue("data-mce-bogus", "all");
        var isEmptyNode = function(targetNode, skipBogus) {
          var brCount = 0;
          if (isContent$1(targetNode, targetNode)) {
            return false;
          } else {
            var node = targetNode.firstChild;
            if (!node) {
              return true;
            }
            var walker = new DomTreeWalker(node, targetNode);
            do {
              if (skipBogus) {
                if (isBogusAll(node)) {
                  node = walker.next(true);
                  continue;
                }
                if (isBogus$1(node)) {
                  node = walker.next();
                  continue;
                }
              }
              if (isBr$5(node)) {
                brCount++;
                node = walker.next();
                continue;
              }
              if (isContent$1(node, targetNode)) {
                return false;
              }
              node = walker.next();
            } while (node);
            return brCount <= 1;
          }
        };
        var isEmpty$2 = function(elm, skipBogus) {
          if (skipBogus === void 0) {
            skipBogus = true;
          }
          return isEmptyNode(elm.dom, skipBogus);
        };
        var isSpan = function(node) {
          return node.nodeName.toLowerCase() === "span";
        };
        var isInlineContent = function(node, root) {
          return isNonNullable(node) && (isContent$1(node, root) || isInline$1(SugarElement.fromDom(node)));
        };
        var surroundedByInlineContent = function(node, root) {
          var prev = new DomTreeWalker(node, root).prev(false);
          var next = new DomTreeWalker(node, root).next(false);
          var prevIsInline = isUndefined(prev) || isInlineContent(prev, root);
          var nextIsInline = isUndefined(next) || isInlineContent(next, root);
          return prevIsInline && nextIsInline;
        };
        var isBookmarkNode$2 = function(node) {
          return isSpan(node) && node.getAttribute("data-mce-type") === "bookmark";
        };
        var isKeepTextNode = function(node, root) {
          return isText$7(node) && node.data.length > 0 && surroundedByInlineContent(node, root);
        };
        var isKeepElement = function(node) {
          return isElement$5(node) ? node.childNodes.length > 0 : false;
        };
        var isDocument = function(node) {
          return isDocumentFragment(node) || isDocument$1(node);
        };
        var trimNode = function(dom2, node, root) {
          var rootNode = root || node;
          if (isElement$5(node) && isBookmarkNode$2(node)) {
            return node;
          }
          var children2 = node.childNodes;
          for (var i2 = children2.length - 1; i2 >= 0; i2--) {
            trimNode(dom2, children2[i2], rootNode);
          }
          if (isElement$5(node)) {
            var currentChildren = node.childNodes;
            if (currentChildren.length === 1 && isBookmarkNode$2(currentChildren[0])) {
              node.parentNode.insertBefore(currentChildren[0], node);
            }
          }
          if (!isDocument(node) && !isContent$1(node, rootNode) && !isKeepElement(node) && !isKeepTextNode(node, rootNode)) {
            dom2.remove(node);
          }
          return node;
        };
        var makeMap$3 = Tools.makeMap;
        var attrsCharsRegExp = /[&<>\"\u0060\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
        var textCharsRegExp = /[<>&\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
        var rawCharsRegExp = /[<>&\"\']/g;
        var entityRegExp = /&#([a-z0-9]+);?|&([a-z0-9]+);/gi;
        var asciiMap = {
          128: "\u20AC",
          130: "\u201A",
          131: "\u0192",
          132: "\u201E",
          133: "\u2026",
          134: "\u2020",
          135: "\u2021",
          136: "\u02C6",
          137: "\u2030",
          138: "\u0160",
          139: "\u2039",
          140: "\u0152",
          142: "\u017D",
          145: "\u2018",
          146: "\u2019",
          147: "\u201C",
          148: "\u201D",
          149: "\u2022",
          150: "\u2013",
          151: "\u2014",
          152: "\u02DC",
          153: "\u2122",
          154: "\u0161",
          155: "\u203A",
          156: "\u0153",
          158: "\u017E",
          159: "\u0178"
        };
        var baseEntities = {
          '"': "&quot;",
          "'": "&#39;",
          "<": "&lt;",
          ">": "&gt;",
          "&": "&amp;",
          "`": "&#96;"
        };
        var reverseEntities = {
          "&lt;": "<",
          "&gt;": ">",
          "&amp;": "&",
          "&quot;": '"',
          "&apos;": "'"
        };
        var nativeDecode = function(text) {
          var elm = SugarElement.fromTag("div").dom;
          elm.innerHTML = text;
          return elm.textContent || elm.innerText || text;
        };
        var buildEntitiesLookup = function(items, radix) {
          var i2, chr, entity;
          var lookup = {};
          if (items) {
            items = items.split(",");
            radix = radix || 10;
            for (i2 = 0; i2 < items.length; i2 += 2) {
              chr = String.fromCharCode(parseInt(items[i2], radix));
              if (!baseEntities[chr]) {
                entity = "&" + items[i2 + 1] + ";";
                lookup[chr] = entity;
                lookup[entity] = chr;
              }
            }
            return lookup;
          }
        };
        var namedEntities = buildEntitiesLookup("50,nbsp,51,iexcl,52,cent,53,pound,54,curren,55,yen,56,brvbar,57,sect,58,uml,59,copy,5a,ordf,5b,laquo,5c,not,5d,shy,5e,reg,5f,macr,5g,deg,5h,plusmn,5i,sup2,5j,sup3,5k,acute,5l,micro,5m,para,5n,middot,5o,cedil,5p,sup1,5q,ordm,5r,raquo,5s,frac14,5t,frac12,5u,frac34,5v,iquest,60,Agrave,61,Aacute,62,Acirc,63,Atilde,64,Auml,65,Aring,66,AElig,67,Ccedil,68,Egrave,69,Eacute,6a,Ecirc,6b,Euml,6c,Igrave,6d,Iacute,6e,Icirc,6f,Iuml,6g,ETH,6h,Ntilde,6i,Ograve,6j,Oacute,6k,Ocirc,6l,Otilde,6m,Ouml,6n,times,6o,Oslash,6p,Ugrave,6q,Uacute,6r,Ucirc,6s,Uuml,6t,Yacute,6u,THORN,6v,szlig,70,agrave,71,aacute,72,acirc,73,atilde,74,auml,75,aring,76,aelig,77,ccedil,78,egrave,79,eacute,7a,ecirc,7b,euml,7c,igrave,7d,iacute,7e,icirc,7f,iuml,7g,eth,7h,ntilde,7i,ograve,7j,oacute,7k,ocirc,7l,otilde,7m,ouml,7n,divide,7o,oslash,7p,ugrave,7q,uacute,7r,ucirc,7s,uuml,7t,yacute,7u,thorn,7v,yuml,ci,fnof,sh,Alpha,si,Beta,sj,Gamma,sk,Delta,sl,Epsilon,sm,Zeta,sn,Eta,so,Theta,sp,Iota,sq,Kappa,sr,Lambda,ss,Mu,st,Nu,su,Xi,sv,Omicron,t0,Pi,t1,Rho,t3,Sigma,t4,Tau,t5,Upsilon,t6,Phi,t7,Chi,t8,Psi,t9,Omega,th,alpha,ti,beta,tj,gamma,tk,delta,tl,epsilon,tm,zeta,tn,eta,to,theta,tp,iota,tq,kappa,tr,lambda,ts,mu,tt,nu,tu,xi,tv,omicron,u0,pi,u1,rho,u2,sigmaf,u3,sigma,u4,tau,u5,upsilon,u6,phi,u7,chi,u8,psi,u9,omega,uh,thetasym,ui,upsih,um,piv,812,bull,816,hellip,81i,prime,81j,Prime,81u,oline,824,frasl,88o,weierp,88h,image,88s,real,892,trade,89l,alefsym,8cg,larr,8ch,uarr,8ci,rarr,8cj,darr,8ck,harr,8dl,crarr,8eg,lArr,8eh,uArr,8ei,rArr,8ej,dArr,8ek,hArr,8g0,forall,8g2,part,8g3,exist,8g5,empty,8g7,nabla,8g8,isin,8g9,notin,8gb,ni,8gf,prod,8gh,sum,8gi,minus,8gn,lowast,8gq,radic,8gt,prop,8gu,infin,8h0,ang,8h7,and,8h8,or,8h9,cap,8ha,cup,8hb,int,8hk,there4,8hs,sim,8i5,cong,8i8,asymp,8j0,ne,8j1,equiv,8j4,le,8j5,ge,8k2,sub,8k3,sup,8k4,nsub,8k6,sube,8k7,supe,8kl,oplus,8kn,otimes,8l5,perp,8m5,sdot,8o8,lceil,8o9,rceil,8oa,lfloor,8ob,rfloor,8p9,lang,8pa,rang,9ea,loz,9j0,spades,9j3,clubs,9j5,hearts,9j6,diams,ai,OElig,aj,oelig,b0,Scaron,b1,scaron,bo,Yuml,m6,circ,ms,tilde,802,ensp,803,emsp,809,thinsp,80c,zwnj,80d,zwj,80e,lrm,80f,rlm,80j,ndash,80k,mdash,80o,lsquo,80p,rsquo,80q,sbquo,80s,ldquo,80t,rdquo,80u,bdquo,810,dagger,811,Dagger,81g,permil,81p,lsaquo,81q,rsaquo,85c,euro", 32);
        var encodeRaw = function(text, attr) {
          return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) {
            return baseEntities[chr] || chr;
          });
        };
        var encodeAllRaw = function(text) {
          return ("" + text).replace(rawCharsRegExp, function(chr) {
            return baseEntities[chr] || chr;
          });
        };
        var encodeNumeric = function(text, attr) {
          return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) {
            if (chr.length > 1) {
              return "&#" + ((chr.charCodeAt(0) - 55296) * 1024 + (chr.charCodeAt(1) - 56320) + 65536) + ";";
            }
            return baseEntities[chr] || "&#" + chr.charCodeAt(0) + ";";
          });
        };
        var encodeNamed = function(text, attr, entities) {
          entities = entities || namedEntities;
          return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) {
            return baseEntities[chr] || entities[chr] || chr;
          });
        };
        var getEncodeFunc = function(name2, entities) {
          var entitiesMap = buildEntitiesLookup(entities) || namedEntities;
          var encodeNamedAndNumeric = function(text, attr) {
            return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) {
              if (baseEntities[chr] !== void 0) {
                return baseEntities[chr];
              }
              if (entitiesMap[chr] !== void 0) {
                return entitiesMap[chr];
              }
              if (chr.length > 1) {
                return "&#" + ((chr.charCodeAt(0) - 55296) * 1024 + (chr.charCodeAt(1) - 56320) + 65536) + ";";
              }
              return "&#" + chr.charCodeAt(0) + ";";
            });
          };
          var encodeCustomNamed = function(text, attr) {
            return encodeNamed(text, attr, entitiesMap);
          };
          var nameMap = makeMap$3(name2.replace(/\+/g, ","));
          if (nameMap.named && nameMap.numeric) {
            return encodeNamedAndNumeric;
          }
          if (nameMap.named) {
            if (entities) {
              return encodeCustomNamed;
            }
            return encodeNamed;
          }
          if (nameMap.numeric) {
            return encodeNumeric;
          }
          return encodeRaw;
        };
        var decode = function(text) {
          return text.replace(entityRegExp, function(all2, numeric) {
            if (numeric) {
              if (numeric.charAt(0).toLowerCase() === "x") {
                numeric = parseInt(numeric.substr(1), 16);
              } else {
                numeric = parseInt(numeric, 10);
              }
              if (numeric > 65535) {
                numeric -= 65536;
                return String.fromCharCode(55296 + (numeric >> 10), 56320 + (numeric & 1023));
              }
              return asciiMap[numeric] || String.fromCharCode(numeric);
            }
            return reverseEntities[all2] || namedEntities[all2] || nativeDecode(all2);
          });
        };
        var Entities = {
          encodeRaw,
          encodeAllRaw,
          encodeNumeric,
          encodeNamed,
          getEncodeFunc,
          decode
        };
        var mapCache = {}, dummyObj = {};
        var makeMap$2 = Tools.makeMap, each$h = Tools.each, extend$5 = Tools.extend, explode$3 = Tools.explode, inArray$2 = Tools.inArray;
        var split$1 = function(items, delim) {
          items = Tools.trim(items);
          return items ? items.split(delim || " ") : [];
        };
        var compileSchema = function(type2) {
          var schema = {};
          var globalAttributes, blockContent;
          var phrasingContent, flowContent, html4BlockContent, html4PhrasingContent;
          var add4 = function(name2, attributes2, children2) {
            var ni2, attributesOrder, element;
            var arrayToMap = function(array, obj) {
              var map4 = {};
              var i2, l2;
              for (i2 = 0, l2 = array.length; i2 < l2; i2++) {
                map4[array[i2]] = obj || {};
              }
              return map4;
            };
            children2 = children2 || [];
            attributes2 = attributes2 || "";
            if (typeof children2 === "string") {
              children2 = split$1(children2);
            }
            var names2 = split$1(name2);
            ni2 = names2.length;
            while (ni2--) {
              attributesOrder = split$1([
                globalAttributes,
                attributes2
              ].join(" "));
              element = {
                attributes: arrayToMap(attributesOrder),
                attributesOrder,
                children: arrayToMap(children2, dummyObj)
              };
              schema[names2[ni2]] = element;
            }
          };
          var addAttrs = function(name2, attributes2) {
            var ni2, schemaItem, i2, l2;
            var names2 = split$1(name2);
            ni2 = names2.length;
            var attrs = split$1(attributes2);
            while (ni2--) {
              schemaItem = schema[names2[ni2]];
              for (i2 = 0, l2 = attrs.length; i2 < l2; i2++) {
                schemaItem.attributes[attrs[i2]] = {};
                schemaItem.attributesOrder.push(attrs[i2]);
              }
            }
          };
          if (mapCache[type2]) {
            return mapCache[type2];
          }
          globalAttributes = "id accesskey class dir lang style tabindex title role";
          blockContent = "address blockquote div dl fieldset form h1 h2 h3 h4 h5 h6 hr menu ol p pre table ul";
          phrasingContent = "a abbr b bdo br button cite code del dfn em embed i iframe img input ins kbd label map noscript object q s samp script select small span strong sub sup textarea u var #text #comment";
          if (type2 !== "html4") {
            globalAttributes += " contenteditable contextmenu draggable dropzone hidden spellcheck translate";
            blockContent += " article aside details dialog figure main header footer hgroup section nav";
            phrasingContent += " audio canvas command datalist mark meter output picture progress time wbr video ruby bdi keygen";
          }
          if (type2 !== "html5-strict") {
            globalAttributes += " xml:lang";
            html4PhrasingContent = "acronym applet basefont big font strike tt";
            phrasingContent = [
              phrasingContent,
              html4PhrasingContent
            ].join(" ");
            each$h(split$1(html4PhrasingContent), function(name2) {
              add4(name2, "", phrasingContent);
            });
            html4BlockContent = "center dir isindex noframes";
            blockContent = [
              blockContent,
              html4BlockContent
            ].join(" ");
            flowContent = [
              blockContent,
              phrasingContent
            ].join(" ");
            each$h(split$1(html4BlockContent), function(name2) {
              add4(name2, "", flowContent);
            });
          }
          flowContent = flowContent || [
            blockContent,
            phrasingContent
          ].join(" ");
          add4("html", "manifest", "head body");
          add4("head", "", "base command link meta noscript script style title");
          add4("title hr noscript br");
          add4("base", "href target");
          add4("link", "href rel media hreflang type sizes hreflang");
          add4("meta", "name http-equiv content charset");
          add4("style", "media type scoped");
          add4("script", "src async defer type charset");
          add4("body", "onafterprint onbeforeprint onbeforeunload onblur onerror onfocus onhashchange onload onmessage onoffline ononline onpagehide onpageshow onpopstate onresize onscroll onstorage onunload", flowContent);
          add4("address dt dd div caption", "", flowContent);
          add4("h1 h2 h3 h4 h5 h6 pre p abbr code var samp kbd sub sup i b u bdo span legend em strong small s cite dfn", "", phrasingContent);
          add4("blockquote", "cite", flowContent);
          add4("ol", "reversed start type", "li");
          add4("ul", "", "li");
          add4("li", "value", flowContent);
          add4("dl", "", "dt dd");
          add4("a", "href target rel media hreflang type", phrasingContent);
          add4("q", "cite", phrasingContent);
          add4("ins del", "cite datetime", flowContent);
          add4("img", "src sizes srcset alt usemap ismap width height");
          add4("iframe", "src name width height", flowContent);
          add4("embed", "src type width height");
          add4("object", "data type typemustmatch name usemap form width height", [
            flowContent,
            "param"
          ].join(" "));
          add4("param", "name value");
          add4("map", "name", [
            flowContent,
            "area"
          ].join(" "));
          add4("area", "alt coords shape href target rel media hreflang type");
          add4("table", "border", "caption colgroup thead tfoot tbody tr" + (type2 === "html4" ? " col" : ""));
          add4("colgroup", "span", "col");
          add4("col", "span");
          add4("tbody thead tfoot", "", "tr");
          add4("tr", "", "td th");
          add4("td", "colspan rowspan headers", flowContent);
          add4("th", "colspan rowspan headers scope abbr", flowContent);
          add4("form", "accept-charset action autocomplete enctype method name novalidate target", flowContent);
          add4("fieldset", "disabled form name", [
            flowContent,
            "legend"
          ].join(" "));
          add4("label", "form for", phrasingContent);
          add4("input", "accept alt autocomplete checked dirname disabled form formaction formenctype formmethod formnovalidate formtarget height list max maxlength min multiple name pattern readonly required size src step type value width");
          add4("button", "disabled form formaction formenctype formmethod formnovalidate formtarget name type value", type2 === "html4" ? flowContent : phrasingContent);
          add4("select", "disabled form multiple name required size", "option optgroup");
          add4("optgroup", "disabled label", "option");
          add4("option", "disabled label selected value");
          add4("textarea", "cols dirname disabled form maxlength name readonly required rows wrap");
          add4("menu", "type label", [
            flowContent,
            "li"
          ].join(" "));
          add4("noscript", "", flowContent);
          if (type2 !== "html4") {
            add4("wbr");
            add4("ruby", "", [
              phrasingContent,
              "rt rp"
            ].join(" "));
            add4("figcaption", "", flowContent);
            add4("mark rt rp summary bdi", "", phrasingContent);
            add4("canvas", "width height", flowContent);
            add4("video", "src crossorigin poster preload autoplay mediagroup loop muted controls width height buffered", [
              flowContent,
              "track source"
            ].join(" "));
            add4("audio", "src crossorigin preload autoplay mediagroup loop muted controls buffered volume", [
              flowContent,
              "track source"
            ].join(" "));
            add4("picture", "", "img source");
            add4("source", "src srcset type media sizes");
            add4("track", "kind src srclang label default");
            add4("datalist", "", [
              phrasingContent,
              "option"
            ].join(" "));
            add4("article section nav aside main header footer", "", flowContent);
            add4("hgroup", "", "h1 h2 h3 h4 h5 h6");
            add4("figure", "", [
              flowContent,
              "figcaption"
            ].join(" "));
            add4("time", "datetime", phrasingContent);
            add4("dialog", "open", flowContent);
            add4("command", "type label icon disabled checked radiogroup command");
            add4("output", "for form name", phrasingContent);
            add4("progress", "value max", phrasingContent);
            add4("meter", "value min max low high optimum", phrasingContent);
            add4("details", "open", [
              flowContent,
              "summary"
            ].join(" "));
            add4("keygen", "autofocus challenge disabled form keytype name");
          }
          if (type2 !== "html5-strict") {
            addAttrs("script", "language xml:space");
            addAttrs("style", "xml:space");
            addAttrs("object", "declare classid code codebase codetype archive standby align border hspace vspace");
            addAttrs("embed", "align name hspace vspace");
            addAttrs("param", "valuetype type");
            addAttrs("a", "charset name rev shape coords");
            addAttrs("br", "clear");
            addAttrs("applet", "codebase archive code object alt name width height align hspace vspace");
            addAttrs("img", "name longdesc align border hspace vspace");
            addAttrs("iframe", "longdesc frameborder marginwidth marginheight scrolling align");
            addAttrs("font basefont", "size color face");
            addAttrs("input", "usemap align");
            addAttrs("select");
            addAttrs("textarea");
            addAttrs("h1 h2 h3 h4 h5 h6 div p legend caption", "align");
            addAttrs("ul", "type compact");
            addAttrs("li", "type");
            addAttrs("ol dl menu dir", "compact");
            addAttrs("pre", "width xml:space");
            addAttrs("hr", "align noshade size width");
            addAttrs("isindex", "prompt");
            addAttrs("table", "summary width frame rules cellspacing cellpadding align bgcolor");
            addAttrs("col", "width align char charoff valign");
            addAttrs("colgroup", "width align char charoff valign");
            addAttrs("thead", "align char charoff valign");
            addAttrs("tr", "align char charoff valign bgcolor");
            addAttrs("th", "axis align char charoff valign nowrap bgcolor width height");
            addAttrs("form", "accept");
            addAttrs("td", "abbr axis scope align char charoff valign nowrap bgcolor width height");
            addAttrs("tfoot", "align char charoff valign");
            addAttrs("tbody", "align char charoff valign");
            addAttrs("area", "nohref");
            addAttrs("body", "background bgcolor text link vlink alink");
          }
          if (type2 !== "html4") {
            addAttrs("input button select textarea", "autofocus");
            addAttrs("input textarea", "placeholder");
            addAttrs("a", "download");
            addAttrs("link script img", "crossorigin");
            addAttrs("img", "loading");
            addAttrs("iframe", "sandbox seamless allowfullscreen loading");
          }
          each$h(split$1("a form meter progress dfn"), function(name2) {
            if (schema[name2]) {
              delete schema[name2].children[name2];
            }
          });
          delete schema.caption.children.table;
          delete schema.script;
          mapCache[type2] = schema;
          return schema;
        };
        var compileElementMap = function(value2, mode) {
          var styles;
          if (value2) {
            styles = {};
            if (typeof value2 === "string") {
              value2 = { "*": value2 };
            }
            each$h(value2, function(value3, key) {
              styles[key] = styles[key.toUpperCase()] = mode === "map" ? makeMap$2(value3, /[, ]/) : explode$3(value3, /[, ]/);
            });
          }
          return styles;
        };
        var Schema = function(settings) {
          var elements2 = {};
          var children2 = {};
          var patternElements = [];
          var customElementsMap = {}, specialElements = {};
          var createLookupTable = function(option, defaultValue, extendWith) {
            var value2 = settings[option];
            if (!value2) {
              value2 = mapCache[option];
              if (!value2) {
                value2 = makeMap$2(defaultValue, " ", makeMap$2(defaultValue.toUpperCase(), " "));
                value2 = extend$5(value2, extendWith);
                mapCache[option] = value2;
              }
            } else {
              value2 = makeMap$2(value2, /[, ]/, makeMap$2(value2.toUpperCase(), /[, ]/));
            }
            return value2;
          };
          settings = settings || {};
          var schemaItems = compileSchema(settings.schema);
          if (settings.verify_html === false) {
            settings.valid_elements = "*[*]";
          }
          var validStyles = compileElementMap(settings.valid_styles);
          var invalidStyles = compileElementMap(settings.invalid_styles, "map");
          var validClasses = compileElementMap(settings.valid_classes, "map");
          var whiteSpaceElementsMap = createLookupTable("whitespace_elements", "pre script noscript style textarea video audio iframe object code");
          var selfClosingElementsMap = createLookupTable("self_closing_elements", "colgroup dd dt li option p td tfoot th thead tr");
          var shortEndedElementsMap = createLookupTable("short_ended_elements", "area base basefont br col frame hr img input isindex link meta param embed source wbr track");
          var boolAttrMap = createLookupTable("boolean_attributes", "checked compact declare defer disabled ismap multiple nohref noresize noshade nowrap readonly selected autoplay loop controls");
          var nonEmptyOrMoveCaretBeforeOnEnter = "td th iframe video audio object script code";
          var nonEmptyElementsMap = createLookupTable("non_empty_elements", nonEmptyOrMoveCaretBeforeOnEnter + " pre", shortEndedElementsMap);
          var moveCaretBeforeOnEnterElementsMap = createLookupTable("move_caret_before_on_enter_elements", nonEmptyOrMoveCaretBeforeOnEnter + " table", shortEndedElementsMap);
          var textBlockElementsMap = createLookupTable("text_block_elements", "h1 h2 h3 h4 h5 h6 p div address pre form blockquote center dir fieldset header footer article section hgroup aside main nav figure");
          var blockElementsMap = createLookupTable("block_elements", "hr table tbody thead tfoot th tr td li ol ul caption dl dt dd noscript menu isindex option datalist select optgroup figcaption details summary", textBlockElementsMap);
          var textInlineElementsMap = createLookupTable("text_inline_elements", "span strong b em i font strike u var cite dfn code mark q sup sub samp");
          each$h((settings.special || "script noscript iframe noframes noembed title style textarea xmp").split(" "), function(name2) {
            specialElements[name2] = new RegExp("</" + name2 + "[^>]*>", "gi");
          });
          var patternToRegExp = function(str) {
            return new RegExp("^" + str.replace(/([?+*])/g, ".$1") + "$");
          };
          var addValidElements = function(validElements) {
            var ei2, el, ai2, al, matches2, element, attr, attrData, elementName, attrName, attrType, attributes2, attributesOrder, prefix, outputName, globalAttributes, globalAttributesOrder, value2;
            var elementRuleRegExp = /^([#+\-])?([^\[!\/]+)(?:\/([^\[!]+))?(?:(!?)\[([^\]]+)])?$/, attrRuleRegExp = /^([!\-])?(\w+[\\:]:\w+|[^=:<]+)?(?:([=:<])(.*))?$/, hasPatternsRegExp = /[*?+]/;
            if (validElements) {
              var validElementsArr = split$1(validElements, ",");
              if (elements2["@"]) {
                globalAttributes = elements2["@"].attributes;
                globalAttributesOrder = elements2["@"].attributesOrder;
              }
              for (ei2 = 0, el = validElementsArr.length; ei2 < el; ei2++) {
                matches2 = elementRuleRegExp.exec(validElementsArr[ei2]);
                if (matches2) {
                  prefix = matches2[1];
                  elementName = matches2[2];
                  outputName = matches2[3];
                  attrData = matches2[5];
                  attributes2 = {};
                  attributesOrder = [];
                  element = {
                    attributes: attributes2,
                    attributesOrder
                  };
                  if (prefix === "#") {
                    element.paddEmpty = true;
                  }
                  if (prefix === "-") {
                    element.removeEmpty = true;
                  }
                  if (matches2[4] === "!") {
                    element.removeEmptyAttrs = true;
                  }
                  if (globalAttributes) {
                    each$j(globalAttributes, function(value3, key) {
                      attributes2[key] = value3;
                    });
                    attributesOrder.push.apply(attributesOrder, globalAttributesOrder);
                  }
                  if (attrData) {
                    attrData = split$1(attrData, "|");
                    for (ai2 = 0, al = attrData.length; ai2 < al; ai2++) {
                      matches2 = attrRuleRegExp.exec(attrData[ai2]);
                      if (matches2) {
                        attr = {};
                        attrType = matches2[1];
                        attrName = matches2[2].replace(/[\\:]:/g, ":");
                        prefix = matches2[3];
                        value2 = matches2[4];
                        if (attrType === "!") {
                          element.attributesRequired = element.attributesRequired || [];
                          element.attributesRequired.push(attrName);
                          attr.required = true;
                        }
                        if (attrType === "-") {
                          delete attributes2[attrName];
                          attributesOrder.splice(inArray$2(attributesOrder, attrName), 1);
                          continue;
                        }
                        if (prefix) {
                          if (prefix === "=") {
                            element.attributesDefault = element.attributesDefault || [];
                            element.attributesDefault.push({
                              name: attrName,
                              value: value2
                            });
                            attr.defaultValue = value2;
                          }
                          if (prefix === ":") {
                            element.attributesForced = element.attributesForced || [];
                            element.attributesForced.push({
                              name: attrName,
                              value: value2
                            });
                            attr.forcedValue = value2;
                          }
                          if (prefix === "<") {
                            attr.validValues = makeMap$2(value2, "?");
                          }
                        }
                        if (hasPatternsRegExp.test(attrName)) {
                          element.attributePatterns = element.attributePatterns || [];
                          attr.pattern = patternToRegExp(attrName);
                          element.attributePatterns.push(attr);
                        } else {
                          if (!attributes2[attrName]) {
                            attributesOrder.push(attrName);
                          }
                          attributes2[attrName] = attr;
                        }
                      }
                    }
                  }
                  if (!globalAttributes && elementName === "@") {
                    globalAttributes = attributes2;
                    globalAttributesOrder = attributesOrder;
                  }
                  if (outputName) {
                    element.outputName = elementName;
                    elements2[outputName] = element;
                  }
                  if (hasPatternsRegExp.test(elementName)) {
                    element.pattern = patternToRegExp(elementName);
                    patternElements.push(element);
                  } else {
                    elements2[elementName] = element;
                  }
                }
              }
            }
          };
          var setValidElements = function(validElements) {
            elements2 = {};
            patternElements = [];
            addValidElements(validElements);
            each$h(schemaItems, function(element, name2) {
              children2[name2] = element.children;
            });
          };
          var addCustomElements = function(customElements2) {
            var customElementRegExp = /^(~)?(.+)$/;
            if (customElements2) {
              mapCache.text_block_elements = mapCache.block_elements = null;
              each$h(split$1(customElements2, ","), function(rule) {
                var matches2 = customElementRegExp.exec(rule), inline = matches2[1] === "~", cloneName = inline ? "span" : "div", name2 = matches2[2];
                children2[name2] = children2[cloneName];
                customElementsMap[name2] = cloneName;
                if (!inline) {
                  blockElementsMap[name2.toUpperCase()] = {};
                  blockElementsMap[name2] = {};
                }
                if (!elements2[name2]) {
                  var customRule = elements2[cloneName];
                  customRule = extend$5({}, customRule);
                  delete customRule.removeEmptyAttrs;
                  delete customRule.removeEmpty;
                  elements2[name2] = customRule;
                }
                each$h(children2, function(element, elmName) {
                  if (element[cloneName]) {
                    children2[elmName] = element = extend$5({}, children2[elmName]);
                    element[name2] = element[cloneName];
                  }
                });
              });
            }
          };
          var addValidChildren = function(validChildren) {
            var childRuleRegExp = /^([+\-]?)([A-Za-z0-9_\-.\u00b7\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u037d\u037f-\u1fff\u200c-\u200d\u203f-\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]+)\[([^\]]+)]$/;
            mapCache[settings.schema] = null;
            if (validChildren) {
              each$h(split$1(validChildren, ","), function(rule) {
                var matches2 = childRuleRegExp.exec(rule);
                var parent2, prefix;
                if (matches2) {
                  prefix = matches2[1];
                  if (prefix) {
                    parent2 = children2[matches2[2]];
                  } else {
                    parent2 = children2[matches2[2]] = { "#comment": {} };
                  }
                  parent2 = children2[matches2[2]];
                  each$h(split$1(matches2[3], "|"), function(child2) {
                    if (prefix === "-") {
                      delete parent2[child2];
                    } else {
                      parent2[child2] = {};
                    }
                  });
                }
              });
            }
          };
          var getElementRule = function(name2) {
            var element = elements2[name2], i2;
            if (element) {
              return element;
            }
            i2 = patternElements.length;
            while (i2--) {
              element = patternElements[i2];
              if (element.pattern.test(name2)) {
                return element;
              }
            }
          };
          if (!settings.valid_elements) {
            each$h(schemaItems, function(element, name2) {
              elements2[name2] = {
                attributes: element.attributes,
                attributesOrder: element.attributesOrder
              };
              children2[name2] = element.children;
            });
            if (settings.schema !== "html5") {
              each$h(split$1("strong/b em/i"), function(item) {
                var items = split$1(item, "/");
                elements2[items[1]].outputName = items[0];
              });
            }
            each$h(split$1("ol ul sub sup blockquote span font a table tbody strong em b i"), function(name2) {
              if (elements2[name2]) {
                elements2[name2].removeEmpty = true;
              }
            });
            each$h(split$1("p h1 h2 h3 h4 h5 h6 th td pre div address caption li"), function(name2) {
              elements2[name2].paddEmpty = true;
            });
            each$h(split$1("span"), function(name2) {
              elements2[name2].removeEmptyAttrs = true;
            });
          } else {
            setValidElements(settings.valid_elements);
          }
          addCustomElements(settings.custom_elements);
          addValidChildren(settings.valid_children);
          addValidElements(settings.extended_valid_elements);
          addValidChildren("+ol[ul|ol],+ul[ul|ol]");
          each$h({
            dd: "dl",
            dt: "dl",
            li: "ul ol",
            td: "tr",
            th: "tr",
            tr: "tbody thead tfoot",
            tbody: "table",
            thead: "table",
            tfoot: "table",
            legend: "fieldset",
            area: "map",
            param: "video audio object"
          }, function(parents2, item) {
            if (elements2[item]) {
              elements2[item].parentsRequired = split$1(parents2);
            }
          });
          if (settings.invalid_elements) {
            each$h(explode$3(settings.invalid_elements), function(item) {
              if (elements2[item]) {
                delete elements2[item];
              }
            });
          }
          if (!getElementRule("span")) {
            addValidElements("span[!data-mce-type|*]");
          }
          var getValidStyles = constant(validStyles);
          var getInvalidStyles = constant(invalidStyles);
          var getValidClasses = constant(validClasses);
          var getBoolAttrs = constant(boolAttrMap);
          var getBlockElements = constant(blockElementsMap);
          var getTextBlockElements = constant(textBlockElementsMap);
          var getTextInlineElements = constant(textInlineElementsMap);
          var getShortEndedElements = constant(shortEndedElementsMap);
          var getSelfClosingElements = constant(selfClosingElementsMap);
          var getNonEmptyElements = constant(nonEmptyElementsMap);
          var getMoveCaretBeforeOnEnterElements = constant(moveCaretBeforeOnEnterElementsMap);
          var getWhiteSpaceElements = constant(whiteSpaceElementsMap);
          var getSpecialElements = constant(specialElements);
          var isValidChild = function(name2, child2) {
            var parent2 = children2[name2.toLowerCase()];
            return !!(parent2 && parent2[child2.toLowerCase()]);
          };
          var isValid3 = function(name2, attr) {
            var attrPatterns, i2;
            var rule = getElementRule(name2);
            if (rule) {
              if (attr) {
                if (rule.attributes[attr]) {
                  return true;
                }
                attrPatterns = rule.attributePatterns;
                if (attrPatterns) {
                  i2 = attrPatterns.length;
                  while (i2--) {
                    if (attrPatterns[i2].pattern.test(name2)) {
                      return true;
                    }
                  }
                }
              } else {
                return true;
              }
            }
            return false;
          };
          var getCustomElements = constant(customElementsMap);
          return {
            children: children2,
            elements: elements2,
            getValidStyles,
            getValidClasses,
            getBlockElements,
            getInvalidStyles,
            getShortEndedElements,
            getTextBlockElements,
            getTextInlineElements,
            getBoolAttrs,
            getElementRule,
            getSelfClosingElements,
            getNonEmptyElements,
            getMoveCaretBeforeOnEnterElements,
            getWhiteSpaceElements,
            getSpecialElements,
            isValidChild,
            isValid: isValid3,
            getCustomElements,
            addValidElements,
            setValidElements,
            addCustomElements,
            addValidChildren
          };
        };
        var toHex = function(match3, r3, g2, b2) {
          var hex2 = function(val) {
            val = parseInt(val, 10).toString(16);
            return val.length > 1 ? val : "0" + val;
          };
          return "#" + hex2(r3) + hex2(g2) + hex2(b2);
        };
        var Styles = function(settings, schema) {
          var _this = this;
          var rgbRegExp = /rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*\)/gi;
          var urlOrStrRegExp = /(?:url(?:(?:\(\s*\"([^\"]+)\"\s*\))|(?:\(\s*\'([^\']+)\'\s*\))|(?:\(\s*([^)\s]+)\s*\))))|(?:\'([^\']+)\')|(?:\"([^\"]+)\")/gi;
          var styleRegExp = /\s*([^:]+):\s*([^;]+);?/g;
          var trimRightRegExp = /\s+$/;
          var i2;
          var encodingLookup = {};
          var validStyles;
          var invalidStyles;
          var invisibleChar = zeroWidth;
          settings = settings || {};
          if (schema) {
            validStyles = schema.getValidStyles();
            invalidStyles = schema.getInvalidStyles();
          }
          var encodingItems = (`\\" \\' \\; \\: ; : ` + invisibleChar).split(" ");
          for (i2 = 0; i2 < encodingItems.length; i2++) {
            encodingLookup[encodingItems[i2]] = invisibleChar + i2;
            encodingLookup[invisibleChar + i2] = encodingItems[i2];
          }
          return {
            toHex: function(color2) {
              return color2.replace(rgbRegExp, toHex);
            },
            parse: function(css) {
              var styles = {};
              var matches2, name2, value2, isEncoded;
              var urlConverter = settings.url_converter;
              var urlConverterScope = settings.url_converter_scope || _this;
              var compress = function(prefix, suffix, noJoin) {
                var top2 = styles[prefix + "-top" + suffix];
                if (!top2) {
                  return;
                }
                var right2 = styles[prefix + "-right" + suffix];
                if (!right2) {
                  return;
                }
                var bottom2 = styles[prefix + "-bottom" + suffix];
                if (!bottom2) {
                  return;
                }
                var left2 = styles[prefix + "-left" + suffix];
                if (!left2) {
                  return;
                }
                var box = [
                  top2,
                  right2,
                  bottom2,
                  left2
                ];
                i2 = box.length - 1;
                while (i2--) {
                  if (box[i2] !== box[i2 + 1]) {
                    break;
                  }
                }
                if (i2 > -1 && noJoin) {
                  return;
                }
                styles[prefix + suffix] = i2 === -1 ? box[0] : box.join(" ");
                delete styles[prefix + "-top" + suffix];
                delete styles[prefix + "-right" + suffix];
                delete styles[prefix + "-bottom" + suffix];
                delete styles[prefix + "-left" + suffix];
              };
              var canCompress = function(key) {
                var value3 = styles[key], i3;
                if (!value3) {
                  return;
                }
                value3 = value3.split(" ");
                i3 = value3.length;
                while (i3--) {
                  if (value3[i3] !== value3[0]) {
                    return false;
                  }
                }
                styles[key] = value3[0];
                return true;
              };
              var compress2 = function(target, a2, b2, c2) {
                if (!canCompress(a2)) {
                  return;
                }
                if (!canCompress(b2)) {
                  return;
                }
                if (!canCompress(c2)) {
                  return;
                }
                styles[target] = styles[a2] + " " + styles[b2] + " " + styles[c2];
                delete styles[a2];
                delete styles[b2];
                delete styles[c2];
              };
              var encode = function(str) {
                isEncoded = true;
                return encodingLookup[str];
              };
              var decode2 = function(str, keepSlashes) {
                if (isEncoded) {
                  str = str.replace(/\uFEFF[0-9]/g, function(str2) {
                    return encodingLookup[str2];
                  });
                }
                if (!keepSlashes) {
                  str = str.replace(/\\([\'\";:])/g, "$1");
                }
                return str;
              };
              var decodeSingleHexSequence = function(escSeq) {
                return String.fromCharCode(parseInt(escSeq.slice(1), 16));
              };
              var decodeHexSequences = function(value3) {
                return value3.replace(/\\[0-9a-f]+/gi, decodeSingleHexSequence);
              };
              var processUrl = function(match3, url, url2, url3, str, str2) {
                str = str || str2;
                if (str) {
                  str = decode2(str);
                  return "'" + str.replace(/\'/g, "\\'") + "'";
                }
                url = decode2(url || url2 || url3);
                if (!settings.allow_script_urls) {
                  var scriptUrl = url.replace(/[\s\r\n]+/g, "");
                  if (/(java|vb)script:/i.test(scriptUrl)) {
                    return "";
                  }
                  if (!settings.allow_svg_data_urls && /^data:image\/svg/i.test(scriptUrl)) {
                    return "";
                  }
                }
                if (urlConverter) {
                  url = urlConverter.call(urlConverterScope, url, "style");
                }
                return "url('" + url.replace(/\'/g, "\\'") + "')";
              };
              if (css) {
                css = css.replace(/[\u0000-\u001F]/g, "");
                css = css.replace(/\\[\"\';:\uFEFF]/g, encode).replace(/\"[^\"]+\"|\'[^\']+\'/g, function(str) {
                  return str.replace(/[;:]/g, encode);
                });
                while (matches2 = styleRegExp.exec(css)) {
                  styleRegExp.lastIndex = matches2.index + matches2[0].length;
                  name2 = matches2[1].replace(trimRightRegExp, "").toLowerCase();
                  value2 = matches2[2].replace(trimRightRegExp, "");
                  if (name2 && value2) {
                    name2 = decodeHexSequences(name2);
                    value2 = decodeHexSequences(value2);
                    if (name2.indexOf(invisibleChar) !== -1 || name2.indexOf('"') !== -1) {
                      continue;
                    }
                    if (!settings.allow_script_urls && (name2 === "behavior" || /expression\s*\(|\/\*|\*\//.test(value2))) {
                      continue;
                    }
                    if (name2 === "font-weight" && value2 === "700") {
                      value2 = "bold";
                    } else if (name2 === "color" || name2 === "background-color") {
                      value2 = value2.toLowerCase();
                    }
                    value2 = value2.replace(rgbRegExp, toHex);
                    value2 = value2.replace(urlOrStrRegExp, processUrl);
                    styles[name2] = isEncoded ? decode2(value2, true) : value2;
                  }
                }
                compress("border", "", true);
                compress("border", "-width");
                compress("border", "-color");
                compress("border", "-style");
                compress("padding", "");
                compress("margin", "");
                compress2("border", "border-width", "border-style", "border-color");
                if (styles.border === "medium none") {
                  delete styles.border;
                }
                if (styles["border-image"] === "none") {
                  delete styles["border-image"];
                }
              }
              return styles;
            },
            serialize: function(styles, elementName) {
              var css = "";
              var serializeStyles = function(name2) {
                var value2;
                var styleList = validStyles[name2];
                if (styleList) {
                  for (var i_1 = 0, l2 = styleList.length; i_1 < l2; i_1++) {
                    name2 = styleList[i_1];
                    value2 = styles[name2];
                    if (value2) {
                      css += (css.length > 0 ? " " : "") + name2 + ": " + value2 + ";";
                    }
                  }
                }
              };
              var isValid3 = function(name2, elementName2) {
                var styleMap = invalidStyles["*"];
                if (styleMap && styleMap[name2]) {
                  return false;
                }
                styleMap = invalidStyles[elementName2];
                return !(styleMap && styleMap[name2]);
              };
              if (elementName && validStyles) {
                serializeStyles("*");
                serializeStyles(elementName);
              } else {
                each$j(styles, function(value2, name2) {
                  if (value2 && (!invalidStyles || isValid3(name2, elementName))) {
                    css += (css.length > 0 ? " " : "") + name2 + ": " + value2 + ";";
                  }
                });
              }
              return css;
            }
          };
        };
        var deprecated = {
          keyLocation: true,
          layerX: true,
          layerY: true,
          returnValue: true,
          webkitMovementX: true,
          webkitMovementY: true,
          keyIdentifier: true,
          mozPressure: true
        };
        var isNativeEvent = function(event) {
          return event instanceof Event || isFunction2(event.initEvent);
        };
        var hasIsDefaultPrevented = function(event) {
          return event.isDefaultPrevented === always || event.isDefaultPrevented === never;
        };
        var needsNormalizing = function(event) {
          return isNullable(event.preventDefault) || isNativeEvent(event);
        };
        var clone$2 = function(originalEvent, data2) {
          var event = data2 !== null && data2 !== void 0 ? data2 : {};
          for (var name_1 in originalEvent) {
            if (!has$2(deprecated, name_1)) {
              event[name_1] = originalEvent[name_1];
            }
          }
          if (isNonNullable(event.composedPath)) {
            event.composedPath = function() {
              return originalEvent.composedPath();
            };
          }
          return event;
        };
        var normalize$3 = function(type2, originalEvent, fallbackTarget, data2) {
          var _a;
          var event = clone$2(originalEvent, data2);
          event.type = type2;
          if (isNullable(event.target)) {
            event.target = (_a = event.srcElement) !== null && _a !== void 0 ? _a : fallbackTarget;
          }
          if (needsNormalizing(originalEvent)) {
            event.preventDefault = function() {
              event.defaultPrevented = true;
              event.isDefaultPrevented = always;
              if (isFunction2(originalEvent.preventDefault)) {
                originalEvent.preventDefault();
              } else if (isNativeEvent(originalEvent)) {
                originalEvent.returnValue = false;
              }
            };
            event.stopPropagation = function() {
              event.cancelBubble = true;
              event.isPropagationStopped = always;
              if (isFunction2(originalEvent.stopPropagation)) {
                originalEvent.stopPropagation();
              } else if (isNativeEvent(originalEvent)) {
                originalEvent.cancelBubble = true;
              }
            };
            event.stopImmediatePropagation = function() {
              event.isImmediatePropagationStopped = always;
              event.stopPropagation();
            };
            if (!hasIsDefaultPrevented(event)) {
              event.isDefaultPrevented = event.defaultPrevented === true ? always : never;
              event.isPropagationStopped = event.cancelBubble === true ? always : never;
              event.isImmediatePropagationStopped = never;
            }
          }
          return event;
        };
        var eventExpandoPrefix = "mce-data-";
        var mouseEventRe = /^(?:mouse|contextmenu)|click/;
        var addEvent = function(target, name2, callback2, capture) {
          if (target.addEventListener) {
            target.addEventListener(name2, callback2, capture || false);
          } else if (target.attachEvent) {
            target.attachEvent("on" + name2, callback2);
          }
        };
        var removeEvent = function(target, name2, callback2, capture) {
          if (target.removeEventListener) {
            target.removeEventListener(name2, callback2, capture || false);
          } else if (target.detachEvent) {
            target.detachEvent("on" + name2, callback2);
          }
        };
        var isMouseEvent = function(event) {
          return isNonNullable(event) && mouseEventRe.test(event.type);
        };
        var fix = function(originalEvent, data2) {
          var event = normalize$3(originalEvent.type, originalEvent, document, data2);
          if (isMouseEvent(originalEvent) && isUndefined(originalEvent.pageX) && !isUndefined(originalEvent.clientX)) {
            var eventDoc = event.target.ownerDocument || document;
            var doc2 = eventDoc.documentElement;
            var body = eventDoc.body;
            var mouseEvent = event;
            mouseEvent.pageX = originalEvent.clientX + (doc2 && doc2.scrollLeft || body && body.scrollLeft || 0) - (doc2 && doc2.clientLeft || body && body.clientLeft || 0);
            mouseEvent.pageY = originalEvent.clientY + (doc2 && doc2.scrollTop || body && body.scrollTop || 0) - (doc2 && doc2.clientTop || body && body.clientTop || 0);
          }
          if (isUndefined(event.metaKey)) {
            event.metaKey = false;
          }
          return event;
        };
        var bindOnReady = function(win, callback2, eventUtils) {
          var doc2 = win.document, event = { type: "ready" };
          if (eventUtils.domLoaded) {
            callback2(event);
            return;
          }
          var isDocReady = function() {
            return doc2.readyState === "complete" || doc2.readyState === "interactive" && doc2.body;
          };
          var readyHandler = function() {
            removeEvent(win, "DOMContentLoaded", readyHandler);
            removeEvent(win, "load", readyHandler);
            if (!eventUtils.domLoaded) {
              eventUtils.domLoaded = true;
              callback2(event);
            }
            win = null;
          };
          if (isDocReady()) {
            readyHandler();
          } else {
            addEvent(win, "DOMContentLoaded", readyHandler);
          }
          if (!eventUtils.domLoaded) {
            addEvent(win, "load", readyHandler);
          }
        };
        var EventUtils = function() {
          function EventUtils2() {
            this.domLoaded = false;
            this.events = {};
            this.count = 1;
            this.expando = eventExpandoPrefix + (+new Date()).toString(32);
            this.hasMouseEnterLeave = "onmouseenter" in document.documentElement;
            this.hasFocusIn = "onfocusin" in document.documentElement;
            this.count = 1;
          }
          EventUtils2.prototype.bind = function(target, names2, callback2, scope) {
            var self2 = this;
            var id2, callbackList, i2, name2, fakeName, nativeHandler, capture;
            var win = window;
            var defaultNativeHandler = function(evt) {
              self2.executeHandlers(fix(evt || win.event), id2);
            };
            if (!target || target.nodeType === 3 || target.nodeType === 8) {
              return;
            }
            if (!target[self2.expando]) {
              id2 = self2.count++;
              target[self2.expando] = id2;
              self2.events[id2] = {};
            } else {
              id2 = target[self2.expando];
            }
            scope = scope || target;
            var namesList = names2.split(" ");
            i2 = namesList.length;
            while (i2--) {
              name2 = namesList[i2];
              nativeHandler = defaultNativeHandler;
              fakeName = capture = false;
              if (name2 === "DOMContentLoaded") {
                name2 = "ready";
              }
              if (self2.domLoaded && name2 === "ready" && target.readyState === "complete") {
                callback2.call(scope, fix({ type: name2 }));
                continue;
              }
              if (!self2.hasMouseEnterLeave) {
                fakeName = self2.mouseEnterLeave[name2];
                if (fakeName) {
                  nativeHandler = function(evt) {
                    var current = evt.currentTarget;
                    var related = evt.relatedTarget;
                    if (related && current.contains) {
                      related = current.contains(related);
                    } else {
                      while (related && related !== current) {
                        related = related.parentNode;
                      }
                    }
                    if (!related) {
                      evt = fix(evt || win.event);
                      evt.type = evt.type === "mouseout" ? "mouseleave" : "mouseenter";
                      evt.target = current;
                      self2.executeHandlers(evt, id2);
                    }
                  };
                }
              }
              if (!self2.hasFocusIn && (name2 === "focusin" || name2 === "focusout")) {
                capture = true;
                fakeName = name2 === "focusin" ? "focus" : "blur";
                nativeHandler = function(evt) {
                  evt = fix(evt || win.event);
                  evt.type = evt.type === "focus" ? "focusin" : "focusout";
                  self2.executeHandlers(evt, id2);
                };
              }
              callbackList = self2.events[id2][name2];
              if (!callbackList) {
                self2.events[id2][name2] = callbackList = [{
                  func: callback2,
                  scope
                }];
                callbackList.fakeName = fakeName;
                callbackList.capture = capture;
                callbackList.nativeHandler = nativeHandler;
                if (name2 === "ready") {
                  bindOnReady(target, nativeHandler, self2);
                } else {
                  addEvent(target, fakeName || name2, nativeHandler, capture);
                }
              } else {
                if (name2 === "ready" && self2.domLoaded) {
                  callback2(fix({ type: name2 }));
                } else {
                  callbackList.push({
                    func: callback2,
                    scope
                  });
                }
              }
            }
            target = callbackList = null;
            return callback2;
          };
          EventUtils2.prototype.unbind = function(target, names2, callback2) {
            var callbackList, i2, ci2, name2, eventMap;
            if (!target || target.nodeType === 3 || target.nodeType === 8) {
              return this;
            }
            var id2 = target[this.expando];
            if (id2) {
              eventMap = this.events[id2];
              if (names2) {
                var namesList = names2.split(" ");
                i2 = namesList.length;
                while (i2--) {
                  name2 = namesList[i2];
                  callbackList = eventMap[name2];
                  if (callbackList) {
                    if (callback2) {
                      ci2 = callbackList.length;
                      while (ci2--) {
                        if (callbackList[ci2].func === callback2) {
                          var nativeHandler = callbackList.nativeHandler;
                          var fakeName = callbackList.fakeName, capture = callbackList.capture;
                          callbackList = callbackList.slice(0, ci2).concat(callbackList.slice(ci2 + 1));
                          callbackList.nativeHandler = nativeHandler;
                          callbackList.fakeName = fakeName;
                          callbackList.capture = capture;
                          eventMap[name2] = callbackList;
                        }
                      }
                    }
                    if (!callback2 || callbackList.length === 0) {
                      delete eventMap[name2];
                      removeEvent(target, callbackList.fakeName || name2, callbackList.nativeHandler, callbackList.capture);
                    }
                  }
                }
              } else {
                each$j(eventMap, function(callbackList2, name3) {
                  removeEvent(target, callbackList2.fakeName || name3, callbackList2.nativeHandler, callbackList2.capture);
                });
                eventMap = {};
              }
              for (name2 in eventMap) {
                if (has$2(eventMap, name2)) {
                  return this;
                }
              }
              delete this.events[id2];
              try {
                delete target[this.expando];
              } catch (ex) {
                target[this.expando] = null;
              }
            }
            return this;
          };
          EventUtils2.prototype.fire = function(target, name2, args) {
            var id2;
            if (!target || target.nodeType === 3 || target.nodeType === 8) {
              return this;
            }
            var event = fix({
              type: name2,
              target
            }, args);
            do {
              id2 = target[this.expando];
              if (id2) {
                this.executeHandlers(event, id2);
              }
              target = target.parentNode || target.ownerDocument || target.defaultView || target.parentWindow;
            } while (target && !event.isPropagationStopped());
            return this;
          };
          EventUtils2.prototype.clean = function(target) {
            var i2, children2;
            if (!target || target.nodeType === 3 || target.nodeType === 8) {
              return this;
            }
            if (target[this.expando]) {
              this.unbind(target);
            }
            if (!target.getElementsByTagName) {
              target = target.document;
            }
            if (target && target.getElementsByTagName) {
              this.unbind(target);
              children2 = target.getElementsByTagName("*");
              i2 = children2.length;
              while (i2--) {
                target = children2[i2];
                if (target[this.expando]) {
                  this.unbind(target);
                }
              }
            }
            return this;
          };
          EventUtils2.prototype.destroy = function() {
            this.events = {};
          };
          EventUtils2.prototype.cancel = function(e2) {
            if (e2) {
              e2.preventDefault();
              e2.stopImmediatePropagation();
            }
            return false;
          };
          EventUtils2.prototype.executeHandlers = function(evt, id2) {
            var container = this.events[id2];
            var callbackList = container && container[evt.type];
            if (callbackList) {
              for (var i2 = 0, l2 = callbackList.length; i2 < l2; i2++) {
                var callback2 = callbackList[i2];
                if (callback2 && callback2.func.call(callback2.scope, evt) === false) {
                  evt.preventDefault();
                }
                if (evt.isImmediatePropagationStopped()) {
                  return;
                }
              }
            }
          };
          EventUtils2.Event = new EventUtils2();
          return EventUtils2;
        }();
        var support, Expr, getText, isXML, tokenize2, compile, select$1, outermostContext, sortInput, hasDuplicate, setDocument, document$1, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains2, expando = "sizzle" + -new Date(), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), sortOrder = function(a2, b2) {
          if (a2 === b2) {
            hasDuplicate = true;
          }
          return 0;
        }, strundefined = "undefined", MAX_NEGATIVE = 1 << 31, hasOwn = {}.hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push$1 = arr.push, slice$1 = arr.slice, indexOf2 = arr.indexOf || function(elem) {
          var i2 = 0, len = this.length;
          for (; i2 < len; i2++) {
            if (this[i2] === elem) {
              return i2;
            }
          }
          return -1;
        }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", whitespace = "[\\x20\\t\\r\\n\\f]", identifier = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + "*([*^$|!~]?=)" + whitespace + `*(?:'((?:\\\\.|[^\\\\'])*)'|"((?:\\\\.|[^\\\\"])*)"|(` + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + identifier + `)(?:\\((('((?:\\\\.|[^\\\\'])*)'|"((?:\\\\.|[^\\\\"])*)")|((?:\\\\.|[^\\\\()[\\]]|` + attributes + ")*)|.*)\\)|)", rtrim = new RegExp("^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g"), rcomma = new RegExp("^" + whitespace + "*," + whitespace + "*"), rcombinators = new RegExp("^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*"), rattributeQuotes = new RegExp("=" + whitespace + `*([^\\]'"]*?)` + whitespace + "*\\]", "g"), rpseudo = new RegExp(pseudos), ridentifier = new RegExp("^" + identifier + "$"), matchExpr = {
          ID: new RegExp("^#(" + identifier + ")"),
          CLASS: new RegExp("^\\.(" + identifier + ")"),
          TAG: new RegExp("^(" + identifier + "|[*])"),
          ATTR: new RegExp("^" + attributes),
          PSEUDO: new RegExp("^" + pseudos),
          CHILD: new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i"),
          bool: new RegExp("^(?:" + booleans + ")$", "i"),
          needsContext: new RegExp("^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i")
        }, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, rquickExpr$1 = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, rescape = /'|\\/g, runescape = new RegExp("\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig"), funescape = function(_2, escaped, escapedWhitespace) {
          var high = "0x" + escaped - 65536;
          return high !== high || escapedWhitespace ? escaped : high < 0 ? String.fromCharCode(high + 65536) : String.fromCharCode(high >> 10 | 55296, high & 1023 | 56320);
        };
        try {
          push$1.apply(arr = slice$1.call(preferredDoc.childNodes), preferredDoc.childNodes);
          arr[preferredDoc.childNodes.length].nodeType;
        } catch (e2) {
          push$1 = {
            apply: arr.length ? function(target, els) {
              push_native.apply(target, slice$1.call(els));
            } : function(target, els) {
              var j2 = target.length, i2 = 0;
              while (target[j2++] = els[i2++]) {
              }
              target.length = j2 - 1;
            }
          };
        }
        var Sizzle = function(selector, context2, results, seed2) {
          var match3, elem, m2, nodeType, i2, groups, old, nid, newContext, newSelector;
          if ((context2 ? context2.ownerDocument || context2 : preferredDoc) !== document$1) {
            setDocument(context2);
          }
          context2 = context2 || document$1;
          results = results || [];
          if (!selector || typeof selector !== "string") {
            return results;
          }
          if ((nodeType = context2.nodeType) !== 1 && nodeType !== 9) {
            return [];
          }
          if (documentIsHTML && !seed2) {
            if (match3 = rquickExpr$1.exec(selector)) {
              if (m2 = match3[1]) {
                if (nodeType === 9) {
                  elem = context2.getElementById(m2);
                  if (elem && elem.parentNode) {
                    if (elem.id === m2) {
                      results.push(elem);
                      return results;
                    }
                  } else {
                    return results;
                  }
                } else {
                  if (context2.ownerDocument && (elem = context2.ownerDocument.getElementById(m2)) && contains2(context2, elem) && elem.id === m2) {
                    results.push(elem);
                    return results;
                  }
                }
              } else if (match3[2]) {
                push$1.apply(results, context2.getElementsByTagName(selector));
                return results;
              } else if ((m2 = match3[3]) && support.getElementsByClassName) {
                push$1.apply(results, context2.getElementsByClassName(m2));
                return results;
              }
            }
            if (support.qsa && (!rbuggyQSA || !rbuggyQSA.test(selector))) {
              nid = old = expando;
              newContext = context2;
              newSelector = nodeType === 9 && selector;
              if (nodeType === 1 && context2.nodeName.toLowerCase() !== "object") {
                groups = tokenize2(selector);
                if (old = context2.getAttribute("id")) {
                  nid = old.replace(rescape, "\\$&");
                } else {
                  context2.setAttribute("id", nid);
                }
                nid = "[id='" + nid + "'] ";
                i2 = groups.length;
                while (i2--) {
                  groups[i2] = nid + toSelector(groups[i2]);
                }
                newContext = rsibling.test(selector) && testContext(context2.parentNode) || context2;
                newSelector = groups.join(",");
              }
              if (newSelector) {
                try {
                  push$1.apply(results, newContext.querySelectorAll(newSelector));
                  return results;
                } catch (qsaError) {
                } finally {
                  if (!old) {
                    context2.removeAttribute("id");
                  }
                }
              }
            }
          }
          return select$1(selector.replace(rtrim, "$1"), context2, results, seed2);
        };
        function createCache() {
          var keys2 = [];
          function cache2(key, value2) {
            if (keys2.push(key + " ") > Expr.cacheLength) {
              delete cache2[keys2.shift()];
            }
            return cache2[key + " "] = value2;
          }
          return cache2;
        }
        function markFunction(fn3) {
          fn3[expando] = true;
          return fn3;
        }
        function siblingCheck(a2, b2) {
          var cur = b2 && a2, diff2 = cur && a2.nodeType === 1 && b2.nodeType === 1 && (~b2.sourceIndex || MAX_NEGATIVE) - (~a2.sourceIndex || MAX_NEGATIVE);
          if (diff2) {
            return diff2;
          }
          if (cur) {
            while (cur = cur.nextSibling) {
              if (cur === b2) {
                return -1;
              }
            }
          }
          return a2 ? 1 : -1;
        }
        function createInputPseudo(type2) {
          return function(elem) {
            var name2 = elem.nodeName.toLowerCase();
            return name2 === "input" && elem.type === type2;
          };
        }
        function createButtonPseudo(type2) {
          return function(elem) {
            var name2 = elem.nodeName.toLowerCase();
            return (name2 === "input" || name2 === "button") && elem.type === type2;
          };
        }
        function createPositionalPseudo(fn3) {
          return markFunction(function(argument) {
            argument = +argument;
            return markFunction(function(seed2, matches2) {
              var j2, matchIndexes = fn3([], seed2.length, argument), i2 = matchIndexes.length;
              while (i2--) {
                if (seed2[j2 = matchIndexes[i2]]) {
                  seed2[j2] = !(matches2[j2] = seed2[j2]);
                }
              }
            });
          });
        }
        function testContext(context2) {
          return context2 && typeof context2.getElementsByTagName !== strundefined && context2;
        }
        support = Sizzle.support = {};
        isXML = Sizzle.isXML = function(elem) {
          var documentElement2 = elem && (elem.ownerDocument || elem).documentElement;
          return documentElement2 ? documentElement2.nodeName !== "HTML" : false;
        };
        setDocument = Sizzle.setDocument = function(node) {
          var hasCompare, doc2 = node ? node.ownerDocument || node : preferredDoc, parent2 = doc2.defaultView;
          function getTop(win) {
            try {
              return win.top;
            } catch (ex) {
            }
            return null;
          }
          if (doc2 === document$1 || doc2.nodeType !== 9 || !doc2.documentElement) {
            return document$1;
          }
          document$1 = doc2;
          docElem = doc2.documentElement;
          documentIsHTML = !isXML(doc2);
          if (parent2 && parent2 !== getTop(parent2)) {
            if (parent2.addEventListener) {
              parent2.addEventListener("unload", function() {
                setDocument();
              }, false);
            } else if (parent2.attachEvent) {
              parent2.attachEvent("onunload", function() {
                setDocument();
              });
            }
          }
          support.attributes = true;
          support.getElementsByTagName = true;
          support.getElementsByClassName = rnative.test(doc2.getElementsByClassName);
          support.getById = true;
          Expr.find.ID = function(id2, context2) {
            if (typeof context2.getElementById !== strundefined && documentIsHTML) {
              var m2 = context2.getElementById(id2);
              return m2 && m2.parentNode ? [m2] : [];
            }
          };
          Expr.filter.ID = function(id2) {
            var attrId = id2.replace(runescape, funescape);
            return function(elem) {
              return elem.getAttribute("id") === attrId;
            };
          };
          Expr.find.TAG = support.getElementsByTagName ? function(tag, context2) {
            if (typeof context2.getElementsByTagName !== strundefined) {
              return context2.getElementsByTagName(tag);
            }
          } : function(tag, context2) {
            var elem, tmp = [], i2 = 0, results = context2.getElementsByTagName(tag);
            if (tag === "*") {
              while (elem = results[i2++]) {
                if (elem.nodeType === 1) {
                  tmp.push(elem);
                }
              }
              return tmp;
            }
            return results;
          };
          Expr.find.CLASS = support.getElementsByClassName && function(className, context2) {
            if (documentIsHTML) {
              return context2.getElementsByClassName(className);
            }
          };
          rbuggyMatches = [];
          rbuggyQSA = [];
          support.disconnectedMatch = true;
          rbuggyQSA = rbuggyQSA.length && new RegExp(rbuggyQSA.join("|"));
          rbuggyMatches = rbuggyMatches.length && new RegExp(rbuggyMatches.join("|"));
          hasCompare = rnative.test(docElem.compareDocumentPosition);
          contains2 = hasCompare || rnative.test(docElem.contains) ? function(a2, b2) {
            var adown = a2.nodeType === 9 ? a2.documentElement : a2, bup = b2 && b2.parentNode;
            return a2 === bup || !!(bup && bup.nodeType === 1 && (adown.contains ? adown.contains(bup) : a2.compareDocumentPosition && a2.compareDocumentPosition(bup) & 16));
          } : function(a2, b2) {
            if (b2) {
              while (b2 = b2.parentNode) {
                if (b2 === a2) {
                  return true;
                }
              }
            }
            return false;
          };
          sortOrder = hasCompare ? function(a2, b2) {
            if (a2 === b2) {
              hasDuplicate = true;
              return 0;
            }
            var compare = !a2.compareDocumentPosition - !b2.compareDocumentPosition;
            if (compare) {
              return compare;
            }
            compare = (a2.ownerDocument || a2) === (b2.ownerDocument || b2) ? a2.compareDocumentPosition(b2) : 1;
            if (compare & 1 || !support.sortDetached && b2.compareDocumentPosition(a2) === compare) {
              if (a2 === doc2 || a2.ownerDocument === preferredDoc && contains2(preferredDoc, a2)) {
                return -1;
              }
              if (b2 === doc2 || b2.ownerDocument === preferredDoc && contains2(preferredDoc, b2)) {
                return 1;
              }
              return sortInput ? indexOf2.call(sortInput, a2) - indexOf2.call(sortInput, b2) : 0;
            }
            return compare & 4 ? -1 : 1;
          } : function(a2, b2) {
            if (a2 === b2) {
              hasDuplicate = true;
              return 0;
            }
            var cur, i2 = 0, aup = a2.parentNode, bup = b2.parentNode, ap = [a2], bp = [b2];
            if (!aup || !bup) {
              return a2 === doc2 ? -1 : b2 === doc2 ? 1 : aup ? -1 : bup ? 1 : sortInput ? indexOf2.call(sortInput, a2) - indexOf2.call(sortInput, b2) : 0;
            } else if (aup === bup) {
              return siblingCheck(a2, b2);
            }
            cur = a2;
            while (cur = cur.parentNode) {
              ap.unshift(cur);
            }
            cur = b2;
            while (cur = cur.parentNode) {
              bp.unshift(cur);
            }
            while (ap[i2] === bp[i2]) {
              i2++;
            }
            return i2 ? siblingCheck(ap[i2], bp[i2]) : ap[i2] === preferredDoc ? -1 : bp[i2] === preferredDoc ? 1 : 0;
          };
          return doc2;
        };
        Sizzle.matches = function(expr, elements2) {
          return Sizzle(expr, null, null, elements2);
        };
        Sizzle.matchesSelector = function(elem, expr) {
          if ((elem.ownerDocument || elem) !== document$1) {
            setDocument(elem);
          }
          expr = expr.replace(rattributeQuotes, "='$1']");
          if (support.matchesSelector && documentIsHTML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && (!rbuggyQSA || !rbuggyQSA.test(expr))) {
            try {
              var ret = matches.call(elem, expr);
              if (ret || support.disconnectedMatch || elem.document && elem.document.nodeType !== 11) {
                return ret;
              }
            } catch (e2) {
            }
          }
          return Sizzle(expr, document$1, null, [elem]).length > 0;
        };
        Sizzle.contains = function(context2, elem) {
          if ((context2.ownerDocument || context2) !== document$1) {
            setDocument(context2);
          }
          return contains2(context2, elem);
        };
        Sizzle.attr = function(elem, name2) {
          if ((elem.ownerDocument || elem) !== document$1) {
            setDocument(elem);
          }
          var fn3 = Expr.attrHandle[name2.toLowerCase()], val = fn3 && hasOwn.call(Expr.attrHandle, name2.toLowerCase()) ? fn3(elem, name2, !documentIsHTML) : void 0;
          return val !== void 0 ? val : support.attributes || !documentIsHTML ? elem.getAttribute(name2) : (val = elem.getAttributeNode(name2)) && val.specified ? val.value : null;
        };
        Sizzle.error = function(msg) {
          throw new Error("Syntax error, unrecognized expression: " + msg);
        };
        Sizzle.uniqueSort = function(results) {
          var elem, duplicates = [], j2 = 0, i2 = 0;
          hasDuplicate = !support.detectDuplicates;
          sortInput = !support.sortStable && results.slice(0);
          results.sort(sortOrder);
          if (hasDuplicate) {
            while (elem = results[i2++]) {
              if (elem === results[i2]) {
                j2 = duplicates.push(i2);
              }
            }
            while (j2--) {
              results.splice(duplicates[j2], 1);
            }
          }
          sortInput = null;
          return results;
        };
        getText = Sizzle.getText = function(elem) {
          var node, ret = "", i2 = 0, nodeType = elem.nodeType;
          if (!nodeType) {
            while (node = elem[i2++]) {
              ret += getText(node);
            }
          } else if (nodeType === 1 || nodeType === 9 || nodeType === 11) {
            if (typeof elem.textContent === "string") {
              return elem.textContent;
            } else {
              for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
                ret += getText(elem);
              }
            }
          } else if (nodeType === 3 || nodeType === 4) {
            return elem.nodeValue;
          }
          return ret;
        };
        Expr = Sizzle.selectors = {
          cacheLength: 50,
          createPseudo: markFunction,
          match: matchExpr,
          attrHandle: {},
          find: {},
          relative: {
            ">": {
              dir: "parentNode",
              first: true
            },
            " ": { dir: "parentNode" },
            "+": {
              dir: "previousSibling",
              first: true
            },
            "~": { dir: "previousSibling" }
          },
          preFilter: {
            ATTR: function(match3) {
              match3[1] = match3[1].replace(runescape, funescape);
              match3[3] = (match3[3] || match3[4] || match3[5] || "").replace(runescape, funescape);
              if (match3[2] === "~=") {
                match3[3] = " " + match3[3] + " ";
              }
              return match3.slice(0, 4);
            },
            CHILD: function(match3) {
              match3[1] = match3[1].toLowerCase();
              if (match3[1].slice(0, 3) === "nth") {
                if (!match3[3]) {
                  Sizzle.error(match3[0]);
                }
                match3[4] = +(match3[4] ? match3[5] + (match3[6] || 1) : 2 * (match3[3] === "even" || match3[3] === "odd"));
                match3[5] = +(match3[7] + match3[8] || match3[3] === "odd");
              } else if (match3[3]) {
                Sizzle.error(match3[0]);
              }
              return match3;
            },
            PSEUDO: function(match3) {
              var excess, unquoted = !match3[6] && match3[2];
              if (matchExpr.CHILD.test(match3[0])) {
                return null;
              }
              if (match3[3]) {
                match3[2] = match3[4] || match3[5] || "";
              } else if (unquoted && rpseudo.test(unquoted) && (excess = tokenize2(unquoted, true)) && (excess = unquoted.indexOf(")", unquoted.length - excess) - unquoted.length)) {
                match3[0] = match3[0].slice(0, excess);
                match3[2] = unquoted.slice(0, excess);
              }
              return match3.slice(0, 3);
            }
          },
          filter: {
            TAG: function(nodeNameSelector) {
              var nodeName = nodeNameSelector.replace(runescape, funescape).toLowerCase();
              return nodeNameSelector === "*" ? function() {
                return true;
              } : function(elem) {
                return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
              };
            },
            CLASS: function(className) {
              var pattern = classCache[className + " "];
              return pattern || (pattern = new RegExp("(^|" + whitespace + ")" + className + "(" + whitespace + "|$)")) && classCache(className, function(elem) {
                return pattern.test(typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "");
              });
            },
            ATTR: function(name2, operator, check) {
              return function(elem) {
                var result = Sizzle.attr(elem, name2);
                if (result == null) {
                  return operator === "!=";
                }
                if (!operator) {
                  return true;
                }
                result += "";
                return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf(check) === 0 : operator === "*=" ? check && result.indexOf(check) > -1 : operator === "$=" ? check && result.slice(-check.length) === check : operator === "~=" ? (" " + result + " ").indexOf(check) > -1 : operator === "|=" ? result === check || result.slice(0, check.length + 1) === check + "-" : false;
              };
            },
            CHILD: function(type2, what, argument, first2, last2) {
              var simple = type2.slice(0, 3) !== "nth", forward = type2.slice(-4) !== "last", ofType = what === "of-type";
              return first2 === 1 && last2 === 0 ? function(elem) {
                return !!elem.parentNode;
              } : function(elem, context2, xml) {
                var cache2, outerCache, node, diff2, nodeIndex2, start5, dir2 = simple !== forward ? "nextSibling" : "previousSibling", parent2 = elem.parentNode, name2 = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType;
                if (parent2) {
                  if (simple) {
                    while (dir2) {
                      node = elem;
                      while (node = node[dir2]) {
                        if (ofType ? node.nodeName.toLowerCase() === name2 : node.nodeType === 1) {
                          return false;
                        }
                      }
                      start5 = dir2 = type2 === "only" && !start5 && "nextSibling";
                    }
                    return true;
                  }
                  start5 = [forward ? parent2.firstChild : parent2.lastChild];
                  if (forward && useCache) {
                    outerCache = parent2[expando] || (parent2[expando] = {});
                    cache2 = outerCache[type2] || [];
                    nodeIndex2 = cache2[0] === dirruns && cache2[1];
                    diff2 = cache2[0] === dirruns && cache2[2];
                    node = nodeIndex2 && parent2.childNodes[nodeIndex2];
                    while (node = ++nodeIndex2 && node && node[dir2] || (diff2 = nodeIndex2 = 0) || start5.pop()) {
                      if (node.nodeType === 1 && ++diff2 && node === elem) {
                        outerCache[type2] = [
                          dirruns,
                          nodeIndex2,
                          diff2
                        ];
                        break;
                      }
                    }
                  } else if (useCache && (cache2 = (elem[expando] || (elem[expando] = {}))[type2]) && cache2[0] === dirruns) {
                    diff2 = cache2[1];
                  } else {
                    while (node = ++nodeIndex2 && node && node[dir2] || (diff2 = nodeIndex2 = 0) || start5.pop()) {
                      if ((ofType ? node.nodeName.toLowerCase() === name2 : node.nodeType === 1) && ++diff2) {
                        if (useCache) {
                          (node[expando] || (node[expando] = {}))[type2] = [
                            dirruns,
                            diff2
                          ];
                        }
                        if (node === elem) {
                          break;
                        }
                      }
                    }
                  }
                  diff2 -= last2;
                  return diff2 === first2 || diff2 % first2 === 0 && diff2 / first2 >= 0;
                }
              };
            },
            PSEUDO: function(pseudo, argument) {
              var args, fn3 = Expr.pseudos[pseudo] || Expr.setFilters[pseudo.toLowerCase()] || Sizzle.error("unsupported pseudo: " + pseudo);
              if (fn3[expando]) {
                return fn3(argument);
              }
              if (fn3.length > 1) {
                args = [
                  pseudo,
                  pseudo,
                  "",
                  argument
                ];
                return Expr.setFilters.hasOwnProperty(pseudo.toLowerCase()) ? markFunction(function(seed2, matches2) {
                  var idx, matched = fn3(seed2, argument), i2 = matched.length;
                  while (i2--) {
                    idx = indexOf2.call(seed2, matched[i2]);
                    seed2[idx] = !(matches2[idx] = matched[i2]);
                  }
                }) : function(elem) {
                  return fn3(elem, 0, args);
                };
              }
              return fn3;
            }
          },
          pseudos: {
            not: markFunction(function(selector) {
              var input = [], results = [], matcher = compile(selector.replace(rtrim, "$1"));
              return matcher[expando] ? markFunction(function(seed2, matches2, context2, xml) {
                var elem, unmatched = matcher(seed2, null, xml, []), i2 = seed2.length;
                while (i2--) {
                  if (elem = unmatched[i2]) {
                    seed2[i2] = !(matches2[i2] = elem);
                  }
                }
              }) : function(elem, context2, xml) {
                input[0] = elem;
                matcher(input, null, xml, results);
                input[0] = null;
                return !results.pop();
              };
            }),
            has: markFunction(function(selector) {
              return function(elem) {
                return Sizzle(selector, elem).length > 0;
              };
            }),
            contains: markFunction(function(text) {
              text = text.replace(runescape, funescape);
              return function(elem) {
                return (elem.textContent || elem.innerText || getText(elem)).indexOf(text) > -1;
              };
            }),
            lang: markFunction(function(lang) {
              if (!ridentifier.test(lang || "")) {
                Sizzle.error("unsupported lang: " + lang);
              }
              lang = lang.replace(runescape, funescape).toLowerCase();
              return function(elem) {
                var elemLang;
                do {
                  if (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) {
                    elemLang = elemLang.toLowerCase();
                    return elemLang === lang || elemLang.indexOf(lang + "-") === 0;
                  }
                } while ((elem = elem.parentNode) && elem.nodeType === 1);
                return false;
              };
            }),
            target: function(elem) {
              var hash3 = window.location && window.location.hash;
              return hash3 && hash3.slice(1) === elem.id;
            },
            root: function(elem) {
              return elem === docElem;
            },
            focus: function(elem) {
              return elem === document$1.activeElement && (!document$1.hasFocus || document$1.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
            },
            enabled: function(elem) {
              return elem.disabled === false;
            },
            disabled: function(elem) {
              return elem.disabled === true;
            },
            checked: function(elem) {
              var nodeName = elem.nodeName.toLowerCase();
              return nodeName === "input" && !!elem.checked || nodeName === "option" && !!elem.selected;
            },
            selected: function(elem) {
              if (elem.parentNode) {
                elem.parentNode.selectedIndex;
              }
              return elem.selected === true;
            },
            empty: function(elem) {
              for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
                if (elem.nodeType < 6) {
                  return false;
                }
              }
              return true;
            },
            parent: function(elem) {
              return !Expr.pseudos.empty(elem);
            },
            header: function(elem) {
              return rheader.test(elem.nodeName);
            },
            input: function(elem) {
              return rinputs.test(elem.nodeName);
            },
            button: function(elem) {
              var name2 = elem.nodeName.toLowerCase();
              return name2 === "input" && elem.type === "button" || name2 === "button";
            },
            text: function(elem) {
              var attr;
              return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && ((attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text");
            },
            first: createPositionalPseudo(function() {
              return [0];
            }),
            last: createPositionalPseudo(function(matchIndexes, length) {
              return [length - 1];
            }),
            eq: createPositionalPseudo(function(matchIndexes, length, argument) {
              return [argument < 0 ? argument + length : argument];
            }),
            even: createPositionalPseudo(function(matchIndexes, length) {
              var i2 = 0;
              for (; i2 < length; i2 += 2) {
                matchIndexes.push(i2);
              }
              return matchIndexes;
            }),
            odd: createPositionalPseudo(function(matchIndexes, length) {
              var i2 = 1;
              for (; i2 < length; i2 += 2) {
                matchIndexes.push(i2);
              }
              return matchIndexes;
            }),
            lt: createPositionalPseudo(function(matchIndexes, length, argument) {
              var i2 = argument < 0 ? argument + length : argument;
              for (; --i2 >= 0; ) {
                matchIndexes.push(i2);
              }
              return matchIndexes;
            }),
            gt: createPositionalPseudo(function(matchIndexes, length, argument) {
              var i2 = argument < 0 ? argument + length : argument;
              for (; ++i2 < length; ) {
                matchIndexes.push(i2);
              }
              return matchIndexes;
            })
          }
        };
        Expr.pseudos.nth = Expr.pseudos.eq;
        each$k([
          "radio",
          "checkbox",
          "file",
          "password",
          "image"
        ], function(i2) {
          Expr.pseudos[i2] = createInputPseudo(i2);
        });
        each$k([
          "submit",
          "reset"
        ], function(i2) {
          Expr.pseudos[i2] = createButtonPseudo(i2);
        });
        function setFilters() {
        }
        setFilters.prototype = Expr.filters = Expr.pseudos;
        Expr.setFilters = new setFilters();
        tokenize2 = Sizzle.tokenize = function(selector, parseOnly) {
          var matched, match3, tokens, type2, soFar, groups, preFilters, cached2 = tokenCache[selector + " "];
          if (cached2) {
            return parseOnly ? 0 : cached2.slice(0);
          }
          soFar = selector;
          groups = [];
          preFilters = Expr.preFilter;
          while (soFar) {
            if (!matched || (match3 = rcomma.exec(soFar))) {
              if (match3) {
                soFar = soFar.slice(match3[0].length) || soFar;
              }
              groups.push(tokens = []);
            }
            matched = false;
            if (match3 = rcombinators.exec(soFar)) {
              matched = match3.shift();
              tokens.push({
                value: matched,
                type: match3[0].replace(rtrim, " ")
              });
              soFar = soFar.slice(matched.length);
            }
            for (type2 in Expr.filter) {
              if (!Expr.filter.hasOwnProperty(type2)) {
                continue;
              }
              if ((match3 = matchExpr[type2].exec(soFar)) && (!preFilters[type2] || (match3 = preFilters[type2](match3)))) {
                matched = match3.shift();
                tokens.push({
                  value: matched,
                  type: type2,
                  matches: match3
                });
                soFar = soFar.slice(matched.length);
              }
            }
            if (!matched) {
              break;
            }
          }
          return parseOnly ? soFar.length : soFar ? Sizzle.error(selector) : tokenCache(selector, groups).slice(0);
        };
        function toSelector(tokens) {
          var i2 = 0, len = tokens.length, selector = "";
          for (; i2 < len; i2++) {
            selector += tokens[i2].value;
          }
          return selector;
        }
        function addCombinator(matcher, combinator, base) {
          var dir2 = combinator.dir, checkNonElements = base && dir2 === "parentNode", doneName = done++;
          return combinator.first ? function(elem, context2, xml) {
            while (elem = elem[dir2]) {
              if (elem.nodeType === 1 || checkNonElements) {
                return matcher(elem, context2, xml);
              }
            }
          } : function(elem, context2, xml) {
            var oldCache, outerCache, newCache = [
              dirruns,
              doneName
            ];
            if (xml) {
              while (elem = elem[dir2]) {
                if (elem.nodeType === 1 || checkNonElements) {
                  if (matcher(elem, context2, xml)) {
                    return true;
                  }
                }
              }
            } else {
              while (elem = elem[dir2]) {
                if (elem.nodeType === 1 || checkNonElements) {
                  outerCache = elem[expando] || (elem[expando] = {});
                  if ((oldCache = outerCache[dir2]) && oldCache[0] === dirruns && oldCache[1] === doneName) {
                    return newCache[2] = oldCache[2];
                  } else {
                    outerCache[dir2] = newCache;
                    if (newCache[2] = matcher(elem, context2, xml)) {
                      return true;
                    }
                  }
                }
              }
            }
          };
        }
        function elementMatcher(matchers) {
          return matchers.length > 1 ? function(elem, context2, xml) {
            var i2 = matchers.length;
            while (i2--) {
              if (!matchers[i2](elem, context2, xml)) {
                return false;
              }
            }
            return true;
          } : matchers[0];
        }
        function multipleContexts(selector, contexts, results) {
          var i2 = 0, len = contexts.length;
          for (; i2 < len; i2++) {
            Sizzle(selector, contexts[i2], results);
          }
          return results;
        }
        function condense(unmatched, map4, filter2, context2, xml) {
          var elem, newUnmatched = [], i2 = 0, len = unmatched.length, mapped = map4 != null;
          for (; i2 < len; i2++) {
            if (elem = unmatched[i2]) {
              if (!filter2 || filter2(elem, context2, xml)) {
                newUnmatched.push(elem);
                if (mapped) {
                  map4.push(i2);
                }
              }
            }
          }
          return newUnmatched;
        }
        function setMatcher(preFilter, selector, matcher, postFilter, postFinder, postSelector) {
          if (postFilter && !postFilter[expando]) {
            postFilter = setMatcher(postFilter);
          }
          if (postFinder && !postFinder[expando]) {
            postFinder = setMatcher(postFinder, postSelector);
          }
          return markFunction(function(seed2, results, context2, xml) {
            var temp, i2, elem, preMap = [], postMap = [], preexisting = results.length, elems = seed2 || multipleContexts(selector || "*", context2.nodeType ? [context2] : context2, []), matcherIn = preFilter && (seed2 || !selector) ? condense(elems, preMap, preFilter, context2, xml) : elems, matcherOut = matcher ? postFinder || (seed2 ? preFilter : preexisting || postFilter) ? [] : results : matcherIn;
            if (matcher) {
              matcher(matcherIn, matcherOut, context2, xml);
            }
            if (postFilter) {
              temp = condense(matcherOut, postMap);
              postFilter(temp, [], context2, xml);
              i2 = temp.length;
              while (i2--) {
                if (elem = temp[i2]) {
                  matcherOut[postMap[i2]] = !(matcherIn[postMap[i2]] = elem);
                }
              }
            }
            if (seed2) {
              if (postFinder || preFilter) {
                if (postFinder) {
                  temp = [];
                  i2 = matcherOut.length;
                  while (i2--) {
                    if (elem = matcherOut[i2]) {
                      temp.push(matcherIn[i2] = elem);
                    }
                  }
                  postFinder(null, matcherOut = [], temp, xml);
                }
                i2 = matcherOut.length;
                while (i2--) {
                  if ((elem = matcherOut[i2]) && (temp = postFinder ? indexOf2.call(seed2, elem) : preMap[i2]) > -1) {
                    seed2[temp] = !(results[temp] = elem);
                  }
                }
              }
            } else {
              matcherOut = condense(matcherOut === results ? matcherOut.splice(preexisting, matcherOut.length) : matcherOut);
              if (postFinder) {
                postFinder(null, results, matcherOut, xml);
              } else {
                push$1.apply(results, matcherOut);
              }
            }
          });
        }
        function matcherFromTokens(tokens) {
          var checkContext, matcher, j2, len = tokens.length, leadingRelative = Expr.relative[tokens[0].type], implicitRelative = leadingRelative || Expr.relative[" "], i2 = leadingRelative ? 1 : 0, matchContext = addCombinator(function(elem) {
            return elem === checkContext;
          }, implicitRelative, true), matchAnyContext = addCombinator(function(elem) {
            return indexOf2.call(checkContext, elem) > -1;
          }, implicitRelative, true), matchers = [function(elem, context2, xml) {
            var ret = !leadingRelative && (xml || context2 !== outermostContext) || ((checkContext = context2).nodeType ? matchContext(elem, context2, xml) : matchAnyContext(elem, context2, xml));
            checkContext = null;
            return ret;
          }];
          for (; i2 < len; i2++) {
            if (matcher = Expr.relative[tokens[i2].type]) {
              matchers = [addCombinator(elementMatcher(matchers), matcher)];
            } else {
              matcher = Expr.filter[tokens[i2].type].apply(null, tokens[i2].matches);
              if (matcher[expando]) {
                j2 = ++i2;
                for (; j2 < len; j2++) {
                  if (Expr.relative[tokens[j2].type]) {
                    break;
                  }
                }
                return setMatcher(i2 > 1 && elementMatcher(matchers), i2 > 1 && toSelector(tokens.slice(0, i2 - 1).concat({ value: tokens[i2 - 2].type === " " ? "*" : "" })).replace(rtrim, "$1"), matcher, i2 < j2 && matcherFromTokens(tokens.slice(i2, j2)), j2 < len && matcherFromTokens(tokens = tokens.slice(j2)), j2 < len && toSelector(tokens));
              }
              matchers.push(matcher);
            }
          }
          return elementMatcher(matchers);
        }
        function matcherFromGroupMatchers(elementMatchers, setMatchers) {
          var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function(seed2, context2, xml, results, outermost) {
            var elem, j2, matcher, matchedCount = 0, i2 = "0", unmatched = seed2 && [], setMatched = [], contextBackup = outermostContext, elems = seed2 || byElement && Expr.find.TAG("*", outermost), dirrunsUnique = dirruns += contextBackup == null ? 1 : Math.random() || 0.1, len = elems.length;
            if (outermost) {
              outermostContext = context2 !== document$1 && context2;
            }
            for (; i2 !== len && (elem = elems[i2]) != null; i2++) {
              if (byElement && elem) {
                j2 = 0;
                while (matcher = elementMatchers[j2++]) {
                  if (matcher(elem, context2, xml)) {
                    results.push(elem);
                    break;
                  }
                }
                if (outermost) {
                  dirruns = dirrunsUnique;
                }
              }
              if (bySet) {
                if (elem = !matcher && elem) {
                  matchedCount--;
                }
                if (seed2) {
                  unmatched.push(elem);
                }
              }
            }
            matchedCount += i2;
            if (bySet && i2 !== matchedCount) {
              j2 = 0;
              while (matcher = setMatchers[j2++]) {
                matcher(unmatched, setMatched, context2, xml);
              }
              if (seed2) {
                if (matchedCount > 0) {
                  while (i2--) {
                    if (!(unmatched[i2] || setMatched[i2])) {
                      setMatched[i2] = pop.call(results);
                    }
                  }
                }
                setMatched = condense(setMatched);
              }
              push$1.apply(results, setMatched);
              if (outermost && !seed2 && setMatched.length > 0 && matchedCount + setMatchers.length > 1) {
                Sizzle.uniqueSort(results);
              }
            }
            if (outermost) {
              dirruns = dirrunsUnique;
              outermostContext = contextBackup;
            }
            return unmatched;
          };
          return bySet ? markFunction(superMatcher) : superMatcher;
        }
        compile = Sizzle.compile = function(selector, match3) {
          var i2, setMatchers = [], elementMatchers = [], cached2 = compilerCache[selector + " "];
          if (!cached2) {
            if (!match3) {
              match3 = tokenize2(selector);
            }
            i2 = match3.length;
            while (i2--) {
              cached2 = matcherFromTokens(match3[i2]);
              if (cached2[expando]) {
                setMatchers.push(cached2);
              } else {
                elementMatchers.push(cached2);
              }
            }
            cached2 = compilerCache(selector, matcherFromGroupMatchers(elementMatchers, setMatchers));
            cached2.selector = selector;
          }
          return cached2;
        };
        select$1 = Sizzle.select = function(selector, context2, results, seed2) {
          var i2, tokens, token, type2, find2, compiled = typeof selector === "function" && selector, match3 = !seed2 && tokenize2(selector = compiled.selector || selector);
          results = results || [];
          if (match3.length === 1) {
            tokens = match3[0] = match3[0].slice(0);
            if (tokens.length > 2 && (token = tokens[0]).type === "ID" && support.getById && context2.nodeType === 9 && documentIsHTML && Expr.relative[tokens[1].type]) {
              context2 = (Expr.find.ID(token.matches[0].replace(runescape, funescape), context2) || [])[0];
              if (!context2) {
                return results;
              } else if (compiled) {
                context2 = context2.parentNode;
              }
              selector = selector.slice(tokens.shift().value.length);
            }
            i2 = matchExpr.needsContext.test(selector) ? 0 : tokens.length;
            while (i2--) {
              token = tokens[i2];
              if (Expr.relative[type2 = token.type]) {
                break;
              }
              if (find2 = Expr.find[type2]) {
                if (seed2 = find2(token.matches[0].replace(runescape, funescape), rsibling.test(tokens[0].type) && testContext(context2.parentNode) || context2)) {
                  tokens.splice(i2, 1);
                  selector = seed2.length && toSelector(tokens);
                  if (!selector) {
                    push$1.apply(results, seed2);
                    return results;
                  }
                  break;
                }
              }
            }
          }
          (compiled || compile(selector, match3))(seed2, context2, !documentIsHTML, results, rsibling.test(selector) && testContext(context2.parentNode) || context2);
          return results;
        };
        support.sortStable = expando.split("").sort(sortOrder).join("") === expando;
        support.detectDuplicates = !!hasDuplicate;
        setDocument();
        support.sortDetached = true;
        var doc = document;
        var push = Array.prototype.push;
        var slice = Array.prototype.slice;
        var rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/;
        var Event$12 = EventUtils.Event;
        var skipUniques = Tools.makeMap("children,contents,next,prev");
        var isDefined = function(obj) {
          return typeof obj !== "undefined";
        };
        var isString = function(obj) {
          return typeof obj === "string";
        };
        var isWindow = function(obj) {
          return obj && obj === obj.window;
        };
        var createFragment$1 = function(html, fragDoc) {
          fragDoc = fragDoc || doc;
          var container = fragDoc.createElement("div");
          var frag = fragDoc.createDocumentFragment();
          container.innerHTML = html;
          var node;
          while (node = container.firstChild) {
            frag.appendChild(node);
          }
          return frag;
        };
        var domManipulate = function(targetNodes, sourceItem, callback2, reverse2) {
          var i2;
          if (isString(sourceItem)) {
            sourceItem = createFragment$1(sourceItem, getElementDocument(targetNodes[0]));
          } else if (sourceItem.length && !sourceItem.nodeType) {
            sourceItem = DomQuery.makeArray(sourceItem);
            if (reverse2) {
              for (i2 = sourceItem.length - 1; i2 >= 0; i2--) {
                domManipulate(targetNodes, sourceItem[i2], callback2, reverse2);
              }
            } else {
              for (i2 = 0; i2 < sourceItem.length; i2++) {
                domManipulate(targetNodes, sourceItem[i2], callback2, reverse2);
              }
            }
            return targetNodes;
          }
          if (sourceItem.nodeType) {
            i2 = targetNodes.length;
            while (i2--) {
              callback2.call(targetNodes[i2], sourceItem);
            }
          }
          return targetNodes;
        };
        var hasClass = function(node, className) {
          return node && className && (" " + node.className + " ").indexOf(" " + className + " ") !== -1;
        };
        var wrap$2 = function(elements2, wrapper, all2) {
          var lastParent, newWrapper;
          wrapper = DomQuery(wrapper)[0];
          elements2.each(function() {
            var self2 = this;
            if (!all2 || lastParent !== self2.parentNode) {
              lastParent = self2.parentNode;
              newWrapper = wrapper.cloneNode(false);
              self2.parentNode.insertBefore(newWrapper, self2);
              newWrapper.appendChild(self2);
            } else {
              newWrapper.appendChild(self2);
            }
          });
          return elements2;
        };
        var numericCssMap = Tools.makeMap("fillOpacity fontWeight lineHeight opacity orphans widows zIndex zoom", " ");
        var booleanMap = Tools.makeMap("checked compact declare defer disabled ismap multiple nohref noshade nowrap readonly selected", " ");
        var propFix = {
          for: "htmlFor",
          class: "className",
          readonly: "readOnly"
        };
        var cssFix = { float: "cssFloat" };
        var attrHooks = {}, cssHooks = {};
        var DomQueryConstructor = function(selector, context2) {
          return new DomQuery.fn.init(selector, context2);
        };
        var inArray$1 = function(item, array) {
          var i2;
          if (array.indexOf) {
            return array.indexOf(item);
          }
          i2 = array.length;
          while (i2--) {
            if (array[i2] === item) {
              return i2;
            }
          }
          return -1;
        };
        var whiteSpaceRegExp = /^\s*|\s*$/g;
        var trim$1 = function(str) {
          return str === null || str === void 0 ? "" : ("" + str).replace(whiteSpaceRegExp, "");
        };
        var each$g = function(obj, callback2) {
          var length, key, i2, value2;
          if (obj) {
            length = obj.length;
            if (length === void 0) {
              for (key in obj) {
                if (obj.hasOwnProperty(key)) {
                  value2 = obj[key];
                  if (callback2.call(value2, key, value2) === false) {
                    break;
                  }
                }
              }
            } else {
              for (i2 = 0; i2 < length; i2++) {
                value2 = obj[i2];
                if (callback2.call(value2, i2, value2) === false) {
                  break;
                }
              }
            }
          }
          return obj;
        };
        var grep$2 = function(array, callback2) {
          var out = [];
          each$g(array, function(i2, item) {
            if (callback2(item, i2)) {
              out.push(item);
            }
          });
          return out;
        };
        var getElementDocument = function(element) {
          if (!element) {
            return doc;
          }
          if (element.nodeType === 9) {
            return element;
          }
          return element.ownerDocument;
        };
        DomQueryConstructor.fn = DomQueryConstructor.prototype = {
          constructor: DomQueryConstructor,
          selector: "",
          context: null,
          length: 0,
          init: function(selector, context2) {
            var self2 = this;
            var match3, node;
            if (!selector) {
              return self2;
            }
            if (selector.nodeType) {
              self2.context = self2[0] = selector;
              self2.length = 1;
              return self2;
            }
            if (context2 && context2.nodeType) {
              self2.context = context2;
            } else {
              if (context2) {
                return DomQuery(selector).attr(context2);
              }
              self2.context = context2 = document;
            }
            if (isString(selector)) {
              self2.selector = selector;
              if (selector.charAt(0) === "<" && selector.charAt(selector.length - 1) === ">" && selector.length >= 3) {
                match3 = [
                  null,
                  selector,
                  null
                ];
              } else {
                match3 = rquickExpr.exec(selector);
              }
              if (match3) {
                if (match3[1]) {
                  node = createFragment$1(selector, getElementDocument(context2)).firstChild;
                  while (node) {
                    push.call(self2, node);
                    node = node.nextSibling;
                  }
                } else {
                  node = getElementDocument(context2).getElementById(match3[2]);
                  if (!node) {
                    return self2;
                  }
                  if (node.id !== match3[2]) {
                    return self2.find(selector);
                  }
                  self2.length = 1;
                  self2[0] = node;
                }
              } else {
                return DomQuery(context2).find(selector);
              }
            } else {
              this.add(selector, false);
            }
            return self2;
          },
          toArray: function() {
            return Tools.toArray(this);
          },
          add: function(items, sort2) {
            var self2 = this;
            var nodes, i2;
            if (isString(items)) {
              return self2.add(DomQuery(items));
            }
            if (sort2 !== false) {
              nodes = DomQuery.unique(self2.toArray().concat(DomQuery.makeArray(items)));
              self2.length = nodes.length;
              for (i2 = 0; i2 < nodes.length; i2++) {
                self2[i2] = nodes[i2];
              }
            } else {
              push.apply(self2, DomQuery.makeArray(items));
            }
            return self2;
          },
          attr: function(name2, value2) {
            var self2 = this;
            var hook;
            if (typeof name2 === "object") {
              each$g(name2, function(name3, value3) {
                self2.attr(name3, value3);
              });
            } else if (isDefined(value2)) {
              this.each(function() {
                var hook2;
                if (this.nodeType === 1) {
                  hook2 = attrHooks[name2];
                  if (hook2 && hook2.set) {
                    hook2.set(this, value2);
                    return;
                  }
                  if (value2 === null) {
                    this.removeAttribute(name2, 2);
                  } else {
                    this.setAttribute(name2, value2, 2);
                  }
                }
              });
            } else {
              if (self2[0] && self2[0].nodeType === 1) {
                hook = attrHooks[name2];
                if (hook && hook.get) {
                  return hook.get(self2[0], name2);
                }
                if (booleanMap[name2]) {
                  return self2.prop(name2) ? name2 : void 0;
                }
                value2 = self2[0].getAttribute(name2, 2);
                if (value2 === null) {
                  value2 = void 0;
                }
              }
              return value2;
            }
            return self2;
          },
          removeAttr: function(name2) {
            return this.attr(name2, null);
          },
          prop: function(name2, value2) {
            var self2 = this;
            name2 = propFix[name2] || name2;
            if (typeof name2 === "object") {
              each$g(name2, function(name3, value3) {
                self2.prop(name3, value3);
              });
            } else if (isDefined(value2)) {
              this.each(function() {
                if (this.nodeType === 1) {
                  this[name2] = value2;
                }
              });
            } else {
              if (self2[0] && self2[0].nodeType && name2 in self2[0]) {
                return self2[0][name2];
              }
              return value2;
            }
            return self2;
          },
          css: function(name2, value2) {
            var self2 = this;
            var elm, hook;
            var camel = function(name3) {
              return name3.replace(/-(\D)/g, function(a2, b2) {
                return b2.toUpperCase();
              });
            };
            var dashed = function(name3) {
              return name3.replace(/[A-Z]/g, function(a2) {
                return "-" + a2;
              });
            };
            if (typeof name2 === "object") {
              each$g(name2, function(name3, value3) {
                self2.css(name3, value3);
              });
            } else {
              if (isDefined(value2)) {
                name2 = camel(name2);
                if (typeof value2 === "number" && !numericCssMap[name2]) {
                  value2 = value2.toString() + "px";
                }
                self2.each(function() {
                  var style = this.style;
                  hook = cssHooks[name2];
                  if (hook && hook.set) {
                    hook.set(this, value2);
                    return;
                  }
                  try {
                    this.style[cssFix[name2] || name2] = value2;
                  } catch (ex) {
                  }
                  if (value2 === null || value2 === "") {
                    if (style.removeProperty) {
                      style.removeProperty(dashed(name2));
                    } else {
                      style.removeAttribute(name2);
                    }
                  }
                });
              } else {
                elm = self2[0];
                hook = cssHooks[name2];
                if (hook && hook.get) {
                  return hook.get(elm);
                }
                if (elm.ownerDocument.defaultView) {
                  try {
                    return elm.ownerDocument.defaultView.getComputedStyle(elm, null).getPropertyValue(dashed(name2));
                  } catch (ex) {
                    return void 0;
                  }
                } else if (elm.currentStyle) {
                  return elm.currentStyle[camel(name2)];
                } else {
                  return "";
                }
              }
            }
            return self2;
          },
          remove: function() {
            var self2 = this;
            var node, i2 = this.length;
            while (i2--) {
              node = self2[i2];
              Event$12.clean(node);
              if (node.parentNode) {
                node.parentNode.removeChild(node);
              }
            }
            return this;
          },
          empty: function() {
            var self2 = this;
            var node, i2 = this.length;
            while (i2--) {
              node = self2[i2];
              while (node.firstChild) {
                node.removeChild(node.firstChild);
              }
            }
            return this;
          },
          html: function(value2) {
            var self2 = this;
            var i2;
            if (isDefined(value2)) {
              i2 = self2.length;
              try {
                while (i2--) {
                  self2[i2].innerHTML = value2;
                }
              } catch (ex) {
                DomQuery(self2[i2]).empty().append(value2);
              }
              return self2;
            }
            return self2[0] ? self2[0].innerHTML : "";
          },
          text: function(value2) {
            var self2 = this;
            var i2;
            if (isDefined(value2)) {
              i2 = self2.length;
              while (i2--) {
                if ("innerText" in self2[i2]) {
                  self2[i2].innerText = value2;
                } else {
                  self2[0].textContent = value2;
                }
              }
              return self2;
            }
            return self2[0] ? self2[0].innerText || self2[0].textContent : "";
          },
          append: function() {
            return domManipulate(this, arguments, function(node) {
              if (this.nodeType === 1 || this.host && this.host.nodeType === 1) {
                this.appendChild(node);
              }
            });
          },
          prepend: function() {
            return domManipulate(this, arguments, function(node) {
              if (this.nodeType === 1 || this.host && this.host.nodeType === 1) {
                this.insertBefore(node, this.firstChild);
              }
            }, true);
          },
          before: function() {
            var self2 = this;
            if (self2[0] && self2[0].parentNode) {
              return domManipulate(self2, arguments, function(node) {
                this.parentNode.insertBefore(node, this);
              });
            }
            return self2;
          },
          after: function() {
            var self2 = this;
            if (self2[0] && self2[0].parentNode) {
              return domManipulate(self2, arguments, function(node) {
                this.parentNode.insertBefore(node, this.nextSibling);
              }, true);
            }
            return self2;
          },
          appendTo: function(val) {
            DomQuery(val).append(this);
            return this;
          },
          prependTo: function(val) {
            DomQuery(val).prepend(this);
            return this;
          },
          replaceWith: function(content) {
            return this.before(content).remove();
          },
          wrap: function(content) {
            return wrap$2(this, content);
          },
          wrapAll: function(content) {
            return wrap$2(this, content, true);
          },
          wrapInner: function(content) {
            this.each(function() {
              DomQuery(this).contents().wrapAll(content);
            });
            return this;
          },
          unwrap: function() {
            return this.parent().each(function() {
              DomQuery(this).replaceWith(this.childNodes);
            });
          },
          clone: function() {
            var result = [];
            this.each(function() {
              result.push(this.cloneNode(true));
            });
            return DomQuery(result);
          },
          addClass: function(className) {
            return this.toggleClass(className, true);
          },
          removeClass: function(className) {
            return this.toggleClass(className, false);
          },
          toggleClass: function(className, state) {
            var self2 = this;
            if (typeof className !== "string") {
              return self2;
            }
            if (className.indexOf(" ") !== -1) {
              each$g(className.split(" "), function() {
                self2.toggleClass(this, state);
              });
            } else {
              self2.each(function(index, node) {
                var classState = hasClass(node, className);
                if (classState !== state) {
                  var existingClassName = node.className;
                  if (classState) {
                    node.className = trim$1((" " + existingClassName + " ").replace(" " + className + " ", " "));
                  } else {
                    node.className += existingClassName ? " " + className : className;
                  }
                }
              });
            }
            return self2;
          },
          hasClass: function(className) {
            return hasClass(this[0], className);
          },
          each: function(callback2) {
            return each$g(this, callback2);
          },
          on: function(name2, callback2) {
            return this.each(function() {
              Event$12.bind(this, name2, callback2);
            });
          },
          off: function(name2, callback2) {
            return this.each(function() {
              Event$12.unbind(this, name2, callback2);
            });
          },
          trigger: function(name2) {
            return this.each(function() {
              if (typeof name2 === "object") {
                Event$12.fire(this, name2.type, name2);
              } else {
                Event$12.fire(this, name2);
              }
            });
          },
          show: function() {
            return this.css("display", "");
          },
          hide: function() {
            return this.css("display", "none");
          },
          slice: function() {
            return DomQuery(slice.apply(this, arguments));
          },
          eq: function(index) {
            return index === -1 ? this.slice(index) : this.slice(index, +index + 1);
          },
          first: function() {
            return this.eq(0);
          },
          last: function() {
            return this.eq(-1);
          },
          find: function(selector) {
            var i2, l2;
            var ret = [];
            for (i2 = 0, l2 = this.length; i2 < l2; i2++) {
              DomQuery.find(selector, this[i2], ret);
            }
            return DomQuery(ret);
          },
          filter: function(selector) {
            if (typeof selector === "function") {
              return DomQuery(grep$2(this.toArray(), function(item, i2) {
                return selector(i2, item);
              }));
            }
            return DomQuery(DomQuery.filter(selector, this.toArray()));
          },
          closest: function(selector) {
            var result = [];
            if (selector instanceof DomQuery) {
              selector = selector[0];
            }
            this.each(function(i2, node) {
              while (node) {
                if (typeof selector === "string" && DomQuery(node).is(selector)) {
                  result.push(node);
                  break;
                } else if (node === selector) {
                  result.push(node);
                  break;
                }
                node = node.parentNode;
              }
            });
            return DomQuery(result);
          },
          offset: function(offset2) {
            var elm, doc2, docElm;
            var x2 = 0, y2 = 0, pos;
            if (!offset2) {
              elm = this[0];
              if (elm) {
                doc2 = elm.ownerDocument;
                docElm = doc2.documentElement;
                if (elm.getBoundingClientRect) {
                  pos = elm.getBoundingClientRect();
                  x2 = pos.left + (docElm.scrollLeft || doc2.body.scrollLeft) - docElm.clientLeft;
                  y2 = pos.top + (docElm.scrollTop || doc2.body.scrollTop) - docElm.clientTop;
                }
              }
              return {
                left: x2,
                top: y2
              };
            }
            return this.css(offset2);
          },
          push,
          sort: Array.prototype.sort,
          splice: Array.prototype.splice
        };
        Tools.extend(DomQueryConstructor, {
          extend: Tools.extend,
          makeArray: function(object) {
            if (isWindow(object) || object.nodeType) {
              return [object];
            }
            return Tools.toArray(object);
          },
          inArray: inArray$1,
          isArray: Tools.isArray,
          each: each$g,
          trim: trim$1,
          grep: grep$2,
          find: Sizzle,
          expr: Sizzle.selectors,
          unique: Sizzle.uniqueSort,
          text: Sizzle.getText,
          contains: Sizzle.contains,
          filter: function(expr, elems, not2) {
            var i2 = elems.length;
            if (not2) {
              expr = ":not(" + expr + ")";
            }
            while (i2--) {
              if (elems[i2].nodeType !== 1) {
                elems.splice(i2, 1);
              }
            }
            if (elems.length === 1) {
              elems = DomQuery.find.matchesSelector(elems[0], expr) ? [elems[0]] : [];
            } else {
              elems = DomQuery.find.matches(expr, elems);
            }
            return elems;
          }
        });
        var dir = function(el, prop, until) {
          var matched = [];
          var cur = el[prop];
          if (typeof until !== "string" && until instanceof DomQuery) {
            until = until[0];
          }
          while (cur && cur.nodeType !== 9) {
            if (until !== void 0) {
              if (cur === until) {
                break;
              }
              if (typeof until === "string" && DomQuery(cur).is(until)) {
                break;
              }
            }
            if (cur.nodeType === 1) {
              matched.push(cur);
            }
            cur = cur[prop];
          }
          return matched;
        };
        var sibling$1 = function(node, siblingName, nodeType, until) {
          var result = [];
          if (until instanceof DomQuery) {
            until = until[0];
          }
          for (; node; node = node[siblingName]) {
            if (nodeType && node.nodeType !== nodeType) {
              continue;
            }
            if (until !== void 0) {
              if (node === until) {
                break;
              }
              if (typeof until === "string" && DomQuery(node).is(until)) {
                break;
              }
            }
            result.push(node);
          }
          return result;
        };
        var firstSibling = function(node, siblingName, nodeType) {
          for (node = node[siblingName]; node; node = node[siblingName]) {
            if (node.nodeType === nodeType) {
              return node;
            }
          }
          return null;
        };
        each$g({
          parent: function(node) {
            var parent2 = node.parentNode;
            return parent2 && parent2.nodeType !== 11 ? parent2 : null;
          },
          parents: function(node) {
            return dir(node, "parentNode");
          },
          next: function(node) {
            return firstSibling(node, "nextSibling", 1);
          },
          prev: function(node) {
            return firstSibling(node, "previousSibling", 1);
          },
          children: function(node) {
            return sibling$1(node.firstChild, "nextSibling", 1);
          },
          contents: function(node) {
            return Tools.toArray((node.nodeName === "iframe" ? node.contentDocument || node.contentWindow.document : node).childNodes);
          }
        }, function(name2, fn3) {
          DomQueryConstructor.fn[name2] = function(selector) {
            var self2 = this;
            var result = [];
            self2.each(function() {
              var nodes = fn3.call(result, this, selector, result);
              if (nodes) {
                if (DomQuery.isArray(nodes)) {
                  result.push.apply(result, nodes);
                } else {
                  result.push(nodes);
                }
              }
            });
            if (this.length > 1) {
              if (!skipUniques[name2]) {
                result = DomQuery.unique(result);
              }
              if (name2.indexOf("parents") === 0) {
                result = result.reverse();
              }
            }
            var wrappedResult = DomQuery(result);
            if (selector) {
              return wrappedResult.filter(selector);
            }
            return wrappedResult;
          };
        });
        each$g({
          parentsUntil: function(node, until) {
            return dir(node, "parentNode", until);
          },
          nextUntil: function(node, until) {
            return sibling$1(node, "nextSibling", 1, until).slice(1);
          },
          prevUntil: function(node, until) {
            return sibling$1(node, "previousSibling", 1, until).slice(1);
          }
        }, function(name2, fn3) {
          DomQueryConstructor.fn[name2] = function(selector, filter2) {
            var self2 = this;
            var result = [];
            self2.each(function() {
              var nodes = fn3.call(result, this, selector, result);
              if (nodes) {
                if (DomQuery.isArray(nodes)) {
                  result.push.apply(result, nodes);
                } else {
                  result.push(nodes);
                }
              }
            });
            if (this.length > 1) {
              result = DomQuery.unique(result);
              if (name2.indexOf("parents") === 0 || name2 === "prevUntil") {
                result = result.reverse();
              }
            }
            var wrappedResult = DomQuery(result);
            if (filter2) {
              return wrappedResult.filter(filter2);
            }
            return wrappedResult;
          };
        });
        DomQueryConstructor.fn.is = function(selector) {
          return !!selector && this.filter(selector).length > 0;
        };
        DomQueryConstructor.fn.init.prototype = DomQueryConstructor.fn;
        DomQueryConstructor.overrideDefaults = function(callback2) {
          var defaults2;
          var sub = function(selector, context2) {
            defaults2 = defaults2 || callback2();
            if (arguments.length === 0) {
              selector = defaults2.element;
            }
            if (!context2) {
              context2 = defaults2.context;
            }
            return new sub.fn.init(selector, context2);
          };
          DomQuery.extend(sub, this);
          return sub;
        };
        DomQueryConstructor.attrHooks = attrHooks;
        DomQueryConstructor.cssHooks = cssHooks;
        var DomQuery = DomQueryConstructor;
        var each$f = Tools.each;
        var grep$1 = Tools.grep;
        var isIE = Env.ie;
        var simpleSelectorRe = /^([a-z0-9],?)+$/i;
        var setupAttrHooks = function(styles, settings, getContext) {
          var keepValues = settings.keep_values;
          var keepUrlHook = {
            set: function($elm, value2, name2) {
              if (settings.url_converter && value2 !== null) {
                value2 = settings.url_converter.call(settings.url_converter_scope || getContext(), value2, name2, $elm[0]);
              }
              $elm.attr("data-mce-" + name2, value2).attr(name2, value2);
            },
            get: function($elm, name2) {
              return $elm.attr("data-mce-" + name2) || $elm.attr(name2);
            }
          };
          var attrHooks2 = {
            style: {
              set: function($elm, value2) {
                if (value2 !== null && typeof value2 === "object") {
                  $elm.css(value2);
                  return;
                }
                if (keepValues) {
                  $elm.attr("data-mce-style", value2);
                }
                if (value2 !== null && typeof value2 === "string") {
                  $elm.removeAttr("style");
                  $elm.css(styles.parse(value2));
                } else {
                  $elm.attr("style", value2);
                }
              },
              get: function($elm) {
                var value2 = $elm.attr("data-mce-style") || $elm.attr("style");
                value2 = styles.serialize(styles.parse(value2), $elm[0].nodeName);
                return value2;
              }
            }
          };
          if (keepValues) {
            attrHooks2.href = attrHooks2.src = keepUrlHook;
          }
          return attrHooks2;
        };
        var updateInternalStyleAttr = function(styles, $elm) {
          var rawValue = $elm.attr("style");
          var value2 = styles.serialize(styles.parse(rawValue), $elm[0].nodeName);
          if (!value2) {
            value2 = null;
          }
          $elm.attr("data-mce-style", value2);
        };
        var findNodeIndex = function(node, normalized) {
          var idx = 0, lastNodeType, nodeType;
          if (node) {
            for (lastNodeType = node.nodeType, node = node.previousSibling; node; node = node.previousSibling) {
              nodeType = node.nodeType;
              if (normalized && nodeType === 3) {
                if (nodeType === lastNodeType || !node.nodeValue.length) {
                  continue;
                }
              }
              idx++;
              lastNodeType = nodeType;
            }
          }
          return idx;
        };
        var DOMUtils = function(doc2, settings) {
          if (settings === void 0) {
            settings = {};
          }
          var addedStyles = {};
          var win = window;
          var files = {};
          var counter = 0;
          var stdMode = true;
          var boxModel = true;
          var styleSheetLoader = instance.forElement(SugarElement.fromDom(doc2), {
            contentCssCors: settings.contentCssCors,
            referrerPolicy: settings.referrerPolicy
          });
          var boundEvents = [];
          var schema = settings.schema ? settings.schema : Schema({});
          var styles = Styles({
            url_converter: settings.url_converter,
            url_converter_scope: settings.url_converter_scope
          }, settings.schema);
          var events = settings.ownEvents ? new EventUtils() : EventUtils.Event;
          var blockElementsMap = schema.getBlockElements();
          var $2 = DomQuery.overrideDefaults(function() {
            return {
              context: doc2,
              element: self2.getRoot()
            };
          });
          var isBlock2 = function(node) {
            if (typeof node === "string") {
              return !!blockElementsMap[node];
            } else if (node) {
              var type2 = node.nodeType;
              if (type2) {
                return !!(type2 === 1 && blockElementsMap[node.nodeName]);
              }
            }
            return false;
          };
          var get2 = function(elm) {
            return elm && doc2 && isString$1(elm) ? doc2.getElementById(elm) : elm;
          };
          var $$ = function(elm) {
            return $2(typeof elm === "string" ? get2(elm) : elm);
          };
          var getAttrib = function(elm, name2, defaultVal) {
            var hook, value2;
            var $elm = $$(elm);
            if ($elm.length) {
              hook = attrHooks2[name2];
              if (hook && hook.get) {
                value2 = hook.get($elm, name2);
              } else {
                value2 = $elm.attr(name2);
              }
            }
            if (typeof value2 === "undefined") {
              value2 = defaultVal || "";
            }
            return value2;
          };
          var getAttribs = function(elm) {
            var node = get2(elm);
            if (!node) {
              return [];
            }
            return node.attributes;
          };
          var setAttrib = function(elm, name2, value2) {
            if (value2 === "") {
              value2 = null;
            }
            var $elm = $$(elm);
            var originalValue = $elm.attr(name2);
            if (!$elm.length) {
              return;
            }
            var hook = attrHooks2[name2];
            if (hook && hook.set) {
              hook.set($elm, value2, name2);
            } else {
              $elm.attr(name2, value2);
            }
            if (originalValue !== value2 && settings.onSetAttrib) {
              settings.onSetAttrib({
                attrElm: $elm,
                attrName: name2,
                attrValue: value2
              });
            }
          };
          var clone3 = function(node, deep2) {
            if (!isIE || node.nodeType !== 1 || deep2) {
              return node.cloneNode(deep2);
            } else {
              var clone_1 = doc2.createElement(node.nodeName);
              each$f(getAttribs(node), function(attr) {
                setAttrib(clone_1, attr.nodeName, getAttrib(node, attr.nodeName));
              });
              return clone_1;
            }
          };
          var getRoot = function() {
            return settings.root_element || doc2.body;
          };
          var getViewPort = function(argWin) {
            var vp = getBounds2(argWin);
            return {
              x: vp.x,
              y: vp.y,
              w: vp.width,
              h: vp.height
            };
          };
          var getPos$1 = function(elm, rootElm) {
            return getPos(doc2.body, get2(elm), rootElm);
          };
          var setStyle2 = function(elm, name2, value2) {
            var $elm = isString$1(name2) ? $$(elm).css(name2, value2) : $$(elm).css(name2);
            if (settings.update_styles) {
              updateInternalStyleAttr(styles, $elm);
            }
          };
          var setStyles = function(elm, stylesArg) {
            var $elm = $$(elm).css(stylesArg);
            if (settings.update_styles) {
              updateInternalStyleAttr(styles, $elm);
            }
          };
          var getStyle3 = function(elm, name2, computed) {
            var $elm = $$(elm);
            if (computed) {
              return $elm.css(name2);
            }
            name2 = name2.replace(/-(\D)/g, function(a2, b2) {
              return b2.toUpperCase();
            });
            if (name2 === "float") {
              name2 = Env.browser.isIE() ? "styleFloat" : "cssFloat";
            }
            return $elm[0] && $elm[0].style ? $elm[0].style[name2] : void 0;
          };
          var getSize = function(elm) {
            var w2, h3;
            elm = get2(elm);
            w2 = getStyle3(elm, "width");
            h3 = getStyle3(elm, "height");
            if (w2.indexOf("px") === -1) {
              w2 = 0;
            }
            if (h3.indexOf("px") === -1) {
              h3 = 0;
            }
            return {
              w: parseInt(w2, 10) || elm.offsetWidth || elm.clientWidth,
              h: parseInt(h3, 10) || elm.offsetHeight || elm.clientHeight
            };
          };
          var getRect = function(elm) {
            elm = get2(elm);
            var pos = getPos$1(elm);
            var size = getSize(elm);
            return {
              x: pos.x,
              y: pos.y,
              w: size.w,
              h: size.h
            };
          };
          var is2 = function(elm, selector) {
            var i2;
            if (!elm) {
              return false;
            }
            if (!Array.isArray(elm)) {
              if (selector === "*") {
                return elm.nodeType === 1;
              }
              if (simpleSelectorRe.test(selector)) {
                var selectors = selector.toLowerCase().split(/,/);
                var elmName = elm.nodeName.toLowerCase();
                for (i2 = selectors.length - 1; i2 >= 0; i2--) {
                  if (selectors[i2] === elmName) {
                    return true;
                  }
                }
                return false;
              }
              if (elm.nodeType && elm.nodeType !== 1) {
                return false;
              }
            }
            var elms = !Array.isArray(elm) ? [elm] : elm;
            return Sizzle(selector, elms[0].ownerDocument || elms[0], null, elms).length > 0;
          };
          var getParents2 = function(elm, selector, root, collect) {
            var result = [];
            var selectorVal;
            var node = get2(elm);
            collect = collect === void 0;
            root = root || (getRoot().nodeName !== "BODY" ? getRoot().parentNode : null);
            if (Tools.is(selector, "string")) {
              selectorVal = selector;
              if (selector === "*") {
                selector = function(node2) {
                  return node2.nodeType === 1;
                };
              } else {
                selector = function(node2) {
                  return is2(node2, selectorVal);
                };
              }
            }
            while (node) {
              if (node === root || isNullable(node.nodeType) || isDocument$1(node) || isDocumentFragment(node)) {
                break;
              }
              if (!selector || typeof selector === "function" && selector(node)) {
                if (collect) {
                  result.push(node);
                } else {
                  return [node];
                }
              }
              node = node.parentNode;
            }
            return collect ? result : null;
          };
          var getParent = function(node, selector, root) {
            var parents2 = getParents2(node, selector, root, false);
            return parents2 && parents2.length > 0 ? parents2[0] : null;
          };
          var _findSib = function(node, selector, name2) {
            var func = selector;
            if (node) {
              if (typeof selector === "string") {
                func = function(node2) {
                  return is2(node2, selector);
                };
              }
              for (node = node[name2]; node; node = node[name2]) {
                if (typeof func === "function" && func(node)) {
                  return node;
                }
              }
            }
            return null;
          };
          var getNext = function(node, selector) {
            return _findSib(node, selector, "nextSibling");
          };
          var getPrev = function(node, selector) {
            return _findSib(node, selector, "previousSibling");
          };
          var select2 = function(selector, scope) {
            return Sizzle(selector, get2(scope) || settings.root_element || doc2, []);
          };
          var run = function(elm, func, scope) {
            var result;
            var node = typeof elm === "string" ? get2(elm) : elm;
            if (!node) {
              return false;
            }
            if (Tools.isArray(node) && (node.length || node.length === 0)) {
              result = [];
              each$f(node, function(elm2, i2) {
                if (elm2) {
                  result.push(func.call(scope, typeof elm2 === "string" ? get2(elm2) : elm2, i2));
                }
              });
              return result;
            }
            var context2 = scope ? scope : this;
            return func.call(context2, node);
          };
          var setAttribs = function(elm, attrs) {
            $$(elm).each(function(i2, node) {
              each$f(attrs, function(value2, name2) {
                setAttrib(node, name2, value2);
              });
            });
          };
          var setHTML = function(elm, html) {
            var $elm = $$(elm);
            if (isIE) {
              $elm.each(function(i2, target) {
                if (target.canHaveHTML === false) {
                  return;
                }
                while (target.firstChild) {
                  target.removeChild(target.firstChild);
                }
                try {
                  target.innerHTML = "<br>" + html;
                  target.removeChild(target.firstChild);
                } catch (ex) {
                  DomQuery("<div></div>").html("<br>" + html).contents().slice(1).appendTo(target);
                }
                return html;
              });
            } else {
              $elm.html(html);
            }
          };
          var add4 = function(parentElm, name2, attrs, html, create3) {
            return run(parentElm, function(parentElm2) {
              var newElm = typeof name2 === "string" ? doc2.createElement(name2) : name2;
              setAttribs(newElm, attrs);
              if (html) {
                if (typeof html !== "string" && html.nodeType) {
                  newElm.appendChild(html);
                } else if (typeof html === "string") {
                  setHTML(newElm, html);
                }
              }
              return !create3 ? parentElm2.appendChild(newElm) : newElm;
            });
          };
          var create2 = function(name2, attrs, html) {
            return add4(doc2.createElement(name2), name2, attrs, html, true);
          };
          var decode2 = Entities.decode;
          var encode = Entities.encodeAllRaw;
          var createHTML = function(name2, attrs, html) {
            var outHtml = "", key;
            outHtml += "<" + name2;
            for (key in attrs) {
              if (hasNonNullableKey(attrs, key)) {
                outHtml += " " + key + '="' + encode(attrs[key]) + '"';
              }
            }
            if (typeof html !== "undefined") {
              return outHtml + ">" + html + "</" + name2 + ">";
            }
            return outHtml + " />";
          };
          var createFragment2 = function(html) {
            var node;
            var container = doc2.createElement("div");
            var frag = doc2.createDocumentFragment();
            frag.appendChild(container);
            if (html) {
              container.innerHTML = html;
            }
            while (node = container.firstChild) {
              frag.appendChild(node);
            }
            frag.removeChild(container);
            return frag;
          };
          var remove2 = function(node, keepChildren) {
            var $node = $$(node);
            if (keepChildren) {
              $node.each(function() {
                var child2;
                while (child2 = this.firstChild) {
                  if (child2.nodeType === 3 && child2.data.length === 0) {
                    this.removeChild(child2);
                  } else {
                    this.parentNode.insertBefore(child2, this);
                  }
                }
              }).remove();
            } else {
              $node.remove();
            }
            return $node.length > 1 ? $node.toArray() : $node[0];
          };
          var removeAllAttribs = function(e2) {
            return run(e2, function(e3) {
              var i2;
              var attrs = e3.attributes;
              for (i2 = attrs.length - 1; i2 >= 0; i2--) {
                e3.removeAttributeNode(attrs.item(i2));
              }
            });
          };
          var parseStyle = function(cssText) {
            return styles.parse(cssText);
          };
          var serializeStyle = function(stylesArg, name2) {
            return styles.serialize(stylesArg, name2);
          };
          var addStyle = function(cssText) {
            var head2, styleElm;
            if (self2 !== DOMUtils.DOM && doc2 === document) {
              if (addedStyles[cssText]) {
                return;
              }
              addedStyles[cssText] = true;
            }
            styleElm = doc2.getElementById("mceDefaultStyles");
            if (!styleElm) {
              styleElm = doc2.createElement("style");
              styleElm.id = "mceDefaultStyles";
              styleElm.type = "text/css";
              head2 = doc2.getElementsByTagName("head")[0];
              if (head2.firstChild) {
                head2.insertBefore(styleElm, head2.firstChild);
              } else {
                head2.appendChild(styleElm);
              }
            }
            if (styleElm.styleSheet) {
              styleElm.styleSheet.cssText += cssText;
            } else {
              styleElm.appendChild(doc2.createTextNode(cssText));
            }
          };
          var loadCSS = function(urls) {
            if (!urls) {
              urls = "";
            }
            each$k(urls.split(","), function(url) {
              files[url] = true;
              styleSheetLoader.load(url, noop3);
            });
          };
          var toggleClass2 = function(elm, cls, state) {
            $$(elm).toggleClass(cls, state).each(function() {
              if (this.className === "") {
                DomQuery(this).attr("class", null);
              }
            });
          };
          var addClass = function(elm, cls) {
            $$(elm).addClass(cls);
          };
          var removeClass = function(elm, cls) {
            toggleClass2(elm, cls, false);
          };
          var hasClass2 = function(elm, cls) {
            return $$(elm).hasClass(cls);
          };
          var show = function(elm) {
            $$(elm).show();
          };
          var hide2 = function(elm) {
            $$(elm).hide();
          };
          var isHidden = function(elm) {
            return $$(elm).css("display") === "none";
          };
          var uniqueId2 = function(prefix) {
            return (!prefix ? "mce_" : prefix) + counter++;
          };
          var getOuterHTML = function(elm) {
            var node = typeof elm === "string" ? get2(elm) : elm;
            return isElement$5(node) ? node.outerHTML : DomQuery("<div></div>").append(DomQuery(node).clone()).html();
          };
          var setOuterHTML = function(elm, html) {
            $$(elm).each(function() {
              try {
                if ("outerHTML" in this) {
                  this.outerHTML = html;
                  return;
                }
              } catch (ex) {
              }
              remove2(DomQuery(this).html(html), true);
            });
          };
          var insertAfter2 = function(node, reference2) {
            var referenceNode = get2(reference2);
            return run(node, function(node2) {
              var parent2 = referenceNode.parentNode;
              var nextSibling2 = referenceNode.nextSibling;
              if (nextSibling2) {
                parent2.insertBefore(node2, nextSibling2);
              } else {
                parent2.appendChild(node2);
              }
              return node2;
            });
          };
          var replace = function(newElm, oldElm, keepChildren) {
            return run(oldElm, function(oldElm2) {
              if (Tools.is(oldElm2, "array")) {
                newElm = newElm.cloneNode(true);
              }
              if (keepChildren) {
                each$f(grep$1(oldElm2.childNodes), function(node) {
                  newElm.appendChild(node);
                });
              }
              return oldElm2.parentNode.replaceChild(newElm, oldElm2);
            });
          };
          var rename = function(elm, name2) {
            var newElm;
            if (elm.nodeName !== name2.toUpperCase()) {
              newElm = create2(name2);
              each$f(getAttribs(elm), function(attrNode) {
                setAttrib(newElm, attrNode.nodeName, getAttrib(elm, attrNode.nodeName));
              });
              replace(newElm, elm, true);
            }
            return newElm || elm;
          };
          var findCommonAncestor = function(a2, b2) {
            var ps = a2, pe2;
            while (ps) {
              pe2 = b2;
              while (pe2 && ps !== pe2) {
                pe2 = pe2.parentNode;
              }
              if (ps === pe2) {
                break;
              }
              ps = ps.parentNode;
            }
            if (!ps && a2.ownerDocument) {
              return a2.ownerDocument.documentElement;
            }
            return ps;
          };
          var toHex2 = function(rgbVal) {
            return styles.toHex(Tools.trim(rgbVal));
          };
          var isNonEmptyElement2 = function(node) {
            if (isElement$5(node)) {
              var isNamedAnchor2 = node.nodeName.toLowerCase() === "a" && !getAttrib(node, "href") && getAttrib(node, "id");
              if (getAttrib(node, "name") || getAttrib(node, "data-mce-bookmark") || isNamedAnchor2) {
                return true;
              }
            }
            return false;
          };
          var isEmpty2 = function(node, elements2) {
            var type2, name2, brCount = 0;
            if (isNonEmptyElement2(node)) {
              return false;
            }
            node = node.firstChild;
            if (node) {
              var walker = new DomTreeWalker(node, node.parentNode);
              var whitespace2 = schema ? schema.getWhiteSpaceElements() : {};
              elements2 = elements2 || (schema ? schema.getNonEmptyElements() : null);
              do {
                type2 = node.nodeType;
                if (isElement$5(node)) {
                  var bogusVal = node.getAttribute("data-mce-bogus");
                  if (bogusVal) {
                    node = walker.next(bogusVal === "all");
                    continue;
                  }
                  name2 = node.nodeName.toLowerCase();
                  if (elements2 && elements2[name2]) {
                    if (name2 === "br") {
                      brCount++;
                      node = walker.next();
                      continue;
                    }
                    return false;
                  }
                  if (isNonEmptyElement2(node)) {
                    return false;
                  }
                }
                if (type2 === 8) {
                  return false;
                }
                if (type2 === 3 && !isWhitespaceText(node.nodeValue)) {
                  return false;
                }
                if (type2 === 3 && node.parentNode && whitespace2[node.parentNode.nodeName] && isWhitespaceText(node.nodeValue)) {
                  return false;
                }
                node = walker.next();
              } while (node);
            }
            return brCount <= 1;
          };
          var createRng = function() {
            return doc2.createRange();
          };
          var split2 = function(parentElm, splitElm, replacementElm) {
            var range2 = createRng();
            var beforeFragment;
            var afterFragment;
            var parentNode;
            if (parentElm && splitElm) {
              range2.setStart(parentElm.parentNode, findNodeIndex(parentElm));
              range2.setEnd(splitElm.parentNode, findNodeIndex(splitElm));
              beforeFragment = range2.extractContents();
              range2 = createRng();
              range2.setStart(splitElm.parentNode, findNodeIndex(splitElm) + 1);
              range2.setEnd(parentElm.parentNode, findNodeIndex(parentElm) + 1);
              afterFragment = range2.extractContents();
              parentNode = parentElm.parentNode;
              parentNode.insertBefore(trimNode(self2, beforeFragment), parentElm);
              if (replacementElm) {
                parentNode.insertBefore(replacementElm, parentElm);
              } else {
                parentNode.insertBefore(splitElm, parentElm);
              }
              parentNode.insertBefore(trimNode(self2, afterFragment), parentElm);
              remove2(parentElm);
              return replacementElm || splitElm;
            }
          };
          var bind2 = function(target, name2, func, scope) {
            if (Tools.isArray(target)) {
              var i2 = target.length;
              var rv = [];
              while (i2--) {
                rv[i2] = bind2(target[i2], name2, func, scope);
              }
              return rv;
            }
            if (settings.collect && (target === doc2 || target === win)) {
              boundEvents.push([
                target,
                name2,
                func,
                scope
              ]);
            }
            var output = events.bind(target, name2, func, scope || self2);
            return output;
          };
          var unbind = function(target, name2, func) {
            if (Tools.isArray(target)) {
              var i2 = target.length;
              var rv = [];
              while (i2--) {
                rv[i2] = unbind(target[i2], name2, func);
              }
              return rv;
            } else {
              if (boundEvents.length > 0 && (target === doc2 || target === win)) {
                var i2 = boundEvents.length;
                while (i2--) {
                  var item = boundEvents[i2];
                  if (target === item[0] && (!name2 || name2 === item[1]) && (!func || func === item[2])) {
                    events.unbind(item[0], item[1], item[2]);
                  }
                }
              }
              return events.unbind(target, name2, func);
            }
          };
          var fire = function(target, name2, evt) {
            return events.fire(target, name2, evt);
          };
          var getContentEditable = function(node) {
            if (node && isElement$5(node)) {
              var contentEditable = node.getAttribute("data-mce-contenteditable");
              if (contentEditable && contentEditable !== "inherit") {
                return contentEditable;
              }
              return node.contentEditable !== "inherit" ? node.contentEditable : null;
            } else {
              return null;
            }
          };
          var getContentEditableParent = function(node) {
            var root = getRoot();
            var state = null;
            for (; node && node !== root; node = node.parentNode) {
              state = getContentEditable(node);
              if (state !== null) {
                break;
              }
            }
            return state;
          };
          var destroy2 = function() {
            if (boundEvents.length > 0) {
              var i2 = boundEvents.length;
              while (i2--) {
                var item = boundEvents[i2];
                events.unbind(item[0], item[1], item[2]);
              }
            }
            each$j(files, function(_2, url) {
              styleSheetLoader.unload(url);
              delete files[url];
            });
            if (Sizzle.setDocument) {
              Sizzle.setDocument();
            }
          };
          var isChildOf = function(node, parent2) {
            if (!isIE) {
              return node === parent2 || parent2.contains(node);
            } else {
              while (node) {
                if (parent2 === node) {
                  return true;
                }
                node = node.parentNode;
              }
              return false;
            }
          };
          var dumpRng = function(r3) {
            return "startContainer: " + r3.startContainer.nodeName + ", startOffset: " + r3.startOffset + ", endContainer: " + r3.endContainer.nodeName + ", endOffset: " + r3.endOffset;
          };
          var self2 = {
            doc: doc2,
            settings,
            win,
            files,
            stdMode,
            boxModel,
            styleSheetLoader,
            boundEvents,
            styles,
            schema,
            events,
            isBlock: isBlock2,
            $: $2,
            $$,
            root: null,
            clone: clone3,
            getRoot,
            getViewPort,
            getRect,
            getSize,
            getParent,
            getParents: getParents2,
            get: get2,
            getNext,
            getPrev,
            select: select2,
            is: is2,
            add: add4,
            create: create2,
            createHTML,
            createFragment: createFragment2,
            remove: remove2,
            setStyle: setStyle2,
            getStyle: getStyle3,
            setStyles,
            removeAllAttribs,
            setAttrib,
            setAttribs,
            getAttrib,
            getPos: getPos$1,
            parseStyle,
            serializeStyle,
            addStyle,
            loadCSS,
            addClass,
            removeClass,
            hasClass: hasClass2,
            toggleClass: toggleClass2,
            show,
            hide: hide2,
            isHidden,
            uniqueId: uniqueId2,
            setHTML,
            getOuterHTML,
            setOuterHTML,
            decode: decode2,
            encode,
            insertAfter: insertAfter2,
            replace,
            rename,
            findCommonAncestor,
            toHex: toHex2,
            run,
            getAttribs,
            isEmpty: isEmpty2,
            createRng,
            nodeIndex: findNodeIndex,
            split: split2,
            bind: bind2,
            unbind,
            fire,
            getContentEditable,
            getContentEditableParent,
            destroy: destroy2,
            isChildOf,
            dumpRng
          };
          var attrHooks2 = setupAttrHooks(styles, settings, constant(self2));
          return self2;
        };
        DOMUtils.DOM = DOMUtils(document);
        DOMUtils.nodeIndex = findNodeIndex;
        var DOM$a = DOMUtils.DOM;
        var each$e = Tools.each, grep = Tools.grep;
        var QUEUED = 0;
        var LOADING = 1;
        var LOADED = 2;
        var FAILED = 3;
        var ScriptLoader = function() {
          function ScriptLoader2(settings) {
            if (settings === void 0) {
              settings = {};
            }
            this.states = {};
            this.queue = [];
            this.scriptLoadedCallbacks = {};
            this.queueLoadedCallbacks = [];
            this.loading = 0;
            this.settings = settings;
          }
          ScriptLoader2.prototype._setReferrerPolicy = function(referrerPolicy) {
            this.settings.referrerPolicy = referrerPolicy;
          };
          ScriptLoader2.prototype.loadScript = function(url, success, failure) {
            var dom2 = DOM$a;
            var elm;
            var cleanup = function() {
              dom2.remove(id2);
              if (elm) {
                elm.onerror = elm.onload = elm = null;
              }
            };
            var done2 = function() {
              cleanup();
              success();
            };
            var error4 = function() {
              cleanup();
              if (isFunction2(failure)) {
                failure();
              } else {
                if (typeof console !== "undefined" && console.log) {
                  console.log("Failed to load script: " + url);
                }
              }
            };
            var id2 = dom2.uniqueId();
            elm = document.createElement("script");
            elm.id = id2;
            elm.type = "text/javascript";
            elm.src = Tools._addCacheSuffix(url);
            if (this.settings.referrerPolicy) {
              dom2.setAttrib(elm, "referrerpolicy", this.settings.referrerPolicy);
            }
            elm.onload = done2;
            elm.onerror = error4;
            (document.getElementsByTagName("head")[0] || document.body).appendChild(elm);
          };
          ScriptLoader2.prototype.isDone = function(url) {
            return this.states[url] === LOADED;
          };
          ScriptLoader2.prototype.markDone = function(url) {
            this.states[url] = LOADED;
          };
          ScriptLoader2.prototype.add = function(url, success, scope, failure) {
            var state = this.states[url];
            this.queue.push(url);
            if (state === void 0) {
              this.states[url] = QUEUED;
            }
            if (success) {
              if (!this.scriptLoadedCallbacks[url]) {
                this.scriptLoadedCallbacks[url] = [];
              }
              this.scriptLoadedCallbacks[url].push({
                success,
                failure,
                scope: scope || this
              });
            }
          };
          ScriptLoader2.prototype.load = function(url, success, scope, failure) {
            return this.add(url, success, scope, failure);
          };
          ScriptLoader2.prototype.remove = function(url) {
            delete this.states[url];
            delete this.scriptLoadedCallbacks[url];
          };
          ScriptLoader2.prototype.loadQueue = function(success, scope, failure) {
            this.loadScripts(this.queue, success, scope, failure);
          };
          ScriptLoader2.prototype.loadScripts = function(scripts, success, scope, failure) {
            var self2 = this;
            var failures = [];
            var execCallbacks = function(name2, url) {
              each$e(self2.scriptLoadedCallbacks[url], function(callback2) {
                if (isFunction2(callback2[name2])) {
                  callback2[name2].call(callback2.scope);
                }
              });
              self2.scriptLoadedCallbacks[url] = void 0;
            };
            self2.queueLoadedCallbacks.push({
              success,
              failure,
              scope: scope || this
            });
            var loadScripts2 = function() {
              var loadingScripts = grep(scripts);
              scripts.length = 0;
              each$e(loadingScripts, function(url) {
                if (self2.states[url] === LOADED) {
                  execCallbacks("success", url);
                  return;
                }
                if (self2.states[url] === FAILED) {
                  execCallbacks("failure", url);
                  return;
                }
                if (self2.states[url] !== LOADING) {
                  self2.states[url] = LOADING;
                  self2.loading++;
                  self2.loadScript(url, function() {
                    self2.states[url] = LOADED;
                    self2.loading--;
                    execCallbacks("success", url);
                    loadScripts2();
                  }, function() {
                    self2.states[url] = FAILED;
                    self2.loading--;
                    failures.push(url);
                    execCallbacks("failure", url);
                    loadScripts2();
                  });
                }
              });
              if (!self2.loading) {
                var notifyCallbacks = self2.queueLoadedCallbacks.slice(0);
                self2.queueLoadedCallbacks.length = 0;
                each$e(notifyCallbacks, function(callback2) {
                  if (failures.length === 0) {
                    if (isFunction2(callback2.success)) {
                      callback2.success.call(callback2.scope);
                    }
                  } else {
                    if (isFunction2(callback2.failure)) {
                      callback2.failure.call(callback2.scope, failures);
                    }
                  }
                });
              }
            };
            loadScripts2();
          };
          ScriptLoader2.ScriptLoader = new ScriptLoader2();
          return ScriptLoader2;
        }();
        var Cell = function(initial) {
          var value2 = initial;
          var get2 = function() {
            return value2;
          };
          var set3 = function(v2) {
            value2 = v2;
          };
          return {
            get: get2,
            set: set3
          };
        };
        var isRaw = function(str) {
          return isObject2(str) && has$2(str, "raw");
        };
        var isTokenised = function(str) {
          return isArray$1(str) && str.length > 1;
        };
        var data = {};
        var currentCode = Cell("en");
        var getLanguageData = function() {
          return get$9(data, currentCode.get());
        };
        var getData = function() {
          return map$2(data, function(value2) {
            return __assign({}, value2);
          });
        };
        var setCode = function(newCode) {
          if (newCode) {
            currentCode.set(newCode);
          }
        };
        var getCode = function() {
          return currentCode.get();
        };
        var add$4 = function(code, items) {
          var langData = data[code];
          if (!langData) {
            data[code] = langData = {};
          }
          each$j(items, function(translation, name2) {
            langData[name2.toLowerCase()] = translation;
          });
        };
        var translate = function(text) {
          var langData = getLanguageData().getOr({});
          var toString = function(obj) {
            if (isFunction2(obj)) {
              return Object.prototype.toString.call(obj);
            }
            return !isEmpty2(obj) ? "" + obj : "";
          };
          var isEmpty2 = function(text2) {
            return text2 === "" || text2 === null || text2 === void 0;
          };
          var getLangData = function(text2) {
            var textstr = toString(text2);
            return get$9(langData, textstr.toLowerCase()).map(toString).getOr(textstr);
          };
          var removeContext = function(str) {
            return str.replace(/{context:\w+}$/, "");
          };
          if (isEmpty2(text)) {
            return "";
          }
          if (isRaw(text)) {
            return toString(text.raw);
          }
          if (isTokenised(text)) {
            var values_1 = text.slice(1);
            var substitued = getLangData(text[0]).replace(/\{([0-9]+)\}/g, function($1, $2) {
              return has$2(values_1, $2) ? toString(values_1[$2]) : $1;
            });
            return removeContext(substitued);
          }
          return removeContext(getLangData(text));
        };
        var isRtl$1 = function() {
          return getLanguageData().bind(function(items) {
            return get$9(items, "_dir");
          }).exists(function(dir2) {
            return dir2 === "rtl";
          });
        };
        var hasCode = function(code) {
          return has$2(data, code);
        };
        var I18n = {
          getData,
          setCode,
          getCode,
          add: add$4,
          translate,
          isRtl: isRtl$1,
          hasCode
        };
        var AddOnManager = function() {
          var items = [];
          var urls = {};
          var lookup = {};
          var _listeners = [];
          var runListeners = function(name2, state) {
            var matchedListeners = filter$4(_listeners, function(listener) {
              return listener.name === name2 && listener.state === state;
            });
            each$k(matchedListeners, function(listener) {
              return listener.callback();
            });
          };
          var get2 = function(name2) {
            if (lookup[name2]) {
              return lookup[name2].instance;
            }
            return void 0;
          };
          var dependencies = function(name2) {
            var result;
            if (lookup[name2]) {
              result = lookup[name2].dependencies;
            }
            return result || [];
          };
          var requireLangPack = function(name2, languages) {
            if (AddOnManager.languageLoad !== false) {
              waitFor(name2, function() {
                var language = I18n.getCode();
                var wrappedLanguages = "," + (languages || "") + ",";
                if (!language || languages && wrappedLanguages.indexOf("," + language + ",") === -1) {
                  return;
                }
                ScriptLoader.ScriptLoader.add(urls[name2] + "/langs/" + language + ".js");
              }, "loaded");
            }
          };
          var add4 = function(id2, addOn, dependencies2) {
            var addOnConstructor = addOn;
            items.push(addOnConstructor);
            lookup[id2] = {
              instance: addOnConstructor,
              dependencies: dependencies2
            };
            runListeners(id2, "added");
            return addOnConstructor;
          };
          var remove2 = function(name2) {
            delete urls[name2];
            delete lookup[name2];
          };
          var createUrl = function(baseUrl, dep) {
            if (typeof dep === "object") {
              return dep;
            }
            return typeof baseUrl === "string" ? {
              prefix: "",
              resource: dep,
              suffix: ""
            } : {
              prefix: baseUrl.prefix,
              resource: dep,
              suffix: baseUrl.suffix
            };
          };
          var addComponents = function(pluginName, scripts) {
            var pluginUrl = urls[pluginName];
            each$k(scripts, function(script) {
              ScriptLoader.ScriptLoader.add(pluginUrl + "/" + script);
            });
          };
          var loadDependencies = function(name2, addOnUrl, success, scope) {
            var deps = dependencies(name2);
            each$k(deps, function(dep) {
              var newUrl = createUrl(addOnUrl, dep);
              load(newUrl.resource, newUrl, void 0, void 0);
            });
            if (success) {
              if (scope) {
                success.call(scope);
              } else {
                success.call(ScriptLoader);
              }
            }
          };
          var load = function(name2, addOnUrl, success, scope, failure) {
            if (urls[name2]) {
              return;
            }
            var urlString = typeof addOnUrl === "string" ? addOnUrl : addOnUrl.prefix + addOnUrl.resource + addOnUrl.suffix;
            if (urlString.indexOf("/") !== 0 && urlString.indexOf("://") === -1) {
              urlString = AddOnManager.baseURL + "/" + urlString;
            }
            urls[name2] = urlString.substring(0, urlString.lastIndexOf("/"));
            var done2 = function() {
              runListeners(name2, "loaded");
              loadDependencies(name2, addOnUrl, success, scope);
            };
            if (lookup[name2]) {
              done2();
            } else {
              ScriptLoader.ScriptLoader.add(urlString, done2, scope, failure);
            }
          };
          var waitFor = function(name2, callback2, state) {
            if (state === void 0) {
              state = "added";
            }
            if (has$2(lookup, name2) && state === "added") {
              callback2();
            } else if (has$2(urls, name2) && state === "loaded") {
              callback2();
            } else {
              _listeners.push({
                name: name2,
                state,
                callback: callback2
              });
            }
          };
          return {
            items,
            urls,
            lookup,
            _listeners,
            get: get2,
            dependencies,
            requireLangPack,
            add: add4,
            remove: remove2,
            createUrl,
            addComponents,
            load,
            waitFor
          };
        };
        AddOnManager.languageLoad = true;
        AddOnManager.baseURL = "";
        AddOnManager.PluginManager = AddOnManager();
        AddOnManager.ThemeManager = AddOnManager();
        var singleton = function(doRevoke) {
          var subject = Cell(Optional.none());
          var revoke = function() {
            return subject.get().each(doRevoke);
          };
          var clear2 = function() {
            revoke();
            subject.set(Optional.none());
          };
          var isSet = function() {
            return subject.get().isSome();
          };
          var get2 = function() {
            return subject.get();
          };
          var set3 = function(s2) {
            revoke();
            subject.set(Optional.some(s2));
          };
          return {
            clear: clear2,
            isSet,
            get: get2,
            set: set3
          };
        };
        var value = function() {
          var subject = singleton(noop3);
          var on3 = function(f2) {
            return subject.get().each(f2);
          };
          return __assign(__assign({}, subject), { on: on3 });
        };
        var first = function(fn3, rate) {
          var timer = null;
          var cancel = function() {
            if (!isNull(timer)) {
              clearTimeout(timer);
              timer = null;
            }
          };
          var throttle = function() {
            var args = [];
            for (var _i2 = 0; _i2 < arguments.length; _i2++) {
              args[_i2] = arguments[_i2];
            }
            if (isNull(timer)) {
              timer = setTimeout(function() {
                timer = null;
                fn3.apply(null, args);
              }, rate);
            }
          };
          return {
            cancel,
            throttle
          };
        };
        var last = function(fn3, rate) {
          var timer = null;
          var cancel = function() {
            if (!isNull(timer)) {
              clearTimeout(timer);
              timer = null;
            }
          };
          var throttle = function() {
            var args = [];
            for (var _i2 = 0; _i2 < arguments.length; _i2++) {
              args[_i2] = arguments[_i2];
            }
            cancel();
            timer = setTimeout(function() {
              timer = null;
              fn3.apply(null, args);
            }, rate);
          };
          return {
            cancel,
            throttle
          };
        };
        var read$4 = function(element, attr) {
          var value2 = get$6(element, attr);
          return value2 === void 0 || value2 === "" ? [] : value2.split(" ");
        };
        var add$3 = function(element, attr, id2) {
          var old = read$4(element, attr);
          var nu2 = old.concat([id2]);
          set$1(element, attr, nu2.join(" "));
          return true;
        };
        var remove$5 = function(element, attr, id2) {
          var nu2 = filter$4(read$4(element, attr), function(v2) {
            return v2 !== id2;
          });
          if (nu2.length > 0) {
            set$1(element, attr, nu2.join(" "));
          } else {
            remove$6(element, attr);
          }
          return false;
        };
        var supports = function(element) {
          return element.dom.classList !== void 0;
        };
        var get$4 = function(element) {
          return read$4(element, "class");
        };
        var add$2 = function(element, clazz) {
          return add$3(element, "class", clazz);
        };
        var remove$4 = function(element, clazz) {
          return remove$5(element, "class", clazz);
        };
        var add$1 = function(element, clazz) {
          if (supports(element)) {
            element.dom.classList.add(clazz);
          } else {
            add$2(element, clazz);
          }
        };
        var cleanClass = function(element) {
          var classList = supports(element) ? element.dom.classList : get$4(element);
          if (classList.length === 0) {
            remove$6(element, "class");
          }
        };
        var remove$3 = function(element, clazz) {
          if (supports(element)) {
            var classList = element.dom.classList;
            classList.remove(clazz);
          } else {
            remove$4(element, clazz);
          }
          cleanClass(element);
        };
        var has = function(element, clazz) {
          return supports(element) && element.dom.classList.contains(clazz);
        };
        var descendants$1 = function(scope, predicate) {
          var result = [];
          each$k(children(scope), function(x2) {
            if (predicate(x2)) {
              result = result.concat([x2]);
            }
            result = result.concat(descendants$1(x2, predicate));
          });
          return result;
        };
        var descendants = function(scope, selector) {
          return all(selector, scope);
        };
        var annotation = constant("mce-annotation");
        var dataAnnotation = constant("data-mce-annotation");
        var dataAnnotationId = constant("data-mce-annotation-uid");
        var identify = function(editor, annotationName) {
          var rng = editor.selection.getRng();
          var start5 = SugarElement.fromDom(rng.startContainer);
          var root = SugarElement.fromDom(editor.getBody());
          var selector = annotationName.fold(function() {
            return "." + annotation();
          }, function(an2) {
            return "[" + dataAnnotation() + '="' + an2 + '"]';
          });
          var newStart = child$1(start5, rng.startOffset).getOr(start5);
          var closest2 = closest$2(newStart, selector, function(n2) {
            return eq2(n2, root);
          });
          var getAttr = function(c2, property) {
            if (has$1(c2, property)) {
              return Optional.some(get$6(c2, property));
            } else {
              return Optional.none();
            }
          };
          return closest2.bind(function(c2) {
            return getAttr(c2, "" + dataAnnotationId()).bind(function(uid2) {
              return getAttr(c2, "" + dataAnnotation()).map(function(name2) {
                var elements2 = findMarkers(editor, uid2);
                return {
                  uid: uid2,
                  name: name2,
                  elements: elements2
                };
              });
            });
          });
        };
        var isAnnotation = function(elem) {
          return isElement$6(elem) && has(elem, annotation());
        };
        var findMarkers = function(editor, uid2) {
          var body = SugarElement.fromDom(editor.getBody());
          return descendants(body, "[" + dataAnnotationId() + '="' + uid2 + '"]');
        };
        var findAll = function(editor, name2) {
          var body = SugarElement.fromDom(editor.getBody());
          var markers = descendants(body, "[" + dataAnnotation() + '="' + name2 + '"]');
          var directory = {};
          each$k(markers, function(m2) {
            var uid2 = get$6(m2, dataAnnotationId());
            var nodesAlready = get$9(directory, uid2).getOr([]);
            directory[uid2] = nodesAlready.concat([m2]);
          });
          return directory;
        };
        var setup$n = function(editor, _registry) {
          var changeCallbacks = Cell({});
          var initData2 = function() {
            return {
              listeners: [],
              previous: value()
            };
          };
          var withCallbacks = function(name2, f2) {
            updateCallbacks(name2, function(data2) {
              f2(data2);
              return data2;
            });
          };
          var updateCallbacks = function(name2, f2) {
            var callbackMap = changeCallbacks.get();
            var data2 = get$9(callbackMap, name2).getOrThunk(initData2);
            var outputData = f2(data2);
            callbackMap[name2] = outputData;
            changeCallbacks.set(callbackMap);
          };
          var fireCallbacks = function(name2, uid2, elements2) {
            withCallbacks(name2, function(data2) {
              each$k(data2.listeners, function(f2) {
                return f2(true, name2, {
                  uid: uid2,
                  nodes: map$3(elements2, function(elem) {
                    return elem.dom;
                  })
                });
              });
            });
          };
          var fireNoAnnotation = function(name2) {
            withCallbacks(name2, function(data2) {
              each$k(data2.listeners, function(f2) {
                return f2(false, name2);
              });
            });
          };
          var onNodeChange = last(function() {
            var callbackMap = changeCallbacks.get();
            var annotations = sort(keys(callbackMap));
            each$k(annotations, function(name2) {
              updateCallbacks(name2, function(data2) {
                var prev = data2.previous.get();
                identify(editor, Optional.some(name2)).fold(function() {
                  if (prev.isSome()) {
                    fireNoAnnotation(name2);
                    data2.previous.clear();
                  }
                }, function(_a) {
                  var uid2 = _a.uid, name3 = _a.name, elements2 = _a.elements;
                  if (!is$1(prev, uid2)) {
                    fireCallbacks(name3, uid2, elements2);
                    data2.previous.set(uid2);
                  }
                });
                return {
                  previous: data2.previous,
                  listeners: data2.listeners
                };
              });
            });
          }, 30);
          editor.on("remove", function() {
            onNodeChange.cancel();
          });
          editor.on("NodeChange", function() {
            onNodeChange.throttle();
          });
          var addListener2 = function(name2, f2) {
            updateCallbacks(name2, function(data2) {
              return {
                previous: data2.previous,
                listeners: data2.listeners.concat([f2])
              };
            });
          };
          return { addListener: addListener2 };
        };
        var setup$m = function(editor, registry3) {
          var identifyParserNode = function(span) {
            return Optional.from(span.attr(dataAnnotation())).bind(registry3.lookup);
          };
          editor.on("init", function() {
            editor.serializer.addNodeFilter("span", function(spans) {
              each$k(spans, function(span) {
                identifyParserNode(span).each(function(settings) {
                  if (settings.persistent === false) {
                    span.unwrap();
                  }
                });
              });
            });
          });
        };
        var create$7 = function() {
          var annotations = {};
          var register2 = function(name2, settings) {
            annotations[name2] = {
              name: name2,
              settings
            };
          };
          var lookup = function(name2) {
            return get$9(annotations, name2).map(function(a2) {
              return a2.settings;
            });
          };
          return {
            register: register2,
            lookup
          };
        };
        var unique = 0;
        var generate = function(prefix) {
          var date = new Date();
          var time = date.getTime();
          var random = Math.floor(Math.random() * 1e9);
          unique++;
          return prefix + "_" + random + unique + String(time);
        };
        var add3 = function(element, classes) {
          each$k(classes, function(x2) {
            add$1(element, x2);
          });
        };
        var fromHtml = function(html, scope) {
          var doc2 = scope || document;
          var div = doc2.createElement("div");
          div.innerHTML = html;
          return children(SugarElement.fromDom(div));
        };
        var fromDom$1 = function(nodes) {
          return map$3(nodes, SugarElement.fromDom);
        };
        var get$3 = function(element) {
          return element.dom.innerHTML;
        };
        var set2 = function(element, content) {
          var owner2 = owner$1(element);
          var docDom = owner2.dom;
          var fragment = SugarElement.fromDom(docDom.createDocumentFragment());
          var contentElements = fromHtml(content, docDom);
          append(fragment, contentElements);
          empty(element);
          append$1(element, fragment);
        };
        var clone$12 = function(original, isDeep) {
          return SugarElement.fromDom(original.dom.cloneNode(isDeep));
        };
        var shallow = function(original) {
          return clone$12(original, false);
        };
        var deep$1 = function(original) {
          return clone$12(original, true);
        };
        var TextWalker = function(startNode, rootNode, isBoundary) {
          if (isBoundary === void 0) {
            isBoundary = never;
          }
          var walker = new DomTreeWalker(startNode, rootNode);
          var walk3 = function(direction) {
            var next;
            do {
              next = walker[direction]();
            } while (next && !isText$7(next) && !isBoundary(next));
            return Optional.from(next).filter(isText$7);
          };
          return {
            current: function() {
              return Optional.from(walker.current()).filter(isText$7);
            },
            next: function() {
              return walk3("next");
            },
            prev: function() {
              return walk3("prev");
            },
            prev2: function() {
              return walk3("prev2");
            }
          };
        };
        var TextSeeker = function(dom2, isBoundary) {
          var isBlockBoundary = isBoundary ? isBoundary : function(node) {
            return dom2.isBlock(node) || isBr$5(node) || isContentEditableFalse$b(node);
          };
          var walk3 = function(node, offset2, walker, process3) {
            if (isText$7(node)) {
              var newOffset = process3(node, offset2, node.data);
              if (newOffset !== -1) {
                return Optional.some({
                  container: node,
                  offset: newOffset
                });
              }
            }
            return walker().bind(function(next) {
              return walk3(next.container, next.offset, walker, process3);
            });
          };
          var backwards = function(node, offset2, process3, root) {
            var walker = TextWalker(node, root, isBlockBoundary);
            return walk3(node, offset2, function() {
              return walker.prev().map(function(prev) {
                return {
                  container: prev,
                  offset: prev.length
                };
              });
            }, process3).getOrNull();
          };
          var forwards = function(node, offset2, process3, root) {
            var walker = TextWalker(node, root, isBlockBoundary);
            return walk3(node, offset2, function() {
              return walker.next().map(function(next) {
                return {
                  container: next,
                  offset: 0
                };
              });
            }, process3).getOrNull();
          };
          return {
            backwards,
            forwards
          };
        };
        var round$2 = Math.round;
        var clone2 = function(rect) {
          if (!rect) {
            return {
              left: 0,
              top: 0,
              bottom: 0,
              right: 0,
              width: 0,
              height: 0
            };
          }
          return {
            left: round$2(rect.left),
            top: round$2(rect.top),
            bottom: round$2(rect.bottom),
            right: round$2(rect.right),
            width: round$2(rect.width),
            height: round$2(rect.height)
          };
        };
        var collapse = function(rect, toStart) {
          rect = clone2(rect);
          if (toStart) {
            rect.right = rect.left;
          } else {
            rect.left = rect.left + rect.width;
            rect.right = rect.left;
          }
          rect.width = 0;
          return rect;
        };
        var isEqual = function(rect1, rect2) {
          return rect1.left === rect2.left && rect1.top === rect2.top && rect1.bottom === rect2.bottom && rect1.right === rect2.right;
        };
        var isValidOverflow = function(overflowY, rect1, rect2) {
          return overflowY >= 0 && overflowY <= Math.min(rect1.height, rect2.height) / 2;
        };
        var isAbove$1 = function(rect1, rect2) {
          var halfHeight = Math.min(rect2.height / 2, rect1.height / 2);
          if (rect1.bottom - halfHeight < rect2.top) {
            return true;
          }
          if (rect1.top > rect2.bottom) {
            return false;
          }
          return isValidOverflow(rect2.top - rect1.bottom, rect1, rect2);
        };
        var isBelow$1 = function(rect1, rect2) {
          if (rect1.top > rect2.bottom) {
            return true;
          }
          if (rect1.bottom < rect2.top) {
            return false;
          }
          return isValidOverflow(rect2.bottom - rect1.top, rect1, rect2);
        };
        var containsXY = function(rect, clientX, clientY) {
          return clientX >= rect.left && clientX <= rect.right && clientY >= rect.top && clientY <= rect.bottom;
        };
        var clamp$2 = function(value2, min3, max3) {
          return Math.min(Math.max(value2, min3), max3);
        };
        var getSelectedNode = function(range2) {
          var startContainer = range2.startContainer, startOffset = range2.startOffset;
          if (startContainer.hasChildNodes() && range2.endOffset === startOffset + 1) {
            return startContainer.childNodes[startOffset];
          }
          return null;
        };
        var getNode$1 = function(container, offset2) {
          if (isElement$5(container) && container.hasChildNodes()) {
            var childNodes = container.childNodes;
            var safeOffset = clamp$2(offset2, 0, childNodes.length - 1);
            return childNodes[safeOffset];
          } else {
            return container;
          }
        };
        var getNodeUnsafe = function(container, offset2) {
          if (offset2 < 0 && isElement$5(container) && container.hasChildNodes()) {
            return void 0;
          } else {
            return getNode$1(container, offset2);
          }
        };
        var extendingChars = new RegExp("[\u0300-\u036F\u0483-\u0487\u0488-\u0489\u0591-\u05BD\u05BF\u05C1-\u05C2\u05C4-\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7-\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08E3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962-\u0963\u0981\u09BC\u09BE\u09C1-\u09C4\u09CD\u09D7\u09E2-\u09E3\u0A01-\u0A02\u0A3C\u0A41-\u0A42\u0A47-\u0A48\u0A4B-\u0A4D\u0A51\u0A70-\u0A71\u0A75\u0A81-\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7-\u0AC8\u0ACD\u0AE2-\u0AE3\u0B01\u0B3C\u0B3E\u0B3F\u0B41-\u0B44\u0B4D\u0B56\u0B57\u0B62-\u0B63\u0B82\u0BBE\u0BC0\u0BCD\u0BD7\u0C00\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55-\u0C56\u0C62-\u0C63\u0C81\u0CBC\u0CBF\u0CC2\u0CC6\u0CCC-\u0CCD\u0CD5-\u0CD6\u0CE2-\u0CE3\u0D01\u0D3E\u0D41-\u0D44\u0D4D\u0D57\u0D62-\u0D63\u0DCA\u0DCF\u0DD2-\u0DD4\u0DD6\u0DDF\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB-\u0EBC\u0EC8-\u0ECD\u0F18-\u0F19\u0F35\u0F37\u0F39\u0F71-\u0F7E\u0F80-\u0F84\u0F86-\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039-\u103A\u103D-\u103E\u1058-\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085-\u1086\u108D\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752-\u1753\u1772-\u1773\u17B4-\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DD\u180B-\u180D\u18A9\u1920-\u1922\u1927-\u1928\u1932\u1939-\u193B\u1A17-\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ABD\u1ABE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80-\u1B81\u1BA2-\u1BA5\u1BA8-\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8-\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8-\u1CF9\u1DC0-\u1DF5\u1DFC-\u1DFF\u200C-\u200D\u20D0-\u20DC\u20DD-\u20E0\u20E1\u20E2-\u20E4\u20E5-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302D\u302E-\u302F\u3099-\u309A\uA66F\uA670-\uA672\uA674-\uA67D\uA69E-\uA69F\uA6F0-\uA6F1\uA802\uA806\uA80B\uA825-\uA826\uA8C4\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9E5\uAA29-\uAA2E\uAA31-\uAA32\uAA35-\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7-\uAAB8\uAABE-\uAABF\uAAC1\uAAEC-\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFF9E-\uFF9F]");
        var isExtendingChar = function(ch) {
          return typeof ch === "string" && ch.charCodeAt(0) >= 768 && extendingChars.test(ch);
        };
        var or = function() {
          var args = [];
          for (var _i2 = 0; _i2 < arguments.length; _i2++) {
            args[_i2] = arguments[_i2];
          }
          return function(x2) {
            for (var i2 = 0; i2 < args.length; i2++) {
              if (args[i2](x2)) {
                return true;
              }
            }
            return false;
          };
        };
        var and = function() {
          var args = [];
          for (var _i2 = 0; _i2 < arguments.length; _i2++) {
            args[_i2] = arguments[_i2];
          }
          return function(x2) {
            for (var i2 = 0; i2 < args.length; i2++) {
              if (!args[i2](x2)) {
                return false;
              }
            }
            return true;
          };
        };
        var isElement$3 = isElement$5;
        var isCaretCandidate$2 = isCaretCandidate$3;
        var isBlock$1 = matchStyleValues("display", "block table");
        var isFloated = matchStyleValues("float", "left right");
        var isValidElementCaretCandidate = and(isElement$3, isCaretCandidate$2, not(isFloated));
        var isNotPre = not(matchStyleValues("white-space", "pre pre-line pre-wrap"));
        var isText$4 = isText$7;
        var isBr$2 = isBr$5;
        var nodeIndex$1 = DOMUtils.nodeIndex;
        var resolveIndex$1 = getNodeUnsafe;
        var createRange$1 = function(doc2) {
          return "createRange" in doc2 ? doc2.createRange() : DOMUtils.DOM.createRng();
        };
        var isWhiteSpace$1 = function(chr) {
          return chr && /[\r\n\t ]/.test(chr);
        };
        var isRange = function(rng) {
          return !!rng.setStart && !!rng.setEnd;
        };
        var isHiddenWhiteSpaceRange = function(range2) {
          var container = range2.startContainer;
          var offset2 = range2.startOffset;
          if (isWhiteSpace$1(range2.toString()) && isNotPre(container.parentNode) && isText$7(container)) {
            var text = container.data;
            if (isWhiteSpace$1(text[offset2 - 1]) || isWhiteSpace$1(text[offset2 + 1])) {
              return true;
            }
          }
          return false;
        };
        var getBrClientRect = function(brNode) {
          var doc2 = brNode.ownerDocument;
          var rng = createRange$1(doc2);
          var nbsp$1 = doc2.createTextNode(nbsp);
          var parentNode = brNode.parentNode;
          parentNode.insertBefore(nbsp$1, brNode);
          rng.setStart(nbsp$1, 0);
          rng.setEnd(nbsp$1, 1);
          var clientRect = clone2(rng.getBoundingClientRect());
          parentNode.removeChild(nbsp$1);
          return clientRect;
        };
        var getBoundingClientRectWebKitText = function(rng) {
          var sc = rng.startContainer;
          var ec = rng.endContainer;
          var so = rng.startOffset;
          var eo = rng.endOffset;
          if (sc === ec && isText$7(ec) && so === 0 && eo === 1) {
            var newRng = rng.cloneRange();
            newRng.setEndAfter(ec);
            return getBoundingClientRect$1(newRng);
          } else {
            return null;
          }
        };
        var isZeroRect = function(r3) {
          return r3.left === 0 && r3.right === 0 && r3.top === 0 && r3.bottom === 0;
        };
        var getBoundingClientRect$1 = function(item) {
          var clientRect;
          var clientRects = item.getClientRects();
          if (clientRects.length > 0) {
            clientRect = clone2(clientRects[0]);
          } else {
            clientRect = clone2(item.getBoundingClientRect());
          }
          if (!isRange(item) && isBr$2(item) && isZeroRect(clientRect)) {
            return getBrClientRect(item);
          }
          if (isZeroRect(clientRect) && isRange(item)) {
            return getBoundingClientRectWebKitText(item);
          }
          return clientRect;
        };
        var collapseAndInflateWidth = function(clientRect, toStart) {
          var newClientRect = collapse(clientRect, toStart);
          newClientRect.width = 1;
          newClientRect.right = newClientRect.left + 1;
          return newClientRect;
        };
        var getCaretPositionClientRects = function(caretPosition) {
          var clientRects = [];
          var addUniqueAndValidRect = function(clientRect) {
            if (clientRect.height === 0) {
              return;
            }
            if (clientRects.length > 0) {
              if (isEqual(clientRect, clientRects[clientRects.length - 1])) {
                return;
              }
            }
            clientRects.push(clientRect);
          };
          var addCharacterOffset = function(container2, offset3) {
            var range2 = createRange$1(container2.ownerDocument);
            if (offset3 < container2.data.length) {
              if (isExtendingChar(container2.data[offset3])) {
                return clientRects;
              }
              if (isExtendingChar(container2.data[offset3 - 1])) {
                range2.setStart(container2, offset3);
                range2.setEnd(container2, offset3 + 1);
                if (!isHiddenWhiteSpaceRange(range2)) {
                  addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(range2), false));
                  return clientRects;
                }
              }
            }
            if (offset3 > 0) {
              range2.setStart(container2, offset3 - 1);
              range2.setEnd(container2, offset3);
              if (!isHiddenWhiteSpaceRange(range2)) {
                addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(range2), false));
              }
            }
            if (offset3 < container2.data.length) {
              range2.setStart(container2, offset3);
              range2.setEnd(container2, offset3 + 1);
              if (!isHiddenWhiteSpaceRange(range2)) {
                addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(range2), true));
              }
            }
          };
          var container = caretPosition.container();
          var offset2 = caretPosition.offset();
          if (isText$4(container)) {
            addCharacterOffset(container, offset2);
            return clientRects;
          }
          if (isElement$3(container)) {
            if (caretPosition.isAtEnd()) {
              var node = resolveIndex$1(container, offset2);
              if (isText$4(node)) {
                addCharacterOffset(node, node.data.length);
              }
              if (isValidElementCaretCandidate(node) && !isBr$2(node)) {
                addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(node), false));
              }
            } else {
              var node = resolveIndex$1(container, offset2);
              if (isText$4(node)) {
                addCharacterOffset(node, 0);
              }
              if (isValidElementCaretCandidate(node) && caretPosition.isAtEnd()) {
                addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(node), false));
                return clientRects;
              }
              var beforeNode = resolveIndex$1(caretPosition.container(), caretPosition.offset() - 1);
              if (isValidElementCaretCandidate(beforeNode) && !isBr$2(beforeNode)) {
                if (isBlock$1(beforeNode) || isBlock$1(node) || !isValidElementCaretCandidate(node)) {
                  addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(beforeNode), false));
                }
              }
              if (isValidElementCaretCandidate(node)) {
                addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(node), true));
              }
            }
          }
          return clientRects;
        };
        var CaretPosition = function(container, offset2, clientRects) {
          var isAtStart = function() {
            if (isText$4(container)) {
              return offset2 === 0;
            }
            return offset2 === 0;
          };
          var isAtEnd = function() {
            if (isText$4(container)) {
              return offset2 >= container.data.length;
            }
            return offset2 >= container.childNodes.length;
          };
          var toRange = function() {
            var range2 = createRange$1(container.ownerDocument);
            range2.setStart(container, offset2);
            range2.setEnd(container, offset2);
            return range2;
          };
          var getClientRects2 = function() {
            if (!clientRects) {
              clientRects = getCaretPositionClientRects(CaretPosition(container, offset2));
            }
            return clientRects;
          };
          var isVisible2 = function() {
            return getClientRects2().length > 0;
          };
          var isEqual2 = function(caretPosition) {
            return caretPosition && container === caretPosition.container() && offset2 === caretPosition.offset();
          };
          var getNode2 = function(before2) {
            return resolveIndex$1(container, before2 ? offset2 - 1 : offset2);
          };
          return {
            container: constant(container),
            offset: constant(offset2),
            toRange,
            getClientRects: getClientRects2,
            isVisible: isVisible2,
            isAtStart,
            isAtEnd,
            isEqual: isEqual2,
            getNode: getNode2
          };
        };
        CaretPosition.fromRangeStart = function(range2) {
          return CaretPosition(range2.startContainer, range2.startOffset);
        };
        CaretPosition.fromRangeEnd = function(range2) {
          return CaretPosition(range2.endContainer, range2.endOffset);
        };
        CaretPosition.after = function(node) {
          return CaretPosition(node.parentNode, nodeIndex$1(node) + 1);
        };
        CaretPosition.before = function(node) {
          return CaretPosition(node.parentNode, nodeIndex$1(node));
        };
        CaretPosition.isAbove = function(pos1, pos2) {
          return lift2(head(pos2.getClientRects()), last$2(pos1.getClientRects()), isAbove$1).getOr(false);
        };
        CaretPosition.isBelow = function(pos1, pos2) {
          return lift2(last$2(pos2.getClientRects()), head(pos1.getClientRects()), isBelow$1).getOr(false);
        };
        CaretPosition.isAtStart = function(pos) {
          return pos ? pos.isAtStart() : false;
        };
        CaretPosition.isAtEnd = function(pos) {
          return pos ? pos.isAtEnd() : false;
        };
        CaretPosition.isTextPosition = function(pos) {
          return pos ? isText$7(pos.container()) : false;
        };
        CaretPosition.isElementPosition = function(pos) {
          return CaretPosition.isTextPosition(pos) === false;
        };
        var trimEmptyTextNode$1 = function(dom2, node) {
          if (isText$7(node) && node.data.length === 0) {
            dom2.remove(node);
          }
        };
        var insertNode = function(dom2, rng, node) {
          rng.insertNode(node);
          trimEmptyTextNode$1(dom2, node.previousSibling);
          trimEmptyTextNode$1(dom2, node.nextSibling);
        };
        var insertFragment = function(dom2, rng, frag) {
          var firstChild2 = Optional.from(frag.firstChild);
          var lastChild2 = Optional.from(frag.lastChild);
          rng.insertNode(frag);
          firstChild2.each(function(child2) {
            return trimEmptyTextNode$1(dom2, child2.previousSibling);
          });
          lastChild2.each(function(child2) {
            return trimEmptyTextNode$1(dom2, child2.nextSibling);
          });
        };
        var rangeInsertNode = function(dom2, rng, node) {
          if (isDocumentFragment(node)) {
            insertFragment(dom2, rng, node);
          } else {
            insertNode(dom2, rng, node);
          }
        };
        var isText$3 = isText$7;
        var isBogus = isBogus$2;
        var nodeIndex = DOMUtils.nodeIndex;
        var normalizedParent = function(node) {
          var parentNode = node.parentNode;
          if (isBogus(parentNode)) {
            return normalizedParent(parentNode);
          }
          return parentNode;
        };
        var getChildNodes = function(node) {
          if (!node) {
            return [];
          }
          return reduce(node.childNodes, function(result, node2) {
            if (isBogus(node2) && node2.nodeName !== "BR") {
              result = result.concat(getChildNodes(node2));
            } else {
              result.push(node2);
            }
            return result;
          }, []);
        };
        var normalizedTextOffset = function(node, offset2) {
          while (node = node.previousSibling) {
            if (!isText$3(node)) {
              break;
            }
            offset2 += node.data.length;
          }
          return offset2;
        };
        var equal = function(a2) {
          return function(b2) {
            return a2 === b2;
          };
        };
        var normalizedNodeIndex = function(node) {
          var nodes, index;
          nodes = getChildNodes(normalizedParent(node));
          index = findIndex$1(nodes, equal(node), node);
          nodes = nodes.slice(0, index + 1);
          var numTextFragments = reduce(nodes, function(result, node2, i2) {
            if (isText$3(node2) && isText$3(nodes[i2 - 1])) {
              result++;
            }
            return result;
          }, 0);
          nodes = filter$2(nodes, matchNodeNames([node.nodeName]));
          index = findIndex$1(nodes, equal(node), node);
          return index - numTextFragments;
        };
        var createPathItem = function(node) {
          var name2;
          if (isText$3(node)) {
            name2 = "text()";
          } else {
            name2 = node.nodeName.toLowerCase();
          }
          return name2 + "[" + normalizedNodeIndex(node) + "]";
        };
        var parentsUntil$1 = function(root, node, predicate) {
          var parents2 = [];
          for (node = node.parentNode; node !== root; node = node.parentNode) {
            if (predicate && predicate(node)) {
              break;
            }
            parents2.push(node);
          }
          return parents2;
        };
        var create$6 = function(root, caretPosition) {
          var container, offset2, path = [], outputOffset, childNodes, parents2;
          container = caretPosition.container();
          offset2 = caretPosition.offset();
          if (isText$3(container)) {
            outputOffset = normalizedTextOffset(container, offset2);
          } else {
            childNodes = container.childNodes;
            if (offset2 >= childNodes.length) {
              outputOffset = "after";
              offset2 = childNodes.length - 1;
            } else {
              outputOffset = "before";
            }
            container = childNodes[offset2];
          }
          path.push(createPathItem(container));
          parents2 = parentsUntil$1(root, container);
          parents2 = filter$2(parents2, not(isBogus$2));
          path = path.concat(map$12(parents2, function(node) {
            return createPathItem(node);
          }));
          return path.reverse().join("/") + "," + outputOffset;
        };
        var resolvePathItem = function(node, name2, index) {
          var nodes = getChildNodes(node);
          nodes = filter$2(nodes, function(node2, index2) {
            return !isText$3(node2) || !isText$3(nodes[index2 - 1]);
          });
          nodes = filter$2(nodes, matchNodeNames([name2]));
          return nodes[index];
        };
        var findTextPosition = function(container, offset2) {
          var node = container, targetOffset = 0, dataLen;
          while (isText$3(node)) {
            dataLen = node.data.length;
            if (offset2 >= targetOffset && offset2 <= targetOffset + dataLen) {
              container = node;
              offset2 = offset2 - targetOffset;
              break;
            }
            if (!isText$3(node.nextSibling)) {
              container = node;
              offset2 = dataLen;
              break;
            }
            targetOffset += dataLen;
            node = node.nextSibling;
          }
          if (isText$3(container) && offset2 > container.data.length) {
            offset2 = container.data.length;
          }
          return CaretPosition(container, offset2);
        };
        var resolve$2 = function(root, path) {
          var offset2;
          if (!path) {
            return null;
          }
          var parts = path.split(",");
          var paths = parts[0].split("/");
          offset2 = parts.length > 1 ? parts[1] : "before";
          var container = reduce(paths, function(result, value2) {
            var match3 = /([\w\-\(\)]+)\[([0-9]+)\]/.exec(value2);
            if (!match3) {
              return null;
            }
            if (match3[1] === "text()") {
              match3[1] = "#text";
            }
            return resolvePathItem(result, match3[1], parseInt(match3[2], 10));
          }, root);
          if (!container) {
            return null;
          }
          if (!isText$3(container)) {
            if (offset2 === "after") {
              offset2 = nodeIndex(container) + 1;
            } else {
              offset2 = nodeIndex(container);
            }
            return CaretPosition(container.parentNode, offset2);
          }
          return findTextPosition(container, parseInt(offset2, 10));
        };
        var isContentEditableFalse$9 = isContentEditableFalse$b;
        var getNormalizedTextOffset = function(trim2, container, offset2) {
          var node, trimmedOffset;
          trimmedOffset = trim2(container.data.slice(0, offset2)).length;
          for (node = container.previousSibling; node && isText$7(node); node = node.previousSibling) {
            trimmedOffset += trim2(node.data).length;
          }
          return trimmedOffset;
        };
        var getPoint2 = function(dom2, trim2, normalized, rng, start5) {
          var container = rng[start5 ? "startContainer" : "endContainer"];
          var offset2 = rng[start5 ? "startOffset" : "endOffset"];
          var point = [];
          var childNodes, after2 = 0;
          var root = dom2.getRoot();
          if (isText$7(container)) {
            point.push(normalized ? getNormalizedTextOffset(trim2, container, offset2) : offset2);
          } else {
            childNodes = container.childNodes;
            if (offset2 >= childNodes.length && childNodes.length) {
              after2 = 1;
              offset2 = Math.max(0, childNodes.length - 1);
            }
            point.push(dom2.nodeIndex(childNodes[offset2], normalized) + after2);
          }
          for (; container && container !== root; container = container.parentNode) {
            point.push(dom2.nodeIndex(container, normalized));
          }
          return point;
        };
        var getLocation = function(trim2, selection, normalized, rng) {
          var dom2 = selection.dom, bookmark = {};
          bookmark.start = getPoint2(dom2, trim2, normalized, rng, true);
          if (!selection.isCollapsed()) {
            bookmark.end = getPoint2(dom2, trim2, normalized, rng, false);
          }
          if (isRangeInCaretContainerBlock(rng)) {
            bookmark.isFakeCaret = true;
          }
          return bookmark;
        };
        var findIndex2 = function(dom2, name2, element) {
          var count2 = 0;
          Tools.each(dom2.select(name2), function(node) {
            if (node.getAttribute("data-mce-bogus") === "all") {
              return;
            }
            if (node === element) {
              return false;
            }
            count2++;
          });
          return count2;
        };
        var moveEndPoint$1 = function(rng, start5) {
          var container, offset2, childNodes;
          var prefix = start5 ? "start" : "end";
          container = rng[prefix + "Container"];
          offset2 = rng[prefix + "Offset"];
          if (isElement$5(container) && container.nodeName === "TR") {
            childNodes = container.childNodes;
            container = childNodes[Math.min(start5 ? offset2 : offset2 - 1, childNodes.length - 1)];
            if (container) {
              offset2 = start5 ? 0 : container.childNodes.length;
              rng["set" + (start5 ? "Start" : "End")](container, offset2);
            }
          }
        };
        var normalizeTableCellSelection = function(rng) {
          moveEndPoint$1(rng, true);
          moveEndPoint$1(rng, false);
          return rng;
        };
        var findSibling = function(node, offset2) {
          var sibling2;
          if (isElement$5(node)) {
            node = getNode$1(node, offset2);
            if (isContentEditableFalse$9(node)) {
              return node;
            }
          }
          if (isCaretContainer$2(node)) {
            if (isText$7(node) && isCaretContainerBlock$1(node)) {
              node = node.parentNode;
            }
            sibling2 = node.previousSibling;
            if (isContentEditableFalse$9(sibling2)) {
              return sibling2;
            }
            sibling2 = node.nextSibling;
            if (isContentEditableFalse$9(sibling2)) {
              return sibling2;
            }
          }
        };
        var findAdjacentContentEditableFalseElm = function(rng) {
          return findSibling(rng.startContainer, rng.startOffset) || findSibling(rng.endContainer, rng.endOffset);
        };
        var getOffsetBookmark = function(trim2, normalized, selection) {
          var element = selection.getNode();
          var name2 = element ? element.nodeName : null;
          var rng = selection.getRng();
          if (isContentEditableFalse$9(element) || name2 === "IMG") {
            return {
              name: name2,
              index: findIndex2(selection.dom, name2, element)
            };
          }
          var sibling2 = findAdjacentContentEditableFalseElm(rng);
          if (sibling2) {
            name2 = sibling2.tagName;
            return {
              name: name2,
              index: findIndex2(selection.dom, name2, sibling2)
            };
          }
          return getLocation(trim2, selection, normalized, rng);
        };
        var getCaretBookmark = function(selection) {
          var rng = selection.getRng();
          return {
            start: create$6(selection.dom.getRoot(), CaretPosition.fromRangeStart(rng)),
            end: create$6(selection.dom.getRoot(), CaretPosition.fromRangeEnd(rng))
          };
        };
        var getRangeBookmark = function(selection) {
          return { rng: selection.getRng() };
        };
        var createBookmarkSpan = function(dom2, id2, filled) {
          var args = {
            "data-mce-type": "bookmark",
            id: id2,
            "style": "overflow:hidden;line-height:0px"
          };
          return filled ? dom2.create("span", args, "&#xFEFF;") : dom2.create("span", args);
        };
        var getPersistentBookmark = function(selection, filled) {
          var dom2 = selection.dom;
          var rng = selection.getRng();
          var id2 = dom2.uniqueId();
          var collapsed = selection.isCollapsed();
          var element = selection.getNode();
          var name2 = element.nodeName;
          if (name2 === "IMG") {
            return {
              name: name2,
              index: findIndex2(dom2, name2, element)
            };
          }
          var rng2 = normalizeTableCellSelection(rng.cloneRange());
          if (!collapsed) {
            rng2.collapse(false);
            var endBookmarkNode = createBookmarkSpan(dom2, id2 + "_end", filled);
            rangeInsertNode(dom2, rng2, endBookmarkNode);
          }
          rng = normalizeTableCellSelection(rng);
          rng.collapse(true);
          var startBookmarkNode = createBookmarkSpan(dom2, id2 + "_start", filled);
          rangeInsertNode(dom2, rng, startBookmarkNode);
          selection.moveToBookmark({
            id: id2,
            keep: true
          });
          return { id: id2 };
        };
        var getBookmark$2 = function(selection, type2, normalized) {
          if (type2 === 2) {
            return getOffsetBookmark(trim$2, normalized, selection);
          } else if (type2 === 3) {
            return getCaretBookmark(selection);
          } else if (type2) {
            return getRangeBookmark(selection);
          } else {
            return getPersistentBookmark(selection, false);
          }
        };
        var getUndoBookmark = curry(getOffsetBookmark, identity, true);
        var DOM$9 = DOMUtils.DOM;
        var defaultPreviewStyles = "font-family font-size font-weight font-style text-decoration text-transform color background-color border border-radius outline text-shadow";
        var getBodySetting = function(editor, name2, defaultValue) {
          var value2 = editor.getParam(name2, defaultValue);
          if (value2.indexOf("=") !== -1) {
            var bodyObj = editor.getParam(name2, "", "hash");
            return get$9(bodyObj, editor.id).getOr(defaultValue);
          } else {
            return value2;
          }
        };
        var getIframeAttrs = function(editor) {
          return editor.getParam("iframe_attrs", {});
        };
        var getDocType = function(editor) {
          return editor.getParam("doctype", "<!DOCTYPE html>");
        };
        var getDocumentBaseUrl = function(editor) {
          return editor.getParam("document_base_url", "");
        };
        var getBodyId = function(editor) {
          return getBodySetting(editor, "body_id", "tinymce");
        };
        var getBodyClass = function(editor) {
          return getBodySetting(editor, "body_class", "");
        };
        var getContentSecurityPolicy = function(editor) {
          return editor.getParam("content_security_policy", "");
        };
        var shouldPutBrInPre$1 = function(editor) {
          return editor.getParam("br_in_pre", true);
        };
        var getForcedRootBlock = function(editor) {
          if (editor.getParam("force_p_newlines", false)) {
            return "p";
          }
          var block = editor.getParam("forced_root_block", "p");
          if (block === false) {
            return "";
          } else if (block === true) {
            return "p";
          } else {
            return block;
          }
        };
        var getForcedRootBlockAttrs = function(editor) {
          return editor.getParam("forced_root_block_attrs", {});
        };
        var getBrNewLineSelector = function(editor) {
          return editor.getParam("br_newline_selector", ".mce-toc h2,figcaption,caption");
        };
        var getNoNewLineSelector = function(editor) {
          return editor.getParam("no_newline_selector", "");
        };
        var shouldKeepStyles = function(editor) {
          return editor.getParam("keep_styles", true);
        };
        var shouldEndContainerOnEmptyBlock = function(editor) {
          return editor.getParam("end_container_on_empty_block", false);
        };
        var getFontStyleValues = function(editor) {
          return Tools.explode(editor.getParam("font_size_style_values", "xx-small,x-small,small,medium,large,x-large,xx-large"));
        };
        var getFontSizeClasses = function(editor) {
          return Tools.explode(editor.getParam("font_size_classes", ""));
        };
        var getImagesDataImgFilter = function(editor) {
          return editor.getParam("images_dataimg_filter", always, "function");
        };
        var isAutomaticUploadsEnabled = function(editor) {
          return editor.getParam("automatic_uploads", true, "boolean");
        };
        var shouldReuseFileName = function(editor) {
          return editor.getParam("images_reuse_filename", false, "boolean");
        };
        var shouldReplaceBlobUris = function(editor) {
          return editor.getParam("images_replace_blob_uris", true, "boolean");
        };
        var getIconPackName = function(editor) {
          return editor.getParam("icons", "", "string");
        };
        var getIconsUrl = function(editor) {
          return editor.getParam("icons_url", "", "string");
        };
        var getImageUploadUrl = function(editor) {
          return editor.getParam("images_upload_url", "", "string");
        };
        var getImageUploadBasePath = function(editor) {
          return editor.getParam("images_upload_base_path", "", "string");
        };
        var getImagesUploadCredentials = function(editor) {
          return editor.getParam("images_upload_credentials", false, "boolean");
        };
        var getImagesUploadHandler = function(editor) {
          return editor.getParam("images_upload_handler", null, "function");
        };
        var shouldUseContentCssCors = function(editor) {
          return editor.getParam("content_css_cors", false, "boolean");
        };
        var getReferrerPolicy = function(editor) {
          return editor.getParam("referrer_policy", "", "string");
        };
        var getLanguageCode = function(editor) {
          return editor.getParam("language", "en", "string");
        };
        var getLanguageUrl = function(editor) {
          return editor.getParam("language_url", "", "string");
        };
        var shouldIndentUseMargin = function(editor) {
          return editor.getParam("indent_use_margin", false);
        };
        var getIndentation = function(editor) {
          return editor.getParam("indentation", "40px", "string");
        };
        var getContentCss = function(editor) {
          var contentCss = editor.getParam("content_css");
          if (isString$1(contentCss)) {
            return map$3(contentCss.split(","), trim$4);
          } else if (isArray$1(contentCss)) {
            return contentCss;
          } else if (contentCss === false || editor.inline) {
            return [];
          } else {
            return ["default"];
          }
        };
        var getFontCss = function(editor) {
          var fontCss = editor.getParam("font_css", []);
          return isArray$1(fontCss) ? fontCss : map$3(fontCss.split(","), trim$4);
        };
        var getDirectionality = function(editor) {
          return editor.getParam("directionality", I18n.isRtl() ? "rtl" : void 0);
        };
        var getInlineBoundarySelector = function(editor) {
          return editor.getParam("inline_boundaries_selector", "a[href],code,.mce-annotation", "string");
        };
        var getObjectResizing = function(editor) {
          var selector = editor.getParam("object_resizing");
          if (selector === false || Env.iOS) {
            return false;
          } else {
            return isString$1(selector) ? selector : "table,img,figure.image,div,video,iframe";
          }
        };
        var getResizeImgProportional = function(editor) {
          return editor.getParam("resize_img_proportional", true, "boolean");
        };
        var getPlaceholder = function(editor) {
          return editor.getParam("placeholder", DOM$9.getAttrib(editor.getElement(), "placeholder"), "string");
        };
        var getEventRoot = function(editor) {
          return editor.getParam("event_root");
        };
        var getServiceMessage = function(editor) {
          return editor.getParam("service_message");
        };
        var getTheme = function(editor) {
          return editor.getParam("theme");
        };
        var shouldValidate = function(editor) {
          return editor.getParam("validate");
        };
        var isInlineBoundariesEnabled = function(editor) {
          return editor.getParam("inline_boundaries") !== false;
        };
        var getFormats = function(editor) {
          return editor.getParam("formats");
        };
        var getPreviewStyles = function(editor) {
          var style = editor.getParam("preview_styles", defaultPreviewStyles);
          if (isString$1(style)) {
            return style;
          } else {
            return "";
          }
        };
        var canFormatEmptyLines = function(editor) {
          return editor.getParam("format_empty_lines", false, "boolean");
        };
        var getCustomUiSelector = function(editor) {
          return editor.getParam("custom_ui_selector", "", "string");
        };
        var getThemeUrl = function(editor) {
          return editor.getParam("theme_url");
        };
        var isInline = function(editor) {
          return editor.getParam("inline");
        };
        var hasHiddenInput = function(editor) {
          return editor.getParam("hidden_input");
        };
        var shouldPatchSubmit = function(editor) {
          return editor.getParam("submit_patch");
        };
        var isEncodingXml = function(editor) {
          return editor.getParam("encoding") === "xml";
        };
        var shouldAddFormSubmitTrigger = function(editor) {
          return editor.getParam("add_form_submit_trigger");
        };
        var shouldAddUnloadTrigger = function(editor) {
          return editor.getParam("add_unload_trigger");
        };
        var hasForcedRootBlock = function(editor) {
          return getForcedRootBlock(editor) !== "";
        };
        var getCustomUndoRedoLevels = function(editor) {
          return editor.getParam("custom_undo_redo_levels", 0, "number");
        };
        var shouldDisableNodeChange = function(editor) {
          return editor.getParam("disable_nodechange");
        };
        var isReadOnly$1 = function(editor) {
          return editor.getParam("readonly");
        };
        var hasContentCssCors = function(editor) {
          return editor.getParam("content_css_cors");
        };
        var getPlugins = function(editor) {
          return editor.getParam("plugins", "", "string");
        };
        var getExternalPlugins$1 = function(editor) {
          return editor.getParam("external_plugins");
        };
        var shouldBlockUnsupportedDrop = function(editor) {
          return editor.getParam("block_unsupported_drop", true, "boolean");
        };
        var isVisualAidsEnabled = function(editor) {
          return editor.getParam("visual", true, "boolean");
        };
        var getVisualAidsTableClass = function(editor) {
          return editor.getParam("visual_table_class", "mce-item-table", "string");
        };
        var getVisualAidsAnchorClass = function(editor) {
          return editor.getParam("visual_anchor_class", "mce-item-anchor", "string");
        };
        var getIframeAriaText = function(editor) {
          return editor.getParam("iframe_aria_text", "Rich Text Area. Press ALT-0 for help.", "string");
        };
        var isElement$2 = isElement$5;
        var isText$2 = isText$7;
        var removeNode$1 = function(node) {
          var parentNode = node.parentNode;
          if (parentNode) {
            parentNode.removeChild(node);
          }
        };
        var trimCount = function(text) {
          var trimmedText = trim$2(text);
          return {
            count: text.length - trimmedText.length,
            text: trimmedText
          };
        };
        var deleteZwspChars = function(caretContainer) {
          var idx;
          while ((idx = caretContainer.data.lastIndexOf(ZWSP$1)) !== -1) {
            caretContainer.deleteData(idx, 1);
          }
        };
        var removeUnchanged = function(caretContainer, pos) {
          remove$2(caretContainer);
          return pos;
        };
        var removeTextAndReposition = function(caretContainer, pos) {
          var before2 = trimCount(caretContainer.data.substr(0, pos.offset()));
          var after2 = trimCount(caretContainer.data.substr(pos.offset()));
          var text = before2.text + after2.text;
          if (text.length > 0) {
            deleteZwspChars(caretContainer);
            return CaretPosition(caretContainer, pos.offset() - before2.count);
          } else {
            return pos;
          }
        };
        var removeElementAndReposition = function(caretContainer, pos) {
          var parentNode = pos.container();
          var newPosition = indexOf$2(from(parentNode.childNodes), caretContainer).map(function(index) {
            return index < pos.offset() ? CaretPosition(parentNode, pos.offset() - 1) : pos;
          }).getOr(pos);
          remove$2(caretContainer);
          return newPosition;
        };
        var removeTextCaretContainer = function(caretContainer, pos) {
          return isText$2(caretContainer) && pos.container() === caretContainer ? removeTextAndReposition(caretContainer, pos) : removeUnchanged(caretContainer, pos);
        };
        var removeElementCaretContainer = function(caretContainer, pos) {
          return pos.container() === caretContainer.parentNode ? removeElementAndReposition(caretContainer, pos) : removeUnchanged(caretContainer, pos);
        };
        var removeAndReposition = function(container, pos) {
          return CaretPosition.isTextPosition(pos) ? removeTextCaretContainer(container, pos) : removeElementCaretContainer(container, pos);
        };
        var remove$2 = function(caretContainerNode) {
          if (isElement$2(caretContainerNode) && isCaretContainer$2(caretContainerNode)) {
            if (hasContent(caretContainerNode)) {
              caretContainerNode.removeAttribute("data-mce-caret");
            } else {
              removeNode$1(caretContainerNode);
            }
          }
          if (isText$2(caretContainerNode)) {
            deleteZwspChars(caretContainerNode);
            if (caretContainerNode.data.length === 0) {
              removeNode$1(caretContainerNode);
            }
          }
        };
        var browser$2 = detect().browser;
        var isContentEditableFalse$8 = isContentEditableFalse$b;
        var isMedia$1 = isMedia$2;
        var isTableCell$3 = isTableCell$5;
        var inlineFakeCaretSelector = "*[contentEditable=false],video,audio,embed,object";
        var getAbsoluteClientRect = function(root, element, before2) {
          var clientRect = collapse(element.getBoundingClientRect(), before2);
          var scrollX;
          var scrollY;
          if (root.tagName === "BODY") {
            var docElm = root.ownerDocument.documentElement;
            scrollX = root.scrollLeft || docElm.scrollLeft;
            scrollY = root.scrollTop || docElm.scrollTop;
          } else {
            var rootRect = root.getBoundingClientRect();
            scrollX = root.scrollLeft - rootRect.left;
            scrollY = root.scrollTop - rootRect.top;
          }
          clientRect.left += scrollX;
          clientRect.right += scrollX;
          clientRect.top += scrollY;
          clientRect.bottom += scrollY;
          clientRect.width = 1;
          var margin = element.offsetWidth - element.clientWidth;
          if (margin > 0) {
            if (before2) {
              margin *= -1;
            }
            clientRect.left += margin;
            clientRect.right += margin;
          }
          return clientRect;
        };
        var trimInlineCaretContainers = function(root) {
          var fakeCaretTargetNodes = descendants(SugarElement.fromDom(root), inlineFakeCaretSelector);
          for (var i2 = 0; i2 < fakeCaretTargetNodes.length; i2++) {
            var node = fakeCaretTargetNodes[i2].dom;
            var sibling2 = node.previousSibling;
            if (endsWithCaretContainer$1(sibling2)) {
              var data2 = sibling2.data;
              if (data2.length === 1) {
                sibling2.parentNode.removeChild(sibling2);
              } else {
                sibling2.deleteData(data2.length - 1, 1);
              }
            }
            sibling2 = node.nextSibling;
            if (startsWithCaretContainer$1(sibling2)) {
              var data2 = sibling2.data;
              if (data2.length === 1) {
                sibling2.parentNode.removeChild(sibling2);
              } else {
                sibling2.deleteData(0, 1);
              }
            }
          }
        };
        var FakeCaret = function(editor, root, isBlock2, hasFocus2) {
          var lastVisualCaret = value();
          var cursorInterval;
          var caretContainerNode;
          var rootBlock = getForcedRootBlock(editor);
          var caretBlock = rootBlock.length > 0 ? rootBlock : "p";
          var show = function(before2, element) {
            var rng;
            hide2();
            if (isTableCell$3(element)) {
              return null;
            }
            if (isBlock2(element)) {
              caretContainerNode = insertBlock$1(caretBlock, element, before2);
              var clientRect = getAbsoluteClientRect(root, element, before2);
              DomQuery(caretContainerNode).css("top", clientRect.top);
              var caret = DomQuery('<div class="mce-visual-caret" data-mce-bogus="all"></div>').css(__assign({}, clientRect)).appendTo(root)[0];
              lastVisualCaret.set({
                caret,
                element,
                before: before2
              });
              if (before2) {
                DomQuery(caret).addClass("mce-visual-caret-before");
              }
              startBlink();
              rng = element.ownerDocument.createRange();
              rng.setStart(caretContainerNode, 0);
              rng.setEnd(caretContainerNode, 0);
            } else {
              caretContainerNode = insertInline$1(element, before2);
              rng = element.ownerDocument.createRange();
              if (isInlineFakeCaretTarget(caretContainerNode.nextSibling)) {
                rng.setStart(caretContainerNode, 0);
                rng.setEnd(caretContainerNode, 0);
              } else {
                rng.setStart(caretContainerNode, 1);
                rng.setEnd(caretContainerNode, 1);
              }
              return rng;
            }
            return rng;
          };
          var hide2 = function() {
            trimInlineCaretContainers(root);
            if (caretContainerNode) {
              remove$2(caretContainerNode);
              caretContainerNode = null;
            }
            lastVisualCaret.on(function(caretState) {
              DomQuery(caretState.caret).remove();
              lastVisualCaret.clear();
            });
            if (cursorInterval) {
              Delay.clearInterval(cursorInterval);
              cursorInterval = void 0;
            }
          };
          var startBlink = function() {
            cursorInterval = Delay.setInterval(function() {
              if (hasFocus2()) {
                DomQuery("div.mce-visual-caret", root).toggleClass("mce-visual-caret-hidden");
              } else {
                DomQuery("div.mce-visual-caret", root).addClass("mce-visual-caret-hidden");
              }
            }, 500);
          };
          var reposition2 = function() {
            lastVisualCaret.on(function(caretState) {
              var clientRect = getAbsoluteClientRect(root, caretState.element, caretState.before);
              DomQuery(caretState.caret).css(__assign({}, clientRect));
            });
          };
          var destroy2 = function() {
            return Delay.clearInterval(cursorInterval);
          };
          var getCss = function() {
            return ".mce-visual-caret {position: absolute;background-color: black;background-color: currentcolor;}.mce-visual-caret-hidden {display: none;}*[data-mce-caret] {position: absolute;left: -1000px;right: auto;top: 0;margin: 0;padding: 0;}";
          };
          return {
            show,
            hide: hide2,
            getCss,
            reposition: reposition2,
            destroy: destroy2
          };
        };
        var isFakeCaretTableBrowser = function() {
          return browser$2.isIE() || browser$2.isEdge() || browser$2.isFirefox();
        };
        var isInlineFakeCaretTarget = function(node) {
          return isContentEditableFalse$8(node) || isMedia$1(node);
        };
        var isFakeCaretTarget = function(node) {
          return isInlineFakeCaretTarget(node) || isTable$3(node) && isFakeCaretTableBrowser();
        };
        var isContentEditableFalse$7 = isContentEditableFalse$b;
        var isMedia = isMedia$2;
        var isBlockLike = matchStyleValues("display", "block table table-cell table-caption list-item");
        var isCaretContainer = isCaretContainer$2;
        var isCaretContainerBlock = isCaretContainerBlock$1;
        var isElement$1 = isElement$5;
        var isCaretCandidate$1 = isCaretCandidate$3;
        var isForwards = function(direction) {
          return direction > 0;
        };
        var isBackwards = function(direction) {
          return direction < 0;
        };
        var skipCaretContainers = function(walk3, shallow2) {
          var node;
          while (node = walk3(shallow2)) {
            if (!isCaretContainerBlock(node)) {
              return node;
            }
          }
          return null;
        };
        var findNode$1 = function(node, direction, predicateFn, rootNode, shallow2) {
          var walker = new DomTreeWalker(node, rootNode);
          var isCefOrCaretContainer = isContentEditableFalse$7(node) || isCaretContainerBlock(node);
          if (isBackwards(direction)) {
            if (isCefOrCaretContainer) {
              node = skipCaretContainers(walker.prev.bind(walker), true);
              if (predicateFn(node)) {
                return node;
              }
            }
            while (node = skipCaretContainers(walker.prev.bind(walker), shallow2)) {
              if (predicateFn(node)) {
                return node;
              }
            }
          }
          if (isForwards(direction)) {
            if (isCefOrCaretContainer) {
              node = skipCaretContainers(walker.next.bind(walker), true);
              if (predicateFn(node)) {
                return node;
              }
            }
            while (node = skipCaretContainers(walker.next.bind(walker), shallow2)) {
              if (predicateFn(node)) {
                return node;
              }
            }
          }
          return null;
        };
        var getParentBlock$2 = function(node, rootNode) {
          while (node && node !== rootNode) {
            if (isBlockLike(node)) {
              return node;
            }
            node = node.parentNode;
          }
          return null;
        };
        var isInSameBlock = function(caretPosition1, caretPosition2, rootNode) {
          return getParentBlock$2(caretPosition1.container(), rootNode) === getParentBlock$2(caretPosition2.container(), rootNode);
        };
        var getChildNodeAtRelativeOffset = function(relativeOffset, caretPosition) {
          if (!caretPosition) {
            return null;
          }
          var container = caretPosition.container();
          var offset2 = caretPosition.offset();
          if (!isElement$1(container)) {
            return null;
          }
          return container.childNodes[offset2 + relativeOffset];
        };
        var beforeAfter = function(before2, node) {
          var range2 = node.ownerDocument.createRange();
          if (before2) {
            range2.setStartBefore(node);
            range2.setEndBefore(node);
          } else {
            range2.setStartAfter(node);
            range2.setEndAfter(node);
          }
          return range2;
        };
        var isNodesInSameBlock = function(root, node1, node2) {
          return getParentBlock$2(node1, root) === getParentBlock$2(node2, root);
        };
        var lean = function(left2, root, node) {
          var siblingName = left2 ? "previousSibling" : "nextSibling";
          while (node && node !== root) {
            var sibling2 = node[siblingName];
            if (isCaretContainer(sibling2)) {
              sibling2 = sibling2[siblingName];
            }
            if (isContentEditableFalse$7(sibling2) || isMedia(sibling2)) {
              if (isNodesInSameBlock(root, sibling2, node)) {
                return sibling2;
              }
              break;
            }
            if (isCaretCandidate$1(sibling2)) {
              break;
            }
            node = node.parentNode;
          }
          return null;
        };
        var before$2 = curry(beforeAfter, true);
        var after$2 = curry(beforeAfter, false);
        var normalizeRange = function(direction, root, range2) {
          var node;
          var leanLeft = curry(lean, true, root);
          var leanRight2 = curry(lean, false, root);
          var container = range2.startContainer;
          var offset2 = range2.startOffset;
          if (isCaretContainerBlock$1(container)) {
            if (!isElement$1(container)) {
              container = container.parentNode;
            }
            var location_1 = container.getAttribute("data-mce-caret");
            if (location_1 === "before") {
              node = container.nextSibling;
              if (isFakeCaretTarget(node)) {
                return before$2(node);
              }
            }
            if (location_1 === "after") {
              node = container.previousSibling;
              if (isFakeCaretTarget(node)) {
                return after$2(node);
              }
            }
          }
          if (!range2.collapsed) {
            return range2;
          }
          if (isText$7(container)) {
            if (isCaretContainer(container)) {
              if (direction === 1) {
                node = leanRight2(container);
                if (node) {
                  return before$2(node);
                }
                node = leanLeft(container);
                if (node) {
                  return after$2(node);
                }
              }
              if (direction === -1) {
                node = leanLeft(container);
                if (node) {
                  return after$2(node);
                }
                node = leanRight2(container);
                if (node) {
                  return before$2(node);
                }
              }
              return range2;
            }
            if (endsWithCaretContainer$1(container) && offset2 >= container.data.length - 1) {
              if (direction === 1) {
                node = leanRight2(container);
                if (node) {
                  return before$2(node);
                }
              }
              return range2;
            }
            if (startsWithCaretContainer$1(container) && offset2 <= 1) {
              if (direction === -1) {
                node = leanLeft(container);
                if (node) {
                  return after$2(node);
                }
              }
              return range2;
            }
            if (offset2 === container.data.length) {
              node = leanRight2(container);
              if (node) {
                return before$2(node);
              }
              return range2;
            }
            if (offset2 === 0) {
              node = leanLeft(container);
              if (node) {
                return after$2(node);
              }
              return range2;
            }
          }
          return range2;
        };
        var getRelativeCefElm = function(forward, caretPosition) {
          return Optional.from(getChildNodeAtRelativeOffset(forward ? 0 : -1, caretPosition)).filter(isContentEditableFalse$7);
        };
        var getNormalizedRangeEndPoint = function(direction, root, range2) {
          var normalizedRange = normalizeRange(direction, root, range2);
          if (direction === -1) {
            return CaretPosition.fromRangeStart(normalizedRange);
          }
          return CaretPosition.fromRangeEnd(normalizedRange);
        };
        var getElementFromPosition = function(pos) {
          return Optional.from(pos.getNode()).map(SugarElement.fromDom);
        };
        var getElementFromPrevPosition = function(pos) {
          return Optional.from(pos.getNode(true)).map(SugarElement.fromDom);
        };
        var getVisualCaretPosition = function(walkFn, caretPosition) {
          while (caretPosition = walkFn(caretPosition)) {
            if (caretPosition.isVisible()) {
              return caretPosition;
            }
          }
          return caretPosition;
        };
        var isMoveInsideSameBlock = function(from2, to2) {
          var inSameBlock = isInSameBlock(from2, to2);
          if (!inSameBlock && isBr$5(from2.getNode())) {
            return true;
          }
          return inSameBlock;
        };
        var HDirection;
        (function(HDirection2) {
          HDirection2[HDirection2["Backwards"] = -1] = "Backwards";
          HDirection2[HDirection2["Forwards"] = 1] = "Forwards";
        })(HDirection || (HDirection = {}));
        var isContentEditableFalse$6 = isContentEditableFalse$b;
        var isText$1 = isText$7;
        var isElement3 = isElement$5;
        var isBr$1 = isBr$5;
        var isCaretCandidate = isCaretCandidate$3;
        var isAtomic = isAtomic$1;
        var isEditableCaretCandidate = isEditableCaretCandidate$1;
        var getParents$3 = function(node, root) {
          var parents2 = [];
          while (node && node !== root) {
            parents2.push(node);
            node = node.parentNode;
          }
          return parents2;
        };
        var nodeAtIndex = function(container, offset2) {
          if (container.hasChildNodes() && offset2 < container.childNodes.length) {
            return container.childNodes[offset2];
          }
          return null;
        };
        var getCaretCandidatePosition = function(direction, node) {
          if (isForwards(direction)) {
            if (isCaretCandidate(node.previousSibling) && !isText$1(node.previousSibling)) {
              return CaretPosition.before(node);
            }
            if (isText$1(node)) {
              return CaretPosition(node, 0);
            }
          }
          if (isBackwards(direction)) {
            if (isCaretCandidate(node.nextSibling) && !isText$1(node.nextSibling)) {
              return CaretPosition.after(node);
            }
            if (isText$1(node)) {
              return CaretPosition(node, node.data.length);
            }
          }
          if (isBackwards(direction)) {
            if (isBr$1(node)) {
              return CaretPosition.before(node);
            }
            return CaretPosition.after(node);
          }
          return CaretPosition.before(node);
        };
        var moveForwardFromBr = function(root, nextNode) {
          var nextSibling2 = nextNode.nextSibling;
          if (nextSibling2 && isCaretCandidate(nextSibling2)) {
            if (isText$1(nextSibling2)) {
              return CaretPosition(nextSibling2, 0);
            } else {
              return CaretPosition.before(nextSibling2);
            }
          } else {
            return findCaretPosition$1(HDirection.Forwards, CaretPosition.after(nextNode), root);
          }
        };
        var findCaretPosition$1 = function(direction, startPos, root) {
          var node;
          var nextNode;
          var innerNode;
          var caretPosition;
          if (!isElement3(root) || !startPos) {
            return null;
          }
          if (startPos.isEqual(CaretPosition.after(root)) && root.lastChild) {
            caretPosition = CaretPosition.after(root.lastChild);
            if (isBackwards(direction) && isCaretCandidate(root.lastChild) && isElement3(root.lastChild)) {
              return isBr$1(root.lastChild) ? CaretPosition.before(root.lastChild) : caretPosition;
            }
          } else {
            caretPosition = startPos;
          }
          var container = caretPosition.container();
          var offset2 = caretPosition.offset();
          if (isText$1(container)) {
            if (isBackwards(direction) && offset2 > 0) {
              return CaretPosition(container, --offset2);
            }
            if (isForwards(direction) && offset2 < container.length) {
              return CaretPosition(container, ++offset2);
            }
            node = container;
          } else {
            if (isBackwards(direction) && offset2 > 0) {
              nextNode = nodeAtIndex(container, offset2 - 1);
              if (isCaretCandidate(nextNode)) {
                if (!isAtomic(nextNode)) {
                  innerNode = findNode$1(nextNode, direction, isEditableCaretCandidate, nextNode);
                  if (innerNode) {
                    if (isText$1(innerNode)) {
                      return CaretPosition(innerNode, innerNode.data.length);
                    }
                    return CaretPosition.after(innerNode);
                  }
                }
                if (isText$1(nextNode)) {
                  return CaretPosition(nextNode, nextNode.data.length);
                }
                return CaretPosition.before(nextNode);
              }
            }
            if (isForwards(direction) && offset2 < container.childNodes.length) {
              nextNode = nodeAtIndex(container, offset2);
              if (isCaretCandidate(nextNode)) {
                if (isBr$1(nextNode)) {
                  return moveForwardFromBr(root, nextNode);
                }
                if (!isAtomic(nextNode)) {
                  innerNode = findNode$1(nextNode, direction, isEditableCaretCandidate, nextNode);
                  if (innerNode) {
                    if (isText$1(innerNode)) {
                      return CaretPosition(innerNode, 0);
                    }
                    return CaretPosition.before(innerNode);
                  }
                }
                if (isText$1(nextNode)) {
                  return CaretPosition(nextNode, 0);
                }
                return CaretPosition.after(nextNode);
              }
            }
            node = nextNode ? nextNode : caretPosition.getNode();
          }
          if (isForwards(direction) && caretPosition.isAtEnd() || isBackwards(direction) && caretPosition.isAtStart()) {
            node = findNode$1(node, direction, always, root, true);
            if (isEditableCaretCandidate(node, root)) {
              return getCaretCandidatePosition(direction, node);
            }
          }
          nextNode = findNode$1(node, direction, isEditableCaretCandidate, root);
          var rootContentEditableFalseElm = last$1(filter$4(getParents$3(container, root), isContentEditableFalse$6));
          if (rootContentEditableFalseElm && (!nextNode || !rootContentEditableFalseElm.contains(nextNode))) {
            if (isForwards(direction)) {
              caretPosition = CaretPosition.after(rootContentEditableFalseElm);
            } else {
              caretPosition = CaretPosition.before(rootContentEditableFalseElm);
            }
            return caretPosition;
          }
          if (nextNode) {
            return getCaretCandidatePosition(direction, nextNode);
          }
          return null;
        };
        var CaretWalker = function(root) {
          return {
            next: function(caretPosition) {
              return findCaretPosition$1(HDirection.Forwards, caretPosition, root);
            },
            prev: function(caretPosition) {
              return findCaretPosition$1(HDirection.Backwards, caretPosition, root);
            }
          };
        };
        var walkToPositionIn = function(forward, root, start5) {
          var position = forward ? CaretPosition.before(start5) : CaretPosition.after(start5);
          return fromPosition(forward, root, position);
        };
        var afterElement = function(node) {
          return isBr$5(node) ? CaretPosition.before(node) : CaretPosition.after(node);
        };
        var isBeforeOrStart = function(position) {
          if (CaretPosition.isTextPosition(position)) {
            return position.offset() === 0;
          } else {
            return isCaretCandidate$3(position.getNode());
          }
        };
        var isAfterOrEnd = function(position) {
          if (CaretPosition.isTextPosition(position)) {
            var container = position.container();
            return position.offset() === container.data.length;
          } else {
            return isCaretCandidate$3(position.getNode(true));
          }
        };
        var isBeforeAfterSameElement = function(from2, to2) {
          return !CaretPosition.isTextPosition(from2) && !CaretPosition.isTextPosition(to2) && from2.getNode() === to2.getNode(true);
        };
        var isAtBr = function(position) {
          return !CaretPosition.isTextPosition(position) && isBr$5(position.getNode());
        };
        var shouldSkipPosition = function(forward, from2, to2) {
          if (forward) {
            return !isBeforeAfterSameElement(from2, to2) && !isAtBr(from2) && isAfterOrEnd(from2) && isBeforeOrStart(to2);
          } else {
            return !isBeforeAfterSameElement(to2, from2) && isBeforeOrStart(from2) && isAfterOrEnd(to2);
          }
        };
        var fromPosition = function(forward, root, pos) {
          var walker = CaretWalker(root);
          return Optional.from(forward ? walker.next(pos) : walker.prev(pos));
        };
        var navigate = function(forward, root, from2) {
          return fromPosition(forward, root, from2).bind(function(to2) {
            if (isInSameBlock(from2, to2, root) && shouldSkipPosition(forward, from2, to2)) {
              return fromPosition(forward, root, to2);
            } else {
              return Optional.some(to2);
            }
          });
        };
        var navigateIgnore = function(forward, root, from2, ignoreFilter) {
          return navigate(forward, root, from2).bind(function(pos) {
            return ignoreFilter(pos) ? navigateIgnore(forward, root, pos, ignoreFilter) : Optional.some(pos);
          });
        };
        var positionIn = function(forward, element) {
          var startNode = forward ? element.firstChild : element.lastChild;
          if (isText$7(startNode)) {
            return Optional.some(CaretPosition(startNode, forward ? 0 : startNode.data.length));
          } else if (startNode) {
            if (isCaretCandidate$3(startNode)) {
              return Optional.some(forward ? CaretPosition.before(startNode) : afterElement(startNode));
            } else {
              return walkToPositionIn(forward, element, startNode);
            }
          } else {
            return Optional.none();
          }
        };
        var nextPosition = curry(fromPosition, true);
        var prevPosition = curry(fromPosition, false);
        var firstPositionIn = curry(positionIn, true);
        var lastPositionIn = curry(positionIn, false);
        var CARET_ID$1 = "_mce_caret";
        var isCaretNode = function(node) {
          return isElement$5(node) && node.id === CARET_ID$1;
        };
        var getParentCaretContainer = function(body, node) {
          while (node && node !== body) {
            if (node.id === CARET_ID$1) {
              return node;
            }
            node = node.parentNode;
          }
          return null;
        };
        var isStringPathBookmark = function(bookmark) {
          return isString$1(bookmark.start);
        };
        var isRangeBookmark = function(bookmark) {
          return has$2(bookmark, "rng");
        };
        var isIdBookmark = function(bookmark) {
          return has$2(bookmark, "id");
        };
        var isIndexBookmark = function(bookmark) {
          return has$2(bookmark, "name");
        };
        var isPathBookmark = function(bookmark) {
          return Tools.isArray(bookmark.start);
        };
        var addBogus = function(dom2, node) {
          if (isElement$5(node) && dom2.isBlock(node) && !node.innerHTML && !Env.ie) {
            node.innerHTML = '<br data-mce-bogus="1" />';
          }
          return node;
        };
        var resolveCaretPositionBookmark = function(dom2, bookmark) {
          var pos;
          var rng = dom2.createRng();
          pos = resolve$2(dom2.getRoot(), bookmark.start);
          rng.setStart(pos.container(), pos.offset());
          pos = resolve$2(dom2.getRoot(), bookmark.end);
          rng.setEnd(pos.container(), pos.offset());
          return rng;
        };
        var insertZwsp = function(node, rng) {
          var textNode = node.ownerDocument.createTextNode(ZWSP$1);
          node.appendChild(textNode);
          rng.setStart(textNode, 0);
          rng.setEnd(textNode, 0);
        };
        var isEmpty$1 = function(node) {
          return node.hasChildNodes() === false;
        };
        var tryFindRangePosition = function(node, rng) {
          return lastPositionIn(node).fold(never, function(pos) {
            rng.setStart(pos.container(), pos.offset());
            rng.setEnd(pos.container(), pos.offset());
            return true;
          });
        };
        var padEmptyCaretContainer = function(root, node, rng) {
          if (isEmpty$1(node) && getParentCaretContainer(root, node)) {
            insertZwsp(node, rng);
            return true;
          } else {
            return false;
          }
        };
        var setEndPoint = function(dom2, start5, bookmark, rng) {
          var point = bookmark[start5 ? "start" : "end"];
          var i2, node, offset2, children2;
          var root = dom2.getRoot();
          if (point) {
            offset2 = point[0];
            for (node = root, i2 = point.length - 1; i2 >= 1; i2--) {
              children2 = node.childNodes;
              if (padEmptyCaretContainer(root, node, rng)) {
                return true;
              }
              if (point[i2] > children2.length - 1) {
                if (padEmptyCaretContainer(root, node, rng)) {
                  return true;
                }
                return tryFindRangePosition(node, rng);
              }
              node = children2[point[i2]];
            }
            if (node.nodeType === 3) {
              offset2 = Math.min(point[0], node.nodeValue.length);
            }
            if (node.nodeType === 1) {
              offset2 = Math.min(point[0], node.childNodes.length);
            }
            if (start5) {
              rng.setStart(node, offset2);
            } else {
              rng.setEnd(node, offset2);
            }
          }
          return true;
        };
        var isValidTextNode = function(node) {
          return isText$7(node) && node.data.length > 0;
        };
        var restoreEndPoint = function(dom2, suffix, bookmark) {
          var marker = dom2.get(bookmark.id + "_" + suffix), node, idx, next, prev;
          var keep = bookmark.keep;
          var container, offset2;
          if (marker) {
            node = marker.parentNode;
            if (suffix === "start") {
              if (!keep) {
                idx = dom2.nodeIndex(marker);
              } else {
                if (marker.hasChildNodes()) {
                  node = marker.firstChild;
                  idx = 1;
                } else if (isValidTextNode(marker.nextSibling)) {
                  node = marker.nextSibling;
                  idx = 0;
                } else if (isValidTextNode(marker.previousSibling)) {
                  node = marker.previousSibling;
                  idx = marker.previousSibling.data.length;
                } else {
                  node = marker.parentNode;
                  idx = dom2.nodeIndex(marker) + 1;
                }
              }
              container = node;
              offset2 = idx;
            } else {
              if (!keep) {
                idx = dom2.nodeIndex(marker);
              } else {
                if (marker.hasChildNodes()) {
                  node = marker.firstChild;
                  idx = 1;
                } else if (isValidTextNode(marker.previousSibling)) {
                  node = marker.previousSibling;
                  idx = marker.previousSibling.data.length;
                } else {
                  node = marker.parentNode;
                  idx = dom2.nodeIndex(marker);
                }
              }
              container = node;
              offset2 = idx;
            }
            if (!keep) {
              prev = marker.previousSibling;
              next = marker.nextSibling;
              Tools.each(Tools.grep(marker.childNodes), function(node2) {
                if (isText$7(node2)) {
                  node2.nodeValue = node2.nodeValue.replace(/\uFEFF/g, "");
                }
              });
              while (marker = dom2.get(bookmark.id + "_" + suffix)) {
                dom2.remove(marker, true);
              }
              if (prev && next && prev.nodeType === next.nodeType && isText$7(prev) && !Env.opera) {
                idx = prev.nodeValue.length;
                prev.appendData(next.nodeValue);
                dom2.remove(next);
                container = prev;
                offset2 = idx;
              }
            }
            return Optional.some(CaretPosition(container, offset2));
          } else {
            return Optional.none();
          }
        };
        var resolvePaths = function(dom2, bookmark) {
          var rng = dom2.createRng();
          if (setEndPoint(dom2, true, bookmark, rng) && setEndPoint(dom2, false, bookmark, rng)) {
            return Optional.some(rng);
          } else {
            return Optional.none();
          }
        };
        var resolveId = function(dom2, bookmark) {
          var startPos = restoreEndPoint(dom2, "start", bookmark);
          var endPos = restoreEndPoint(dom2, "end", bookmark);
          return lift2(startPos, endPos.or(startPos), function(spos, epos) {
            var rng = dom2.createRng();
            rng.setStart(addBogus(dom2, spos.container()), spos.offset());
            rng.setEnd(addBogus(dom2, epos.container()), epos.offset());
            return rng;
          });
        };
        var resolveIndex = function(dom2, bookmark) {
          return Optional.from(dom2.select(bookmark.name)[bookmark.index]).map(function(elm) {
            var rng = dom2.createRng();
            rng.selectNode(elm);
            return rng;
          });
        };
        var resolve$1 = function(selection, bookmark) {
          var dom2 = selection.dom;
          if (bookmark) {
            if (isPathBookmark(bookmark)) {
              return resolvePaths(dom2, bookmark);
            } else if (isStringPathBookmark(bookmark)) {
              return Optional.some(resolveCaretPositionBookmark(dom2, bookmark));
            } else if (isIdBookmark(bookmark)) {
              return resolveId(dom2, bookmark);
            } else if (isIndexBookmark(bookmark)) {
              return resolveIndex(dom2, bookmark);
            } else if (isRangeBookmark(bookmark)) {
              return Optional.some(bookmark.rng);
            }
          }
          return Optional.none();
        };
        var getBookmark$1 = function(selection, type2, normalized) {
          return getBookmark$2(selection, type2, normalized);
        };
        var moveToBookmark = function(selection, bookmark) {
          resolve$1(selection, bookmark).each(function(rng) {
            selection.setRng(rng);
          });
        };
        var isBookmarkNode$1 = function(node) {
          return isElement$5(node) && node.tagName === "SPAN" && node.getAttribute("data-mce-type") === "bookmark";
        };
        var is = function(expected) {
          return function(actual) {
            return expected === actual;
          };
        };
        var isNbsp = is(nbsp);
        var isWhiteSpace = function(chr) {
          return chr !== "" && " \f\n\r	\v".indexOf(chr) !== -1;
        };
        var isContent = function(chr) {
          return !isWhiteSpace(chr) && !isNbsp(chr);
        };
        var isNode = function(node) {
          return !!node.nodeType;
        };
        var isInlineBlock = function(node) {
          return node && /^(IMG)$/.test(node.nodeName);
        };
        var moveStart = function(dom2, selection, rng) {
          var offset2 = rng.startOffset;
          var container = rng.startContainer;
          if (container === rng.endContainer) {
            if (isInlineBlock(container.childNodes[offset2])) {
              return;
            }
          }
          if (isElement$5(container)) {
            var nodes = container.childNodes;
            var walker = void 0;
            if (offset2 < nodes.length) {
              container = nodes[offset2];
              walker = new DomTreeWalker(container, dom2.getParent(container, dom2.isBlock));
            } else {
              container = nodes[nodes.length - 1];
              walker = new DomTreeWalker(container, dom2.getParent(container, dom2.isBlock));
              walker.next(true);
            }
            for (var node = walker.current(); node; node = walker.next()) {
              if (isText$7(node) && !isWhiteSpaceNode$1(node)) {
                rng.setStart(node, 0);
                selection.setRng(rng);
                return;
              }
            }
          }
        };
        var getNonWhiteSpaceSibling = function(node, next, inc) {
          if (node) {
            var nextName = next ? "nextSibling" : "previousSibling";
            for (node = inc ? node : node[nextName]; node; node = node[nextName]) {
              if (isElement$5(node) || !isWhiteSpaceNode$1(node)) {
                return node;
              }
            }
          }
        };
        var isTextBlock$1 = function(editor, name2) {
          if (isNode(name2)) {
            name2 = name2.nodeName;
          }
          return !!editor.schema.getTextBlockElements()[name2.toLowerCase()];
        };
        var isValid2 = function(ed, parent2, child2) {
          return ed.schema.isValidChild(parent2, child2);
        };
        var isWhiteSpaceNode$1 = function(node, allowSpaces) {
          if (allowSpaces === void 0) {
            allowSpaces = false;
          }
          if (isNonNullable(node) && isText$7(node)) {
            var data2 = allowSpaces ? node.data.replace(/ /g, "\xA0") : node.data;
            return isWhitespaceText(data2);
          } else {
            return false;
          }
        };
        var isEmptyTextNode$1 = function(node) {
          return isNonNullable(node) && isText$7(node) && node.length === 0;
        };
        var replaceVars = function(value2, vars) {
          if (isFunction2(value2)) {
            value2 = value2(vars);
          } else if (isNonNullable(vars)) {
            value2 = value2.replace(/%(\w+)/g, function(str, name2) {
              return vars[name2] || str;
            });
          }
          return value2;
        };
        var isEq$5 = function(str1, str2) {
          str1 = str1 || "";
          str2 = str2 || "";
          str1 = "" + (str1.nodeName || str1);
          str2 = "" + (str2.nodeName || str2);
          return str1.toLowerCase() === str2.toLowerCase();
        };
        var normalizeStyleValue = function(dom2, value2, name2) {
          if (name2 === "color" || name2 === "backgroundColor") {
            value2 = dom2.toHex(value2);
          }
          if (name2 === "fontWeight" && value2 === 700) {
            value2 = "bold";
          }
          if (name2 === "fontFamily") {
            value2 = value2.replace(/[\'\"]/g, "").replace(/,\s+/g, ",");
          }
          return "" + value2;
        };
        var getStyle2 = function(dom2, node, name2) {
          return normalizeStyleValue(dom2, dom2.getStyle(node, name2), name2);
        };
        var getTextDecoration = function(dom2, node) {
          var decoration;
          dom2.getParent(node, function(n2) {
            decoration = dom2.getStyle(n2, "text-decoration");
            return decoration && decoration !== "none";
          });
          return decoration;
        };
        var getParents$2 = function(dom2, node, selector) {
          return dom2.getParents(node, selector, dom2.getRoot());
        };
        var isVariableFormatName = function(editor, formatName) {
          var hasVariableValues = function(format3) {
            var isVariableValue = function(val) {
              return val.length > 1 && val.charAt(0) === "%";
            };
            return exists([
              "styles",
              "attributes"
            ], function(key) {
              return get$9(format3, key).exists(function(field) {
                var fieldValues = isArray$1(field) ? field : values(field);
                return exists(fieldValues, isVariableValue);
              });
            });
          };
          return exists(editor.formatter.get(formatName), hasVariableValues);
        };
        var areSimilarFormats = function(editor, formatName, otherFormatName) {
          var validKeys = [
            "inline",
            "block",
            "selector",
            "attributes",
            "styles",
            "classes"
          ];
          var filterObj = function(format3) {
            return filter$3(format3, function(_2, key) {
              return exists(validKeys, function(validKey) {
                return validKey === key;
              });
            });
          };
          return exists(editor.formatter.get(formatName), function(fmt1) {
            var filteredFmt1 = filterObj(fmt1);
            return exists(editor.formatter.get(otherFormatName), function(fmt2) {
              var filteredFmt2 = filterObj(fmt2);
              return equal$1(filteredFmt1, filteredFmt2);
            });
          });
        };
        var isBlockFormat = function(format3) {
          return hasNonNullableKey(format3, "block");
        };
        var isSelectorFormat = function(format3) {
          return hasNonNullableKey(format3, "selector");
        };
        var isInlineFormat = function(format3) {
          return hasNonNullableKey(format3, "inline");
        };
        var isMixedFormat = function(format3) {
          return isSelectorFormat(format3) && isInlineFormat(format3) && is$1(get$9(format3, "mixed"), true);
        };
        var shouldExpandToSelector = function(format3) {
          return isSelectorFormat(format3) && format3.expand !== false && !isInlineFormat(format3);
        };
        var isBookmarkNode = isBookmarkNode$1;
        var getParents$1 = getParents$2;
        var isWhiteSpaceNode = isWhiteSpaceNode$1;
        var isTextBlock = isTextBlock$1;
        var isBogusBr = function(node) {
          return isBr$5(node) && node.getAttribute("data-mce-bogus") && !node.nextSibling;
        };
        var findParentContentEditable = function(dom2, node) {
          var parent2 = node;
          while (parent2) {
            if (isElement$5(parent2) && dom2.getContentEditable(parent2)) {
              return dom2.getContentEditable(parent2) === "false" ? parent2 : node;
            }
            parent2 = parent2.parentNode;
          }
          return node;
        };
        var walkText = function(start5, node, offset2, predicate) {
          var str = node.data;
          for (var i2 = offset2; start5 ? i2 >= 0 : i2 < str.length; start5 ? i2-- : i2++) {
            if (predicate(str.charAt(i2))) {
              return start5 ? i2 + 1 : i2;
            }
          }
          return -1;
        };
        var findSpace = function(start5, node, offset2) {
          return walkText(start5, node, offset2, function(c2) {
            return isNbsp(c2) || isWhiteSpace(c2);
          });
        };
        var findContent = function(start5, node, offset2) {
          return walkText(start5, node, offset2, isContent);
        };
        var findWordEndPoint = function(dom2, body, container, offset2, start5, includeTrailingSpaces) {
          var lastTextNode;
          var rootNode = dom2.getParent(container, dom2.isBlock) || body;
          var walk3 = function(container2, offset3, pred) {
            var textSeeker = TextSeeker(dom2);
            var walker = start5 ? textSeeker.backwards : textSeeker.forwards;
            return Optional.from(walker(container2, offset3, function(text, textOffset) {
              if (isBookmarkNode(text.parentNode)) {
                return -1;
              } else {
                lastTextNode = text;
                return pred(start5, text, textOffset);
              }
            }, rootNode));
          };
          var spaceResult = walk3(container, offset2, findSpace);
          return spaceResult.bind(function(result) {
            return includeTrailingSpaces ? walk3(result.container, result.offset + (start5 ? -1 : 0), findContent) : Optional.some(result);
          }).orThunk(function() {
            return lastTextNode ? Optional.some({
              container: lastTextNode,
              offset: start5 ? 0 : lastTextNode.length
            }) : Optional.none();
          });
        };
        var findSelectorEndPoint = function(dom2, formatList, rng, container, siblingName) {
          if (isText$7(container) && isEmpty$3(container.data) && container[siblingName]) {
            container = container[siblingName];
          }
          var parents2 = getParents$1(dom2, container);
          for (var i2 = 0; i2 < parents2.length; i2++) {
            for (var y2 = 0; y2 < formatList.length; y2++) {
              var curFormat = formatList[y2];
              if (isNonNullable(curFormat.collapsed) && curFormat.collapsed !== rng.collapsed) {
                continue;
              }
              if (isSelectorFormat(curFormat) && dom2.is(parents2[i2], curFormat.selector)) {
                return parents2[i2];
              }
            }
          }
          return container;
        };
        var findBlockEndPoint = function(editor, formatList, container, siblingName) {
          var node = container;
          var dom2 = editor.dom;
          var root = dom2.getRoot();
          var format3 = formatList[0];
          if (isBlockFormat(format3)) {
            node = format3.wrapper ? null : dom2.getParent(container, format3.block, root);
          }
          if (!node) {
            var scopeRoot = dom2.getParent(container, "LI,TD,TH");
            node = dom2.getParent(isText$7(container) ? container.parentNode : container, function(node2) {
              return node2 !== root && isTextBlock(editor, node2);
            }, scopeRoot);
          }
          if (node && isBlockFormat(format3) && format3.wrapper) {
            node = getParents$1(dom2, node, "ul,ol").reverse()[0] || node;
          }
          if (!node) {
            node = container;
            while (node[siblingName] && !dom2.isBlock(node[siblingName])) {
              node = node[siblingName];
              if (isEq$5(node, "br")) {
                break;
              }
            }
          }
          return node || container;
        };
        var isAtBlockBoundary$1 = function(dom2, root, container, siblingName) {
          var parent2 = container.parentNode;
          if (isNonNullable(container[siblingName])) {
            return false;
          } else if (parent2 === root || isNullable(parent2) || dom2.isBlock(parent2)) {
            return true;
          } else {
            return isAtBlockBoundary$1(dom2, root, parent2, siblingName);
          }
        };
        var findParentContainer = function(dom2, formatList, container, offset2, start5) {
          var parent2 = container;
          var siblingName = start5 ? "previousSibling" : "nextSibling";
          var root = dom2.getRoot();
          if (isText$7(container) && !isWhiteSpaceNode(container)) {
            if (start5 ? offset2 > 0 : offset2 < container.data.length) {
              return container;
            }
          }
          while (true) {
            if (!formatList[0].block_expand && dom2.isBlock(parent2)) {
              return parent2;
            }
            for (var sibling2 = parent2[siblingName]; sibling2; sibling2 = sibling2[siblingName]) {
              var allowSpaces = isText$7(sibling2) && !isAtBlockBoundary$1(dom2, root, sibling2, siblingName);
              if (!isBookmarkNode(sibling2) && !isBogusBr(sibling2) && !isWhiteSpaceNode(sibling2, allowSpaces)) {
                return parent2;
              }
            }
            if (parent2 === root || parent2.parentNode === root) {
              container = parent2;
              break;
            }
            parent2 = parent2.parentNode;
          }
          return container;
        };
        var isSelfOrParentBookmark = function(container) {
          return isBookmarkNode(container.parentNode) || isBookmarkNode(container);
        };
        var expandRng = function(editor, rng, formatList, includeTrailingSpace) {
          if (includeTrailingSpace === void 0) {
            includeTrailingSpace = false;
          }
          var startContainer = rng.startContainer, startOffset = rng.startOffset, endContainer = rng.endContainer, endOffset = rng.endOffset;
          var dom2 = editor.dom;
          var format3 = formatList[0];
          if (isElement$5(startContainer) && startContainer.hasChildNodes()) {
            startContainer = getNode$1(startContainer, startOffset);
            if (isText$7(startContainer)) {
              startOffset = 0;
            }
          }
          if (isElement$5(endContainer) && endContainer.hasChildNodes()) {
            endContainer = getNode$1(endContainer, rng.collapsed ? endOffset : endOffset - 1);
            if (isText$7(endContainer)) {
              endOffset = endContainer.nodeValue.length;
            }
          }
          startContainer = findParentContentEditable(dom2, startContainer);
          endContainer = findParentContentEditable(dom2, endContainer);
          if (isSelfOrParentBookmark(startContainer)) {
            startContainer = isBookmarkNode(startContainer) ? startContainer : startContainer.parentNode;
            if (rng.collapsed) {
              startContainer = startContainer.previousSibling || startContainer;
            } else {
              startContainer = startContainer.nextSibling || startContainer;
            }
            if (isText$7(startContainer)) {
              startOffset = rng.collapsed ? startContainer.length : 0;
            }
          }
          if (isSelfOrParentBookmark(endContainer)) {
            endContainer = isBookmarkNode(endContainer) ? endContainer : endContainer.parentNode;
            if (rng.collapsed) {
              endContainer = endContainer.nextSibling || endContainer;
            } else {
              endContainer = endContainer.previousSibling || endContainer;
            }
            if (isText$7(endContainer)) {
              endOffset = rng.collapsed ? 0 : endContainer.length;
            }
          }
          if (rng.collapsed) {
            var startPoint = findWordEndPoint(dom2, editor.getBody(), startContainer, startOffset, true, includeTrailingSpace);
            startPoint.each(function(_a) {
              var container = _a.container, offset2 = _a.offset;
              startContainer = container;
              startOffset = offset2;
            });
            var endPoint = findWordEndPoint(dom2, editor.getBody(), endContainer, endOffset, false, includeTrailingSpace);
            endPoint.each(function(_a) {
              var container = _a.container, offset2 = _a.offset;
              endContainer = container;
              endOffset = offset2;
            });
          }
          if (isInlineFormat(format3) || format3.block_expand) {
            if (!isInlineFormat(format3) || (!isText$7(startContainer) || startOffset === 0)) {
              startContainer = findParentContainer(dom2, formatList, startContainer, startOffset, true);
            }
            if (!isInlineFormat(format3) || (!isText$7(endContainer) || endOffset === endContainer.nodeValue.length)) {
              endContainer = findParentContainer(dom2, formatList, endContainer, endOffset, false);
            }
          }
          if (shouldExpandToSelector(format3)) {
            startContainer = findSelectorEndPoint(dom2, formatList, rng, startContainer, "previousSibling");
            endContainer = findSelectorEndPoint(dom2, formatList, rng, endContainer, "nextSibling");
          }
          if (isBlockFormat(format3) || isSelectorFormat(format3)) {
            startContainer = findBlockEndPoint(editor, formatList, startContainer, "previousSibling");
            endContainer = findBlockEndPoint(editor, formatList, endContainer, "nextSibling");
            if (isBlockFormat(format3)) {
              if (!dom2.isBlock(startContainer)) {
                startContainer = findParentContainer(dom2, formatList, startContainer, startOffset, true);
              }
              if (!dom2.isBlock(endContainer)) {
                endContainer = findParentContainer(dom2, formatList, endContainer, endOffset, false);
              }
            }
          }
          if (isElement$5(startContainer)) {
            startOffset = dom2.nodeIndex(startContainer);
            startContainer = startContainer.parentNode;
          }
          if (isElement$5(endContainer)) {
            endOffset = dom2.nodeIndex(endContainer) + 1;
            endContainer = endContainer.parentNode;
          }
          return {
            startContainer,
            startOffset,
            endContainer,
            endOffset
          };
        };
        var walk$2 = function(dom2, rng, callback2) {
          var startOffset = rng.startOffset;
          var startContainer = getNode$1(rng.startContainer, startOffset);
          var endOffset = rng.endOffset;
          var endContainer = getNode$1(rng.endContainer, endOffset - 1);
          var exclude = function(nodes) {
            var firstNode = nodes[0];
            if (isText$7(firstNode) && firstNode === startContainer && startOffset >= firstNode.data.length) {
              nodes.splice(0, 1);
            }
            var lastNode = nodes[nodes.length - 1];
            if (endOffset === 0 && nodes.length > 0 && lastNode === endContainer && isText$7(lastNode)) {
              nodes.splice(nodes.length - 1, 1);
            }
            return nodes;
          };
          var collectSiblings = function(node, name2, endNode) {
            var siblings3 = [];
            for (; node && node !== endNode; node = node[name2]) {
              siblings3.push(node);
            }
            return siblings3;
          };
          var findEndPoint = function(node, root) {
            return dom2.getParent(node, function(node2) {
              return node2.parentNode === root;
            }, root);
          };
          var walkBoundary = function(startNode, endNode, next) {
            var siblingName = next ? "nextSibling" : "previousSibling";
            for (var node = startNode, parent_1 = node.parentNode; node && node !== endNode; node = parent_1) {
              parent_1 = node.parentNode;
              var siblings_1 = collectSiblings(node === startNode ? node : node[siblingName], siblingName);
              if (siblings_1.length) {
                if (!next) {
                  siblings_1.reverse();
                }
                callback2(exclude(siblings_1));
              }
            }
          };
          if (startContainer === endContainer) {
            return callback2(exclude([startContainer]));
          }
          var ancestor2 = dom2.findCommonAncestor(startContainer, endContainer);
          if (dom2.isChildOf(startContainer, endContainer)) {
            return walkBoundary(startContainer, ancestor2, true);
          }
          if (dom2.isChildOf(endContainer, startContainer)) {
            return walkBoundary(endContainer, ancestor2);
          }
          var startPoint = findEndPoint(startContainer, ancestor2) || startContainer;
          var endPoint = findEndPoint(endContainer, ancestor2) || endContainer;
          walkBoundary(startContainer, startPoint, true);
          var siblings2 = collectSiblings(startPoint === startContainer ? startPoint : startPoint.nextSibling, "nextSibling", endPoint === endContainer ? endPoint.nextSibling : endPoint);
          if (siblings2.length) {
            callback2(exclude(siblings2));
          }
          walkBoundary(endContainer, endPoint);
        };
        var getRanges = function(selection) {
          var ranges = [];
          if (selection) {
            for (var i2 = 0; i2 < selection.rangeCount; i2++) {
              ranges.push(selection.getRangeAt(i2));
            }
          }
          return ranges;
        };
        var getSelectedNodes = function(ranges) {
          return bind(ranges, function(range2) {
            var node = getSelectedNode(range2);
            return node ? [SugarElement.fromDom(node)] : [];
          });
        };
        var hasMultipleRanges = function(selection) {
          return getRanges(selection).length > 1;
        };
        var getCellsFromRanges = function(ranges) {
          return filter$4(getSelectedNodes(ranges), isTableCell$4);
        };
        var getCellsFromElement = function(elm) {
          return descendants(elm, "td[data-mce-selected],th[data-mce-selected]");
        };
        var getCellsFromElementOrRanges = function(ranges, element) {
          var selectedCells = getCellsFromElement(element);
          return selectedCells.length > 0 ? selectedCells : getCellsFromRanges(ranges);
        };
        var getCellsFromEditor = function(editor) {
          return getCellsFromElementOrRanges(getRanges(editor.selection.getSel()), SugarElement.fromDom(editor.getBody()));
        };
        var getClosestTable = function(cell, isRoot) {
          return ancestor$2(cell, "table", isRoot);
        };
        var getStartNode = function(rng) {
          var sc = rng.startContainer, so = rng.startOffset;
          if (isText$7(sc)) {
            return so === 0 ? Optional.some(SugarElement.fromDom(sc)) : Optional.none();
          } else {
            return Optional.from(sc.childNodes[so]).map(SugarElement.fromDom);
          }
        };
        var getEndNode = function(rng) {
          var ec = rng.endContainer, eo = rng.endOffset;
          if (isText$7(ec)) {
            return eo === ec.data.length ? Optional.some(SugarElement.fromDom(ec)) : Optional.none();
          } else {
            return Optional.from(ec.childNodes[eo - 1]).map(SugarElement.fromDom);
          }
        };
        var getFirstChildren = function(node) {
          return firstChild(node).fold(constant([node]), function(child2) {
            return [node].concat(getFirstChildren(child2));
          });
        };
        var getLastChildren$1 = function(node) {
          return lastChild(node).fold(constant([node]), function(child2) {
            if (name(child2) === "br") {
              return prevSibling(child2).map(function(sibling2) {
                return [node].concat(getLastChildren$1(sibling2));
              }).getOr([]);
            } else {
              return [node].concat(getLastChildren$1(child2));
            }
          });
        };
        var hasAllContentsSelected = function(elm, rng) {
          return lift2(getStartNode(rng), getEndNode(rng), function(startNode, endNode) {
            var start5 = find$3(getFirstChildren(elm), curry(eq2, startNode));
            var end3 = find$3(getLastChildren$1(elm), curry(eq2, endNode));
            return start5.isSome() && end3.isSome();
          }).getOr(false);
        };
        var moveEndPoint = function(dom2, rng, node, start5) {
          var root = node, walker = new DomTreeWalker(node, root);
          var moveCaretBeforeOnEnterElementsMap = filter$3(dom2.schema.getMoveCaretBeforeOnEnterElements(), function(_2, name2) {
            return !contains$3([
              "td",
              "th",
              "table"
            ], name2.toLowerCase());
          });
          do {
            if (isText$7(node) && Tools.trim(node.nodeValue).length !== 0) {
              if (start5) {
                rng.setStart(node, 0);
              } else {
                rng.setEnd(node, node.nodeValue.length);
              }
              return;
            }
            if (moveCaretBeforeOnEnterElementsMap[node.nodeName]) {
              if (start5) {
                rng.setStartBefore(node);
              } else {
                if (node.nodeName === "BR") {
                  rng.setEndBefore(node);
                } else {
                  rng.setEndAfter(node);
                }
              }
              return;
            }
          } while (node = start5 ? walker.next() : walker.prev());
          if (root.nodeName === "BODY") {
            if (start5) {
              rng.setStart(root, 0);
            } else {
              rng.setEnd(root, root.childNodes.length);
            }
          }
        };
        var hasAnyRanges = function(editor) {
          var sel = editor.selection.getSel();
          return sel && sel.rangeCount > 0;
        };
        var runOnRanges = function(editor, executor) {
          var fakeSelectionNodes = getCellsFromEditor(editor);
          if (fakeSelectionNodes.length > 0) {
            each$k(fakeSelectionNodes, function(elem) {
              var node = elem.dom;
              var fakeNodeRng = editor.dom.createRng();
              fakeNodeRng.setStartBefore(node);
              fakeNodeRng.setEndAfter(node);
              executor(fakeNodeRng, true);
            });
          } else {
            executor(editor.selection.getRng(), false);
          }
        };
        var preserve = function(selection, fillBookmark, executor) {
          var bookmark = getPersistentBookmark(selection, fillBookmark);
          executor(bookmark);
          selection.moveToBookmark(bookmark);
        };
        var NodeValue = function(is2, name2) {
          var get2 = function(element) {
            if (!is2(element)) {
              throw new Error("Can only get " + name2 + " value of a " + name2 + " node");
            }
            return getOption(element).getOr("");
          };
          var getOption = function(element) {
            return is2(element) ? Optional.from(element.dom.nodeValue) : Optional.none();
          };
          var set3 = function(element, value2) {
            if (!is2(element)) {
              throw new Error("Can only set raw " + name2 + " value of a " + name2 + " node");
            }
            element.dom.nodeValue = value2;
          };
          return {
            get: get2,
            getOption,
            set: set3
          };
        };
        var api$1 = NodeValue(isText$8, "text");
        var get$2 = function(element) {
          return api$1.get(element);
        };
        var isZeroWidth = function(elem) {
          return isText$8(elem) && get$2(elem) === ZWSP$1;
        };
        var context = function(editor, elem, wrapName, nodeName) {
          return parent(elem).fold(function() {
            return "skipping";
          }, function(parent2) {
            if (nodeName === "br" || isZeroWidth(elem)) {
              return "valid";
            } else if (isAnnotation(elem)) {
              return "existing";
            } else if (isCaretNode(elem.dom)) {
              return "caret";
            } else if (!isValid2(editor, wrapName, nodeName) || !isValid2(editor, name(parent2), wrapName)) {
              return "invalid-child";
            } else {
              return "valid";
            }
          });
        };
        var applyWordGrab = function(editor, rng) {
          var r3 = expandRng(editor, rng, [{ inline: "span" }]);
          rng.setStart(r3.startContainer, r3.startOffset);
          rng.setEnd(r3.endContainer, r3.endOffset);
          editor.selection.setRng(rng);
        };
        var makeAnnotation = function(eDoc, _a, annotationName, decorate) {
          var _b = _a.uid, uid2 = _b === void 0 ? generate("mce-annotation") : _b, data2 = __rest(_a, ["uid"]);
          var master = SugarElement.fromTag("span", eDoc);
          add$1(master, annotation());
          set$1(master, "" + dataAnnotationId(), uid2);
          set$1(master, "" + dataAnnotation(), annotationName);
          var _c = decorate(uid2, data2), _d = _c.attributes, attributes2 = _d === void 0 ? {} : _d, _e2 = _c.classes, classes = _e2 === void 0 ? [] : _e2;
          setAll$1(master, attributes2);
          add3(master, classes);
          return master;
        };
        var annotate = function(editor, rng, annotationName, decorate, data2) {
          var newWrappers = [];
          var master = makeAnnotation(editor.getDoc(), data2, annotationName, decorate);
          var wrapper = value();
          var finishWrapper = function() {
            wrapper.clear();
          };
          var getOrOpenWrapper = function() {
            return wrapper.get().getOrThunk(function() {
              var nu2 = shallow(master);
              newWrappers.push(nu2);
              wrapper.set(nu2);
              return nu2;
            });
          };
          var processElements = function(elems) {
            each$k(elems, processElement);
          };
          var processElement = function(elem) {
            var ctx = context(editor, elem, "span", name(elem));
            switch (ctx) {
              case "invalid-child": {
                finishWrapper();
                var children$1 = children(elem);
                processElements(children$1);
                finishWrapper();
                break;
              }
              case "valid": {
                var w2 = getOrOpenWrapper();
                wrap$3(elem, w2);
                break;
              }
            }
          };
          var processNodes = function(nodes) {
            var elems = map$3(nodes, SugarElement.fromDom);
            processElements(elems);
          };
          walk$2(editor.dom, rng, function(nodes) {
            finishWrapper();
            processNodes(nodes);
          });
          return newWrappers;
        };
        var annotateWithBookmark = function(editor, name2, settings, data2) {
          editor.undoManager.transact(function() {
            var selection = editor.selection;
            var initialRng = selection.getRng();
            var hasFakeSelection = getCellsFromEditor(editor).length > 0;
            if (initialRng.collapsed && !hasFakeSelection) {
              applyWordGrab(editor, initialRng);
            }
            if (selection.getRng().collapsed && !hasFakeSelection) {
              var wrapper = makeAnnotation(editor.getDoc(), data2, name2, settings.decorate);
              set2(wrapper, nbsp);
              selection.getRng().insertNode(wrapper.dom);
              selection.select(wrapper.dom);
            } else {
              preserve(selection, false, function() {
                runOnRanges(editor, function(selectionRng) {
                  annotate(editor, selectionRng, name2, settings.decorate, data2);
                });
              });
            }
          });
        };
        var Annotator = function(editor) {
          var registry3 = create$7();
          setup$m(editor, registry3);
          var changes = setup$n(editor);
          return {
            register: function(name2, settings) {
              registry3.register(name2, settings);
            },
            annotate: function(name2, data2) {
              registry3.lookup(name2).each(function(settings) {
                annotateWithBookmark(editor, name2, settings, data2);
              });
            },
            annotationChanged: function(name2, callback2) {
              changes.addListener(name2, callback2);
            },
            remove: function(name2) {
              identify(editor, Optional.some(name2)).each(function(_a) {
                var elements2 = _a.elements;
                each$k(elements2, unwrap);
              });
            },
            getAll: function(name2) {
              var directory = findAll(editor, name2);
              return map$2(directory, function(elems) {
                return map$3(elems, function(elem) {
                  return elem.dom;
                });
              });
            }
          };
        };
        var BookmarkManager = function(selection) {
          return {
            getBookmark: curry(getBookmark$1, selection),
            moveToBookmark: curry(moveToBookmark, selection)
          };
        };
        BookmarkManager.isBookmarkNode = isBookmarkNode$1;
        var getContentEditableRoot$1 = function(root, node) {
          while (node && node !== root) {
            if (isContentEditableTrue$4(node) || isContentEditableFalse$b(node)) {
              return node;
            }
            node = node.parentNode;
          }
          return null;
        };
        var isXYWithinRange = function(clientX, clientY, range2) {
          if (range2.collapsed) {
            return false;
          }
          if (Env.browser.isIE() && range2.startOffset === range2.endOffset - 1 && range2.startContainer === range2.endContainer) {
            var elm = range2.startContainer.childNodes[range2.startOffset];
            if (isElement$5(elm)) {
              return exists(elm.getClientRects(), function(rect) {
                return containsXY(rect, clientX, clientY);
              });
            }
          }
          return exists(range2.getClientRects(), function(rect) {
            return containsXY(rect, clientX, clientY);
          });
        };
        var firePreProcess = function(editor, args) {
          return editor.fire("PreProcess", args);
        };
        var firePostProcess = function(editor, args) {
          return editor.fire("PostProcess", args);
        };
        var fireRemove = function(editor) {
          return editor.fire("remove");
        };
        var fireDetach = function(editor) {
          return editor.fire("detach");
        };
        var fireSwitchMode = function(editor, mode) {
          return editor.fire("SwitchMode", { mode });
        };
        var fireObjectResizeStart = function(editor, target, width, height, origin) {
          editor.fire("ObjectResizeStart", {
            target,
            width,
            height,
            origin
          });
        };
        var fireObjectResized = function(editor, target, width, height, origin) {
          editor.fire("ObjectResized", {
            target,
            width,
            height,
            origin
          });
        };
        var firePreInit = function(editor) {
          return editor.fire("PreInit");
        };
        var firePostRender = function(editor) {
          return editor.fire("PostRender");
        };
        var fireInit = function(editor) {
          return editor.fire("Init");
        };
        var firePlaceholderToggle = function(editor, state) {
          return editor.fire("PlaceholderToggle", { state });
        };
        var fireError = function(editor, errorType, error4) {
          return editor.fire(errorType, error4);
        };
        var fireFormatApply = function(editor, format3, node, vars) {
          return editor.fire("FormatApply", {
            format: format3,
            node,
            vars
          });
        };
        var fireFormatRemove = function(editor, format3, node, vars) {
          return editor.fire("FormatRemove", {
            format: format3,
            node,
            vars
          });
        };
        var VK = {
          BACKSPACE: 8,
          DELETE: 46,
          DOWN: 40,
          ENTER: 13,
          ESC: 27,
          LEFT: 37,
          RIGHT: 39,
          SPACEBAR: 32,
          TAB: 9,
          UP: 38,
          PAGE_UP: 33,
          PAGE_DOWN: 34,
          END: 35,
          HOME: 36,
          modifierPressed: function(e2) {
            return e2.shiftKey || e2.ctrlKey || e2.altKey || VK.metaKeyPressed(e2);
          },
          metaKeyPressed: function(e2) {
            return Env.mac ? e2.metaKey : e2.ctrlKey && !e2.altKey;
          }
        };
        var isContentEditableFalse$5 = isContentEditableFalse$b;
        var ControlSelection = function(selection, editor) {
          var elementSelectionAttr = "data-mce-selected";
          var dom2 = editor.dom, each3 = Tools.each;
          var selectedElm, selectedElmGhost, resizeHelper, selectedHandle, resizeBackdrop;
          var startX, startY, selectedElmX, selectedElmY, startW, startH, ratio, resizeStarted;
          var width, height;
          var editableDoc = editor.getDoc(), rootDocument = document;
          var abs = Math.abs, round4 = Math.round, rootElement = editor.getBody();
          var startScrollWidth, startScrollHeight;
          var resizeHandles = {
            nw: [
              0,
              0,
              -1,
              -1
            ],
            ne: [
              1,
              0,
              1,
              -1
            ],
            se: [
              1,
              1,
              1,
              1
            ],
            sw: [
              0,
              1,
              -1,
              1
            ]
          };
          var isImage = function(elm) {
            return elm && (elm.nodeName === "IMG" || editor.dom.is(elm, "figure.image"));
          };
          var isMedia2 = function(elm) {
            return isMedia$2(elm) || dom2.hasClass(elm, "mce-preview-object");
          };
          var isEventOnImageOutsideRange = function(evt, range2) {
            if (evt.type === "longpress" || evt.type.indexOf("touch") === 0) {
              var touch = evt.touches[0];
              return isImage(evt.target) && !isXYWithinRange(touch.clientX, touch.clientY, range2);
            } else {
              return isImage(evt.target) && !isXYWithinRange(evt.clientX, evt.clientY, range2);
            }
          };
          var contextMenuSelectImage = function(evt) {
            var target = evt.target;
            if (isEventOnImageOutsideRange(evt, editor.selection.getRng()) && !evt.isDefaultPrevented()) {
              editor.selection.select(target);
            }
          };
          var getResizeTargets = function(elm) {
            if (dom2.is(elm, "figure.image")) {
              return [elm.querySelector("img")];
            } else if (dom2.hasClass(elm, "mce-preview-object") && isNonNullable(elm.firstElementChild)) {
              return [
                elm,
                elm.firstElementChild
              ];
            } else {
              return [elm];
            }
          };
          var isResizable = function(elm) {
            var selector = getObjectResizing(editor);
            if (!selector) {
              return false;
            }
            if (elm.getAttribute("data-mce-resize") === "false") {
              return false;
            }
            if (elm === editor.getBody()) {
              return false;
            }
            if (dom2.hasClass(elm, "mce-preview-object")) {
              return is$2(SugarElement.fromDom(elm.firstElementChild), selector);
            } else {
              return is$2(SugarElement.fromDom(elm), selector);
            }
          };
          var createGhostElement = function(elm) {
            if (isMedia2(elm)) {
              return dom2.create("img", { src: Env.transparentSrc });
            } else {
              return elm.cloneNode(true);
            }
          };
          var setSizeProp = function(element, name2, value2) {
            if (isNonNullable(value2)) {
              var targets = getResizeTargets(element);
              each$k(targets, function(target) {
                if (target.style[name2] || !editor.schema.isValid(target.nodeName.toLowerCase(), name2)) {
                  dom2.setStyle(target, name2, value2);
                } else {
                  dom2.setAttrib(target, name2, "" + value2);
                }
              });
            }
          };
          var setGhostElmSize = function(ghostElm, width2, height2) {
            setSizeProp(ghostElm, "width", width2);
            setSizeProp(ghostElm, "height", height2);
          };
          var resizeGhostElement = function(e2) {
            var deltaX, deltaY, proportional;
            var resizeHelperX, resizeHelperY;
            deltaX = e2.screenX - startX;
            deltaY = e2.screenY - startY;
            width = deltaX * selectedHandle[2] + startW;
            height = deltaY * selectedHandle[3] + startH;
            width = width < 5 ? 5 : width;
            height = height < 5 ? 5 : height;
            if ((isImage(selectedElm) || isMedia2(selectedElm)) && getResizeImgProportional(editor) !== false) {
              proportional = !VK.modifierPressed(e2);
            } else {
              proportional = VK.modifierPressed(e2);
            }
            if (proportional) {
              if (abs(deltaX) > abs(deltaY)) {
                height = round4(width * ratio);
                width = round4(height / ratio);
              } else {
                width = round4(height / ratio);
                height = round4(width * ratio);
              }
            }
            setGhostElmSize(selectedElmGhost, width, height);
            resizeHelperX = selectedHandle.startPos.x + deltaX;
            resizeHelperY = selectedHandle.startPos.y + deltaY;
            resizeHelperX = resizeHelperX > 0 ? resizeHelperX : 0;
            resizeHelperY = resizeHelperY > 0 ? resizeHelperY : 0;
            dom2.setStyles(resizeHelper, {
              left: resizeHelperX,
              top: resizeHelperY,
              display: "block"
            });
            resizeHelper.innerHTML = width + " &times; " + height;
            if (selectedHandle[2] < 0 && selectedElmGhost.clientWidth <= width) {
              dom2.setStyle(selectedElmGhost, "left", selectedElmX + (startW - width));
            }
            if (selectedHandle[3] < 0 && selectedElmGhost.clientHeight <= height) {
              dom2.setStyle(selectedElmGhost, "top", selectedElmY + (startH - height));
            }
            deltaX = rootElement.scrollWidth - startScrollWidth;
            deltaY = rootElement.scrollHeight - startScrollHeight;
            if (deltaX + deltaY !== 0) {
              dom2.setStyles(resizeHelper, {
                left: resizeHelperX - deltaX,
                top: resizeHelperY - deltaY
              });
            }
            if (!resizeStarted) {
              fireObjectResizeStart(editor, selectedElm, startW, startH, "corner-" + selectedHandle.name);
              resizeStarted = true;
            }
          };
          var endGhostResize = function() {
            var wasResizeStarted = resizeStarted;
            resizeStarted = false;
            if (wasResizeStarted) {
              setSizeProp(selectedElm, "width", width);
              setSizeProp(selectedElm, "height", height);
            }
            dom2.unbind(editableDoc, "mousemove", resizeGhostElement);
            dom2.unbind(editableDoc, "mouseup", endGhostResize);
            if (rootDocument !== editableDoc) {
              dom2.unbind(rootDocument, "mousemove", resizeGhostElement);
              dom2.unbind(rootDocument, "mouseup", endGhostResize);
            }
            dom2.remove(selectedElmGhost);
            dom2.remove(resizeHelper);
            dom2.remove(resizeBackdrop);
            showResizeRect(selectedElm);
            if (wasResizeStarted) {
              fireObjectResized(editor, selectedElm, width, height, "corner-" + selectedHandle.name);
              dom2.setAttrib(selectedElm, "style", dom2.getAttrib(selectedElm, "style"));
            }
            editor.nodeChanged();
          };
          var showResizeRect = function(targetElm) {
            unbindResizeHandleEvents();
            var position = dom2.getPos(targetElm, rootElement);
            var selectedElmX2 = position.x;
            var selectedElmY2 = position.y;
            var rect = targetElm.getBoundingClientRect();
            var targetWidth = rect.width || rect.right - rect.left;
            var targetHeight = rect.height || rect.bottom - rect.top;
            if (selectedElm !== targetElm) {
              hideResizeRect();
              selectedElm = targetElm;
              width = height = 0;
            }
            var e2 = editor.fire("ObjectSelected", { target: targetElm });
            var selectedValue = dom2.getAttrib(selectedElm, elementSelectionAttr, "1");
            if (isResizable(targetElm) && !e2.isDefaultPrevented()) {
              each3(resizeHandles, function(handle2, name2) {
                var handleElm;
                var startDrag = function(e3) {
                  var target = getResizeTargets(selectedElm)[0];
                  startX = e3.screenX;
                  startY = e3.screenY;
                  startW = target.clientWidth;
                  startH = target.clientHeight;
                  ratio = startH / startW;
                  selectedHandle = handle2;
                  selectedHandle.name = name2;
                  selectedHandle.startPos = {
                    x: targetWidth * handle2[0] + selectedElmX2,
                    y: targetHeight * handle2[1] + selectedElmY2
                  };
                  startScrollWidth = rootElement.scrollWidth;
                  startScrollHeight = rootElement.scrollHeight;
                  resizeBackdrop = dom2.add(rootElement, "div", {
                    "class": "mce-resize-backdrop",
                    "data-mce-bogus": "all"
                  });
                  dom2.setStyles(resizeBackdrop, {
                    position: "fixed",
                    left: "0",
                    top: "0",
                    width: "100%",
                    height: "100%"
                  });
                  selectedElmGhost = createGhostElement(selectedElm);
                  dom2.addClass(selectedElmGhost, "mce-clonedresizable");
                  dom2.setAttrib(selectedElmGhost, "data-mce-bogus", "all");
                  selectedElmGhost.contentEditable = "false";
                  dom2.setStyles(selectedElmGhost, {
                    left: selectedElmX2,
                    top: selectedElmY2,
                    margin: 0
                  });
                  setGhostElmSize(selectedElmGhost, targetWidth, targetHeight);
                  selectedElmGhost.removeAttribute(elementSelectionAttr);
                  rootElement.appendChild(selectedElmGhost);
                  dom2.bind(editableDoc, "mousemove", resizeGhostElement);
                  dom2.bind(editableDoc, "mouseup", endGhostResize);
                  if (rootDocument !== editableDoc) {
                    dom2.bind(rootDocument, "mousemove", resizeGhostElement);
                    dom2.bind(rootDocument, "mouseup", endGhostResize);
                  }
                  resizeHelper = dom2.add(rootElement, "div", {
                    "class": "mce-resize-helper",
                    "data-mce-bogus": "all"
                  }, startW + " &times; " + startH);
                };
                handleElm = dom2.get("mceResizeHandle" + name2);
                if (handleElm) {
                  dom2.remove(handleElm);
                }
                handleElm = dom2.add(rootElement, "div", {
                  "id": "mceResizeHandle" + name2,
                  "data-mce-bogus": "all",
                  "class": "mce-resizehandle",
                  "unselectable": true,
                  "style": "cursor:" + name2 + "-resize; margin:0; padding:0"
                });
                if (Env.ie === 11) {
                  handleElm.contentEditable = false;
                }
                dom2.bind(handleElm, "mousedown", function(e3) {
                  e3.stopImmediatePropagation();
                  e3.preventDefault();
                  startDrag(e3);
                });
                handle2.elm = handleElm;
                dom2.setStyles(handleElm, {
                  left: targetWidth * handle2[0] + selectedElmX2 - handleElm.offsetWidth / 2,
                  top: targetHeight * handle2[1] + selectedElmY2 - handleElm.offsetHeight / 2
                });
              });
            } else {
              hideResizeRect();
            }
            if (!dom2.getAttrib(selectedElm, elementSelectionAttr)) {
              selectedElm.setAttribute(elementSelectionAttr, selectedValue);
            }
          };
          var hideResizeRect = function() {
            unbindResizeHandleEvents();
            if (selectedElm) {
              selectedElm.removeAttribute(elementSelectionAttr);
            }
            each$j(resizeHandles, function(value2, name2) {
              var handleElm = dom2.get("mceResizeHandle" + name2);
              if (handleElm) {
                dom2.unbind(handleElm);
                dom2.remove(handleElm);
              }
            });
          };
          var updateResizeRect = function(e2) {
            var startElm, controlElm;
            var isChildOrEqual = function(node, parent2) {
              if (node) {
                do {
                  if (node === parent2) {
                    return true;
                  }
                } while (node = node.parentNode);
              }
            };
            if (resizeStarted || editor.removed) {
              return;
            }
            each3(dom2.select("img[data-mce-selected],hr[data-mce-selected]"), function(img) {
              img.removeAttribute(elementSelectionAttr);
            });
            controlElm = e2.type === "mousedown" ? e2.target : selection.getNode();
            controlElm = dom2.$(controlElm).closest("table,img,figure.image,hr,video,span.mce-preview-object")[0];
            if (isChildOrEqual(controlElm, rootElement)) {
              disableGeckoResize();
              startElm = selection.getStart(true);
              if (isChildOrEqual(startElm, controlElm) && isChildOrEqual(selection.getEnd(true), controlElm)) {
                showResizeRect(controlElm);
                return;
              }
            }
            hideResizeRect();
          };
          var isWithinContentEditableFalse = function(elm) {
            return isContentEditableFalse$5(getContentEditableRoot$1(editor.getBody(), elm));
          };
          var unbindResizeHandleEvents = function() {
            each$j(resizeHandles, function(handle2) {
              if (handle2.elm) {
                dom2.unbind(handle2.elm);
                delete handle2.elm;
              }
            });
          };
          var disableGeckoResize = function() {
            try {
              editor.getDoc().execCommand("enableObjectResizing", false, "false");
            } catch (ex) {
            }
          };
          editor.on("init", function() {
            disableGeckoResize();
            if (Env.browser.isIE() || Env.browser.isEdge()) {
              editor.on("mousedown click", function(e2) {
                var target = e2.target, nodeName = target.nodeName;
                if (!resizeStarted && /^(TABLE|IMG|HR)$/.test(nodeName) && !isWithinContentEditableFalse(target)) {
                  if (e2.button !== 2) {
                    editor.selection.select(target, nodeName === "TABLE");
                  }
                  if (e2.type === "mousedown") {
                    editor.nodeChanged();
                  }
                }
              });
              var handleMSControlSelect_1 = function(e2) {
                var delayedSelect = function(node) {
                  Delay.setEditorTimeout(editor, function() {
                    return editor.selection.select(node);
                  });
                };
                if (isWithinContentEditableFalse(e2.target) || isMedia$2(e2.target)) {
                  e2.preventDefault();
                  delayedSelect(e2.target);
                  return;
                }
                if (/^(TABLE|IMG|HR)$/.test(e2.target.nodeName)) {
                  e2.preventDefault();
                  if (e2.target.tagName === "IMG") {
                    delayedSelect(e2.target);
                  }
                }
              };
              dom2.bind(rootElement, "mscontrolselect", handleMSControlSelect_1);
              editor.on("remove", function() {
                return dom2.unbind(rootElement, "mscontrolselect", handleMSControlSelect_1);
              });
            }
            var throttledUpdateResizeRect = Delay.throttle(function(e2) {
              if (!editor.composing) {
                updateResizeRect(e2);
              }
            });
            editor.on("nodechange ResizeEditor ResizeWindow ResizeContent drop FullscreenStateChanged", throttledUpdateResizeRect);
            editor.on("keyup compositionend", function(e2) {
              if (selectedElm && selectedElm.nodeName === "TABLE") {
                throttledUpdateResizeRect(e2);
              }
            });
            editor.on("hide blur", hideResizeRect);
            editor.on("contextmenu longpress", contextMenuSelectImage, true);
          });
          editor.on("remove", unbindResizeHandleEvents);
          var destroy2 = function() {
            selectedElm = selectedElmGhost = resizeBackdrop = null;
          };
          return {
            isResizable,
            showResizeRect,
            hideResizeRect,
            updateResizeRect,
            destroy: destroy2
          };
        };
        var hasCeProperty = function(node) {
          return isContentEditableTrue$4(node) || isContentEditableFalse$b(node);
        };
        var findParent$1 = function(node, rootNode, predicate) {
          while (node && node !== rootNode) {
            if (predicate(node)) {
              return node;
            }
            node = node.parentNode;
          }
          return null;
        };
        var findClosestIeRange = function(clientX, clientY, doc2) {
          var rects;
          var element = doc2.elementFromPoint(clientX, clientY);
          var rng = doc2.body.createTextRange();
          if (!element || element.tagName === "HTML") {
            element = doc2.body;
          }
          rng.moveToElementText(element);
          rects = Tools.toArray(rng.getClientRects());
          rects = rects.sort(function(a2, b2) {
            a2 = Math.abs(Math.max(a2.top - clientY, a2.bottom - clientY));
            b2 = Math.abs(Math.max(b2.top - clientY, b2.bottom - clientY));
            return a2 - b2;
          });
          if (rects.length > 0) {
            clientY = (rects[0].bottom + rects[0].top) / 2;
            try {
              rng.moveToPoint(clientX, clientY);
              rng.collapse(true);
              return rng;
            } catch (ex) {
            }
          }
          return null;
        };
        var moveOutOfContentEditableFalse = function(rng, rootNode) {
          var parentElement = rng && rng.parentElement ? rng.parentElement() : null;
          return isContentEditableFalse$b(findParent$1(parentElement, rootNode, hasCeProperty)) ? null : rng;
        };
        var fromPoint = function(clientX, clientY, doc2) {
          var rng, point;
          var pointDoc = doc2;
          if (pointDoc.caretPositionFromPoint) {
            point = pointDoc.caretPositionFromPoint(clientX, clientY);
            if (point) {
              rng = doc2.createRange();
              rng.setStart(point.offsetNode, point.offset);
              rng.collapse(true);
            }
          } else if (pointDoc.caretRangeFromPoint) {
            rng = pointDoc.caretRangeFromPoint(clientX, clientY);
          } else if (pointDoc.body.createTextRange) {
            rng = pointDoc.body.createTextRange();
            try {
              rng.moveToPoint(clientX, clientY);
              rng.collapse(true);
            } catch (ex) {
              rng = findClosestIeRange(clientX, clientY, doc2);
            }
            return moveOutOfContentEditableFalse(rng, doc2.body);
          }
          return rng;
        };
        var isEq$4 = function(rng1, rng2) {
          return rng1 && rng2 && (rng1.startContainer === rng2.startContainer && rng1.startOffset === rng2.startOffset) && (rng1.endContainer === rng2.endContainer && rng1.endOffset === rng2.endOffset);
        };
        var findParent = function(node, rootNode, predicate) {
          while (node && node !== rootNode) {
            if (predicate(node)) {
              return node;
            }
            node = node.parentNode;
          }
          return null;
        };
        var hasParent$1 = function(node, rootNode, predicate) {
          return findParent(node, rootNode, predicate) !== null;
        };
        var hasParentWithName = function(node, rootNode, name2) {
          return hasParent$1(node, rootNode, function(node2) {
            return node2.nodeName === name2;
          });
        };
        var isTable = function(node) {
          return node && node.nodeName === "TABLE";
        };
        var isTableCell$2 = function(node) {
          return node && /^(TD|TH|CAPTION)$/.test(node.nodeName);
        };
        var isCeFalseCaretContainer = function(node, rootNode) {
          return isCaretContainer$2(node) && hasParent$1(node, rootNode, isCaretNode) === false;
        };
        var hasBrBeforeAfter = function(dom2, node, left2) {
          var walker = new DomTreeWalker(node, dom2.getParent(node.parentNode, dom2.isBlock) || dom2.getRoot());
          while (node = walker[left2 ? "prev" : "next"]()) {
            if (isBr$5(node)) {
              return true;
            }
          }
        };
        var isPrevNode = function(node, name2) {
          return node.previousSibling && node.previousSibling.nodeName === name2;
        };
        var hasContentEditableFalseParent = function(body, node) {
          while (node && node !== body) {
            if (isContentEditableFalse$b(node)) {
              return true;
            }
            node = node.parentNode;
          }
          return false;
        };
        var findTextNodeRelative = function(dom2, isAfterNode, collapsed, left2, startNode) {
          var lastInlineElement;
          var body = dom2.getRoot();
          var node;
          var nonEmptyElementsMap = dom2.schema.getNonEmptyElements();
          var parentBlockContainer = dom2.getParent(startNode.parentNode, dom2.isBlock) || body;
          if (left2 && isBr$5(startNode) && isAfterNode && dom2.isEmpty(parentBlockContainer)) {
            return Optional.some(CaretPosition(startNode.parentNode, dom2.nodeIndex(startNode)));
          }
          var walker = new DomTreeWalker(startNode, parentBlockContainer);
          while (node = walker[left2 ? "prev" : "next"]()) {
            if (dom2.getContentEditableParent(node) === "false" || isCeFalseCaretContainer(node, body)) {
              return Optional.none();
            }
            if (isText$7(node) && node.nodeValue.length > 0) {
              if (hasParentWithName(node, body, "A") === false) {
                return Optional.some(CaretPosition(node, left2 ? node.nodeValue.length : 0));
              }
              return Optional.none();
            }
            if (dom2.isBlock(node) || nonEmptyElementsMap[node.nodeName.toLowerCase()]) {
              return Optional.none();
            }
            lastInlineElement = node;
          }
          if (collapsed && lastInlineElement) {
            return Optional.some(CaretPosition(lastInlineElement, 0));
          }
          return Optional.none();
        };
        var normalizeEndPoint = function(dom2, collapsed, start5, rng) {
          var container, offset2;
          var body = dom2.getRoot();
          var node;
          var directionLeft, normalized = false;
          container = rng[(start5 ? "start" : "end") + "Container"];
          offset2 = rng[(start5 ? "start" : "end") + "Offset"];
          var isAfterNode = isElement$5(container) && offset2 === container.childNodes.length;
          var nonEmptyElementsMap = dom2.schema.getNonEmptyElements();
          directionLeft = start5;
          if (isCaretContainer$2(container)) {
            return Optional.none();
          }
          if (isElement$5(container) && offset2 > container.childNodes.length - 1) {
            directionLeft = false;
          }
          if (isDocument$1(container)) {
            container = body;
            offset2 = 0;
          }
          if (container === body) {
            if (directionLeft) {
              node = container.childNodes[offset2 > 0 ? offset2 - 1 : 0];
              if (node) {
                if (isCaretContainer$2(node)) {
                  return Optional.none();
                }
                if (nonEmptyElementsMap[node.nodeName] || isTable(node)) {
                  return Optional.none();
                }
              }
            }
            if (container.hasChildNodes()) {
              offset2 = Math.min(!directionLeft && offset2 > 0 ? offset2 - 1 : offset2, container.childNodes.length - 1);
              container = container.childNodes[offset2];
              offset2 = isText$7(container) && isAfterNode ? container.data.length : 0;
              if (!collapsed && container === body.lastChild && isTable(container)) {
                return Optional.none();
              }
              if (hasContentEditableFalseParent(body, container) || isCaretContainer$2(container)) {
                return Optional.none();
              }
              if (container.hasChildNodes() && isTable(container) === false) {
                node = container;
                var walker = new DomTreeWalker(container, body);
                do {
                  if (isContentEditableFalse$b(node) || isCaretContainer$2(node)) {
                    normalized = false;
                    break;
                  }
                  if (isText$7(node) && node.nodeValue.length > 0) {
                    offset2 = directionLeft ? 0 : node.nodeValue.length;
                    container = node;
                    normalized = true;
                    break;
                  }
                  if (nonEmptyElementsMap[node.nodeName.toLowerCase()] && !isTableCell$2(node)) {
                    offset2 = dom2.nodeIndex(node);
                    container = node.parentNode;
                    if (!directionLeft) {
                      offset2++;
                    }
                    normalized = true;
                    break;
                  }
                } while (node = directionLeft ? walker.next() : walker.prev());
              }
            }
          }
          if (collapsed) {
            if (isText$7(container) && offset2 === 0) {
              findTextNodeRelative(dom2, isAfterNode, collapsed, true, container).each(function(pos) {
                container = pos.container();
                offset2 = pos.offset();
                normalized = true;
              });
            }
            if (isElement$5(container)) {
              node = container.childNodes[offset2];
              if (!node) {
                node = container.childNodes[offset2 - 1];
              }
              if (node && isBr$5(node) && !isPrevNode(node, "A") && !hasBrBeforeAfter(dom2, node, false) && !hasBrBeforeAfter(dom2, node, true)) {
                findTextNodeRelative(dom2, isAfterNode, collapsed, true, node).each(function(pos) {
                  container = pos.container();
                  offset2 = pos.offset();
                  normalized = true;
                });
              }
            }
          }
          if (directionLeft && !collapsed && isText$7(container) && offset2 === container.nodeValue.length) {
            findTextNodeRelative(dom2, isAfterNode, collapsed, false, container).each(function(pos) {
              container = pos.container();
              offset2 = pos.offset();
              normalized = true;
            });
          }
          return normalized ? Optional.some(CaretPosition(container, offset2)) : Optional.none();
        };
        var normalize$2 = function(dom2, rng) {
          var collapsed = rng.collapsed, normRng = rng.cloneRange();
          var startPos = CaretPosition.fromRangeStart(rng);
          normalizeEndPoint(dom2, collapsed, true, normRng).each(function(pos) {
            if (!collapsed || !CaretPosition.isAbove(startPos, pos)) {
              normRng.setStart(pos.container(), pos.offset());
            }
          });
          if (!collapsed) {
            normalizeEndPoint(dom2, collapsed, false, normRng).each(function(pos) {
              normRng.setEnd(pos.container(), pos.offset());
            });
          }
          if (collapsed) {
            normRng.collapse(true);
          }
          return isEq$4(rng, normRng) ? Optional.none() : Optional.some(normRng);
        };
        var splitText = function(node, offset2) {
          return node.splitText(offset2);
        };
        var split = function(rng) {
          var startContainer = rng.startContainer, startOffset = rng.startOffset, endContainer = rng.endContainer, endOffset = rng.endOffset;
          if (startContainer === endContainer && isText$7(startContainer)) {
            if (startOffset > 0 && startOffset < startContainer.nodeValue.length) {
              endContainer = splitText(startContainer, startOffset);
              startContainer = endContainer.previousSibling;
              if (endOffset > startOffset) {
                endOffset = endOffset - startOffset;
                startContainer = endContainer = splitText(endContainer, endOffset).previousSibling;
                endOffset = endContainer.nodeValue.length;
                startOffset = 0;
              } else {
                endOffset = 0;
              }
            }
          } else {
            if (isText$7(startContainer) && startOffset > 0 && startOffset < startContainer.nodeValue.length) {
              startContainer = splitText(startContainer, startOffset);
              startOffset = 0;
            }
            if (isText$7(endContainer) && endOffset > 0 && endOffset < endContainer.nodeValue.length) {
              endContainer = splitText(endContainer, endOffset).previousSibling;
              endOffset = endContainer.nodeValue.length;
            }
          }
          return {
            startContainer,
            startOffset,
            endContainer,
            endOffset
          };
        };
        var RangeUtils = function(dom2) {
          var walk3 = function(rng, callback2) {
            return walk$2(dom2, rng, callback2);
          };
          var split$12 = split;
          var normalize2 = function(rng) {
            return normalize$2(dom2, rng).fold(never, function(normalizedRng) {
              rng.setStart(normalizedRng.startContainer, normalizedRng.startOffset);
              rng.setEnd(normalizedRng.endContainer, normalizedRng.endOffset);
              return true;
            });
          };
          return {
            walk: walk3,
            split: split$12,
            normalize: normalize2
          };
        };
        RangeUtils.compareRanges = isEq$4;
        RangeUtils.getCaretRangeFromPoint = fromPoint;
        RangeUtils.getSelectedNode = getSelectedNode;
        RangeUtils.getNode = getNode$1;
        var Dimension = function(name2, getOffset) {
          var set3 = function(element, h3) {
            if (!isNumber2(h3) && !h3.match(/^[0-9]+$/)) {
              throw new Error(name2 + ".set accepts only positive integer values. Value was " + h3);
            }
            var dom2 = element.dom;
            if (isSupported(dom2)) {
              dom2.style[name2] = h3 + "px";
            }
          };
          var get2 = function(element) {
            var r3 = getOffset(element);
            if (r3 <= 0 || r3 === null) {
              var css = get$5(element, name2);
              return parseFloat(css) || 0;
            }
            return r3;
          };
          var getOuter = get2;
          var aggregate = function(element, properties) {
            return foldl(properties, function(acc, property) {
              var val = get$5(element, property);
              var value2 = val === void 0 ? 0 : parseInt(val, 10);
              return isNaN(value2) ? acc : acc + value2;
            }, 0);
          };
          var max3 = function(element, value2, properties) {
            var cumulativeInclusions = aggregate(element, properties);
            var absoluteMax = value2 > cumulativeInclusions ? value2 - cumulativeInclusions : 0;
            return absoluteMax;
          };
          return {
            set: set3,
            get: get2,
            getOuter,
            aggregate,
            max: max3
          };
        };
        var api = Dimension("height", function(element) {
          var dom2 = element.dom;
          return inBody(element) ? dom2.getBoundingClientRect().height : dom2.offsetHeight;
        });
        var get$1 = function(element) {
          return api.get(element);
        };
        var walkUp = function(navigation, doc2) {
          var frame = navigation.view(doc2);
          return frame.fold(constant([]), function(f2) {
            var parent2 = navigation.owner(f2);
            var rest = walkUp(navigation, parent2);
            return [f2].concat(rest);
          });
        };
        var pathTo = function(element, navigation) {
          var d2 = navigation.owner(element);
          return walkUp(navigation, d2);
        };
        var view = function(doc2) {
          var _a;
          var element = doc2.dom === document ? Optional.none() : Optional.from((_a = doc2.dom.defaultView) === null || _a === void 0 ? void 0 : _a.frameElement);
          return element.map(SugarElement.fromDom);
        };
        var owner = function(element) {
          return documentOrOwner(element);
        };
        var Navigation = /* @__PURE__ */ Object.freeze({
          __proto__: null,
          view,
          owner
        });
        var find$1 = function(element) {
          var doc2 = SugarElement.fromDom(document);
          var scroll = get$8(doc2);
          var frames = pathTo(element, Navigation);
          var offset2 = viewport2(element);
          var r3 = foldr(frames, function(b2, a2) {
            var loc = viewport2(a2);
            return {
              left: b2.left + loc.left,
              top: b2.top + loc.top
            };
          }, {
            left: 0,
            top: 0
          });
          return SugarPosition(r3.left + offset2.left + scroll.left, r3.top + offset2.top + scroll.top);
        };
        var excludeFromDescend = function(element) {
          return name(element) === "textarea";
        };
        var fireScrollIntoViewEvent = function(editor, data2) {
          var scrollEvent = editor.fire("ScrollIntoView", data2);
          return scrollEvent.isDefaultPrevented();
        };
        var fireAfterScrollIntoViewEvent = function(editor, data2) {
          editor.fire("AfterScrollIntoView", data2);
        };
        var descend = function(element, offset2) {
          var children$1 = children(element);
          if (children$1.length === 0 || excludeFromDescend(element)) {
            return {
              element,
              offset: offset2
            };
          } else if (offset2 < children$1.length && !excludeFromDescend(children$1[offset2])) {
            return {
              element: children$1[offset2],
              offset: 0
            };
          } else {
            var last2 = children$1[children$1.length - 1];
            if (excludeFromDescend(last2)) {
              return {
                element,
                offset: offset2
              };
            } else {
              if (name(last2) === "img") {
                return {
                  element: last2,
                  offset: 1
                };
              } else if (isText$8(last2)) {
                return {
                  element: last2,
                  offset: get$2(last2).length
                };
              } else {
                return {
                  element: last2,
                  offset: children(last2).length
                };
              }
            }
          }
        };
        var markerInfo = function(element, cleanupFun) {
          var pos = absolute(element);
          var height = get$1(element);
          return {
            element,
            bottom: pos.top + height,
            height,
            pos,
            cleanup: cleanupFun
          };
        };
        var createMarker = function(element, offset2) {
          var startPoint = descend(element, offset2);
          var span = SugarElement.fromHtml('<span data-mce-bogus="all" style="display: inline-block;">' + ZWSP$1 + "</span>");
          before$4(startPoint.element, span);
          return markerInfo(span, function() {
            return remove$7(span);
          });
        };
        var elementMarker = function(element) {
          return markerInfo(SugarElement.fromDom(element), noop3);
        };
        var withMarker = function(editor, f2, rng, alignToTop) {
          preserveWith(editor, function(_s, _e2) {
            return applyWithMarker(editor, f2, rng, alignToTop);
          }, rng);
        };
        var withScrollEvents = function(editor, doc2, f2, marker, alignToTop) {
          var data2 = {
            elm: marker.element.dom,
            alignToTop
          };
          if (fireScrollIntoViewEvent(editor, data2)) {
            return;
          }
          var scrollTop = get$8(doc2).top;
          f2(doc2, scrollTop, marker, alignToTop);
          fireAfterScrollIntoViewEvent(editor, data2);
        };
        var applyWithMarker = function(editor, f2, rng, alignToTop) {
          var body = SugarElement.fromDom(editor.getBody());
          var doc2 = SugarElement.fromDom(editor.getDoc());
          reflow2(body);
          var marker = createMarker(SugarElement.fromDom(rng.startContainer), rng.startOffset);
          withScrollEvents(editor, doc2, f2, marker, alignToTop);
          marker.cleanup();
        };
        var withElement = function(editor, element, f2, alignToTop) {
          var doc2 = SugarElement.fromDom(editor.getDoc());
          withScrollEvents(editor, doc2, f2, elementMarker(element), alignToTop);
        };
        var preserveWith = function(editor, f2, rng) {
          var startElement = rng.startContainer;
          var startOffset = rng.startOffset;
          var endElement = rng.endContainer;
          var endOffset = rng.endOffset;
          f2(SugarElement.fromDom(startElement), SugarElement.fromDom(endElement));
          var newRng = editor.dom.createRng();
          newRng.setStart(startElement, startOffset);
          newRng.setEnd(endElement, endOffset);
          editor.selection.setRng(rng);
        };
        var scrollToMarker = function(marker, viewHeight, alignToTop, doc2) {
          var pos = marker.pos;
          if (alignToTop) {
            to(pos.left, pos.top, doc2);
          } else {
            var y2 = pos.top - viewHeight + marker.height;
            to(pos.left, y2, doc2);
          }
        };
        var intoWindowIfNeeded = function(doc2, scrollTop, viewHeight, marker, alignToTop) {
          var viewportBottom = viewHeight + scrollTop;
          var markerTop = marker.pos.top;
          var markerBottom = marker.bottom;
          var largerThanViewport = markerBottom - markerTop >= viewHeight;
          if (markerTop < scrollTop) {
            scrollToMarker(marker, viewHeight, alignToTop !== false, doc2);
          } else if (markerTop > viewportBottom) {
            var align = largerThanViewport ? alignToTop !== false : alignToTop === true;
            scrollToMarker(marker, viewHeight, align, doc2);
          } else if (markerBottom > viewportBottom && !largerThanViewport) {
            scrollToMarker(marker, viewHeight, alignToTop === true, doc2);
          }
        };
        var intoWindow = function(doc2, scrollTop, marker, alignToTop) {
          var viewHeight = doc2.dom.defaultView.innerHeight;
          intoWindowIfNeeded(doc2, scrollTop, viewHeight, marker, alignToTop);
        };
        var intoFrame = function(doc2, scrollTop, marker, alignToTop) {
          var frameViewHeight = doc2.dom.defaultView.innerHeight;
          intoWindowIfNeeded(doc2, scrollTop, frameViewHeight, marker, alignToTop);
          var op = find$1(marker.element);
          var viewportBounds = getBounds2(window);
          if (op.top < viewportBounds.y) {
            intoView(marker.element, alignToTop !== false);
          } else if (op.top > viewportBounds.bottom) {
            intoView(marker.element, alignToTop === true);
          }
        };
        var rangeIntoWindow = function(editor, rng, alignToTop) {
          return withMarker(editor, intoWindow, rng, alignToTop);
        };
        var elementIntoWindow = function(editor, element, alignToTop) {
          return withElement(editor, element, intoWindow, alignToTop);
        };
        var rangeIntoFrame = function(editor, rng, alignToTop) {
          return withMarker(editor, intoFrame, rng, alignToTop);
        };
        var elementIntoFrame = function(editor, element, alignToTop) {
          return withElement(editor, element, intoFrame, alignToTop);
        };
        var scrollElementIntoView = function(editor, element, alignToTop) {
          var scroller = editor.inline ? elementIntoWindow : elementIntoFrame;
          scroller(editor, element, alignToTop);
        };
        var scrollRangeIntoView = function(editor, rng, alignToTop) {
          var scroller = editor.inline ? rangeIntoWindow : rangeIntoFrame;
          scroller(editor, rng, alignToTop);
        };
        var getDocument = function() {
          return SugarElement.fromDom(document);
        };
        var focus$1 = function(element) {
          return element.dom.focus();
        };
        var hasFocus$1 = function(element) {
          var root = getRootNode(element).dom;
          return element.dom === root.activeElement;
        };
        var active = function(root) {
          if (root === void 0) {
            root = getDocument();
          }
          return Optional.from(root.dom.activeElement).map(SugarElement.fromDom);
        };
        var search = function(element) {
          return active(getRootNode(element)).filter(function(e2) {
            return element.dom.contains(e2.dom);
          });
        };
        var create$5 = function(start5, soffset, finish, foffset) {
          return {
            start: start5,
            soffset,
            finish,
            foffset
          };
        };
        var SimRange = { create: create$5 };
        var adt$1 = Adt.generate([
          { before: ["element"] },
          {
            on: [
              "element",
              "offset"
            ]
          },
          { after: ["element"] }
        ]);
        var cata = function(subject, onBefore, onOn, onAfter) {
          return subject.fold(onBefore, onOn, onAfter);
        };
        var getStart$2 = function(situ) {
          return situ.fold(identity, identity, identity);
        };
        var before$1 = adt$1.before;
        var on2 = adt$1.on;
        var after$1 = adt$1.after;
        var Situ = {
          before: before$1,
          on: on2,
          after: after$1,
          cata,
          getStart: getStart$2
        };
        var adt = Adt.generate([
          { domRange: ["rng"] },
          {
            relative: [
              "startSitu",
              "finishSitu"
            ]
          },
          {
            exact: [
              "start",
              "soffset",
              "finish",
              "foffset"
            ]
          }
        ]);
        var exactFromRange = function(simRange) {
          return adt.exact(simRange.start, simRange.soffset, simRange.finish, simRange.foffset);
        };
        var getStart$1 = function(selection) {
          return selection.match({
            domRange: function(rng) {
              return SugarElement.fromDom(rng.startContainer);
            },
            relative: function(startSitu, _finishSitu) {
              return Situ.getStart(startSitu);
            },
            exact: function(start5, _soffset, _finish, _foffset) {
              return start5;
            }
          });
        };
        var domRange = adt.domRange;
        var relative = adt.relative;
        var exact = adt.exact;
        var getWin = function(selection) {
          var start5 = getStart$1(selection);
          return defaultView(start5);
        };
        var range = SimRange.create;
        var SimSelection = {
          domRange,
          relative,
          exact,
          exactFromRange,
          getWin,
          range
        };
        var browser$1 = detect().browser;
        var clamp$1 = function(offset2, element) {
          var max3 = isText$8(element) ? get$2(element).length : children(element).length + 1;
          if (offset2 > max3) {
            return max3;
          } else if (offset2 < 0) {
            return 0;
          }
          return offset2;
        };
        var normalizeRng = function(rng) {
          return SimSelection.range(rng.start, clamp$1(rng.soffset, rng.start), rng.finish, clamp$1(rng.foffset, rng.finish));
        };
        var isOrContains = function(root, elm) {
          return !isRestrictedNode(elm.dom) && (contains$1(root, elm) || eq2(root, elm));
        };
        var isRngInRoot = function(root) {
          return function(rng) {
            return isOrContains(root, rng.start) && isOrContains(root, rng.finish);
          };
        };
        var shouldStore = function(editor) {
          return editor.inline === true || browser$1.isIE();
        };
        var nativeRangeToSelectionRange = function(r3) {
          return SimSelection.range(SugarElement.fromDom(r3.startContainer), r3.startOffset, SugarElement.fromDom(r3.endContainer), r3.endOffset);
        };
        var readRange = function(win) {
          var selection = win.getSelection();
          var rng = !selection || selection.rangeCount === 0 ? Optional.none() : Optional.from(selection.getRangeAt(0));
          return rng.map(nativeRangeToSelectionRange);
        };
        var getBookmark = function(root) {
          var win = defaultView(root);
          return readRange(win.dom).filter(isRngInRoot(root));
        };
        var validate = function(root, bookmark) {
          return Optional.from(bookmark).filter(isRngInRoot(root)).map(normalizeRng);
        };
        var bookmarkToNativeRng = function(bookmark) {
          var rng = document.createRange();
          try {
            rng.setStart(bookmark.start.dom, bookmark.soffset);
            rng.setEnd(bookmark.finish.dom, bookmark.foffset);
            return Optional.some(rng);
          } catch (_2) {
            return Optional.none();
          }
        };
        var store = function(editor) {
          var newBookmark = shouldStore(editor) ? getBookmark(SugarElement.fromDom(editor.getBody())) : Optional.none();
          editor.bookmark = newBookmark.isSome() ? newBookmark : editor.bookmark;
        };
        var storeNative = function(editor, rng) {
          var root = SugarElement.fromDom(editor.getBody());
          var range2 = shouldStore(editor) ? Optional.from(rng) : Optional.none();
          var newBookmark = range2.map(nativeRangeToSelectionRange).filter(isRngInRoot(root));
          editor.bookmark = newBookmark.isSome() ? newBookmark : editor.bookmark;
        };
        var getRng = function(editor) {
          var bookmark = editor.bookmark ? editor.bookmark : Optional.none();
          return bookmark.bind(function(x2) {
            return validate(SugarElement.fromDom(editor.getBody()), x2);
          }).bind(bookmarkToNativeRng);
        };
        var restore = function(editor) {
          getRng(editor).each(function(rng) {
            return editor.selection.setRng(rng);
          });
        };
        var isEditorUIElement$1 = function(elm) {
          var className = elm.className.toString();
          return className.indexOf("tox-") !== -1 || className.indexOf("mce-") !== -1;
        };
        var FocusManager = { isEditorUIElement: isEditorUIElement$1 };
        var isManualNodeChange = function(e2) {
          return e2.type === "nodechange" && e2.selectionChange;
        };
        var registerPageMouseUp = function(editor, throttledStore) {
          var mouseUpPage = function() {
            throttledStore.throttle();
          };
          DOMUtils.DOM.bind(document, "mouseup", mouseUpPage);
          editor.on("remove", function() {
            DOMUtils.DOM.unbind(document, "mouseup", mouseUpPage);
          });
        };
        var registerFocusOut = function(editor) {
          editor.on("focusout", function() {
            store(editor);
          });
        };
        var registerMouseUp = function(editor, throttledStore) {
          editor.on("mouseup touchend", function(_e2) {
            throttledStore.throttle();
          });
        };
        var registerEditorEvents = function(editor, throttledStore) {
          var browser2 = detect().browser;
          if (browser2.isIE()) {
            registerFocusOut(editor);
          } else {
            registerMouseUp(editor, throttledStore);
          }
          editor.on("keyup NodeChange", function(e2) {
            if (!isManualNodeChange(e2)) {
              store(editor);
            }
          });
        };
        var register$3 = function(editor) {
          var throttledStore = first(function() {
            store(editor);
          }, 0);
          editor.on("init", function() {
            if (editor.inline) {
              registerPageMouseUp(editor, throttledStore);
            }
            registerEditorEvents(editor, throttledStore);
          });
          editor.on("remove", function() {
            throttledStore.cancel();
          });
        };
        var documentFocusInHandler;
        var DOM$8 = DOMUtils.DOM;
        var isEditorUIElement = function(elm) {
          return FocusManager.isEditorUIElement(elm);
        };
        var isEditorContentAreaElement = function(elm) {
          var classList = elm.classList;
          if (classList !== void 0) {
            return classList.contains("tox-edit-area") || classList.contains("tox-edit-area__iframe") || classList.contains("mce-content-body");
          } else {
            return false;
          }
        };
        var isUIElement = function(editor, elm) {
          var customSelector = getCustomUiSelector(editor);
          var parent2 = DOM$8.getParent(elm, function(elm2) {
            return isEditorUIElement(elm2) || (customSelector ? editor.dom.is(elm2, customSelector) : false);
          });
          return parent2 !== null;
        };
        var getActiveElement = function(editor) {
          try {
            var root = getRootNode(SugarElement.fromDom(editor.getElement()));
            return active(root).fold(function() {
              return document.body;
            }, function(x2) {
              return x2.dom;
            });
          } catch (ex) {
            return document.body;
          }
        };
        var registerEvents$1 = function(editorManager, e2) {
          var editor = e2.editor;
          register$3(editor);
          editor.on("focusin", function() {
            var focusedEditor = editorManager.focusedEditor;
            if (focusedEditor !== editor) {
              if (focusedEditor) {
                focusedEditor.fire("blur", { focusedEditor: editor });
              }
              editorManager.setActive(editor);
              editorManager.focusedEditor = editor;
              editor.fire("focus", { blurredEditor: focusedEditor });
              editor.focus(true);
            }
          });
          editor.on("focusout", function() {
            Delay.setEditorTimeout(editor, function() {
              var focusedEditor = editorManager.focusedEditor;
              if (!isUIElement(editor, getActiveElement(editor)) && focusedEditor === editor) {
                editor.fire("blur", { focusedEditor: null });
                editorManager.focusedEditor = null;
              }
            });
          });
          if (!documentFocusInHandler) {
            documentFocusInHandler = function(e3) {
              var activeEditor = editorManager.activeEditor;
              if (activeEditor) {
                getOriginalEventTarget(e3).each(function(target) {
                  if (target.ownerDocument === document) {
                    if (target !== document.body && !isUIElement(activeEditor, target) && editorManager.focusedEditor === activeEditor) {
                      activeEditor.fire("blur", { focusedEditor: null });
                      editorManager.focusedEditor = null;
                    }
                  }
                });
              }
            };
            DOM$8.bind(document, "focusin", documentFocusInHandler);
          }
        };
        var unregisterDocumentEvents = function(editorManager, e2) {
          if (editorManager.focusedEditor === e2.editor) {
            editorManager.focusedEditor = null;
          }
          if (!editorManager.activeEditor) {
            DOM$8.unbind(document, "focusin", documentFocusInHandler);
            documentFocusInHandler = null;
          }
        };
        var setup$l = function(editorManager) {
          editorManager.on("AddEditor", curry(registerEvents$1, editorManager));
          editorManager.on("RemoveEditor", curry(unregisterDocumentEvents, editorManager));
        };
        var getContentEditableHost = function(editor, node) {
          return editor.dom.getParent(node, function(node2) {
            return editor.dom.getContentEditable(node2) === "true";
          });
        };
        var getCollapsedNode = function(rng) {
          return rng.collapsed ? Optional.from(getNode$1(rng.startContainer, rng.startOffset)).map(SugarElement.fromDom) : Optional.none();
        };
        var getFocusInElement = function(root, rng) {
          return getCollapsedNode(rng).bind(function(node) {
            if (isTableSection(node)) {
              return Optional.some(node);
            } else if (contains$1(root, node) === false) {
              return Optional.some(root);
            } else {
              return Optional.none();
            }
          });
        };
        var normalizeSelection$1 = function(editor, rng) {
          getFocusInElement(SugarElement.fromDom(editor.getBody()), rng).bind(function(elm) {
            return firstPositionIn(elm.dom);
          }).fold(function() {
            editor.selection.normalize();
            return;
          }, function(caretPos) {
            return editor.selection.setRng(caretPos.toRange());
          });
        };
        var focusBody = function(body) {
          if (body.setActive) {
            try {
              body.setActive();
            } catch (ex) {
              body.focus();
            }
          } else {
            body.focus();
          }
        };
        var hasElementFocus = function(elm) {
          return hasFocus$1(elm) || search(elm).isSome();
        };
        var hasIframeFocus = function(editor) {
          return editor.iframeElement && hasFocus$1(SugarElement.fromDom(editor.iframeElement));
        };
        var hasInlineFocus = function(editor) {
          var rawBody = editor.getBody();
          return rawBody && hasElementFocus(SugarElement.fromDom(rawBody));
        };
        var hasUiFocus = function(editor) {
          var dos = getRootNode(SugarElement.fromDom(editor.getElement()));
          return active(dos).filter(function(elem) {
            return !isEditorContentAreaElement(elem.dom) && isUIElement(editor, elem.dom);
          }).isSome();
        };
        var hasFocus = function(editor) {
          return editor.inline ? hasInlineFocus(editor) : hasIframeFocus(editor);
        };
        var hasEditorOrUiFocus = function(editor) {
          return hasFocus(editor) || hasUiFocus(editor);
        };
        var focusEditor = function(editor) {
          var selection = editor.selection;
          var body = editor.getBody();
          var rng = selection.getRng();
          editor.quirks.refreshContentEditable();
          if (editor.bookmark !== void 0 && hasFocus(editor) === false) {
            getRng(editor).each(function(bookmarkRng) {
              editor.selection.setRng(bookmarkRng);
              rng = bookmarkRng;
            });
          }
          var contentEditableHost = getContentEditableHost(editor, selection.getNode());
          if (editor.$.contains(body, contentEditableHost)) {
            focusBody(contentEditableHost);
            normalizeSelection$1(editor, rng);
            activateEditor(editor);
            return;
          }
          if (!editor.inline) {
            if (!Env.opera) {
              focusBody(body);
            }
            editor.getWin().focus();
          }
          if (Env.gecko || editor.inline) {
            focusBody(body);
            normalizeSelection$1(editor, rng);
          }
          activateEditor(editor);
        };
        var activateEditor = function(editor) {
          return editor.editorManager.setActive(editor);
        };
        var focus = function(editor, skipFocus) {
          if (editor.removed) {
            return;
          }
          if (skipFocus) {
            activateEditor(editor);
          } else {
            focusEditor(editor);
          }
        };
        var getEndpointElement = function(root, rng, start5, real, resolve3) {
          var container = start5 ? rng.startContainer : rng.endContainer;
          var offset2 = start5 ? rng.startOffset : rng.endOffset;
          return Optional.from(container).map(SugarElement.fromDom).map(function(elm) {
            return !real || !rng.collapsed ? child$1(elm, resolve3(elm, offset2)).getOr(elm) : elm;
          }).bind(function(elm) {
            return isElement$6(elm) ? Optional.some(elm) : parent(elm).filter(isElement$6);
          }).map(function(elm) {
            return elm.dom;
          }).getOr(root);
        };
        var getStart = function(root, rng, real) {
          return getEndpointElement(root, rng, true, real, function(elm, offset2) {
            return Math.min(childNodesCount(elm), offset2);
          });
        };
        var getEnd = function(root, rng, real) {
          return getEndpointElement(root, rng, false, real, function(elm, offset2) {
            return offset2 > 0 ? offset2 - 1 : offset2;
          });
        };
        var skipEmptyTextNodes = function(node, forwards) {
          var orig = node;
          while (node && isText$7(node) && node.length === 0) {
            node = forwards ? node.nextSibling : node.previousSibling;
          }
          return node || orig;
        };
        var getNode = function(root, rng) {
          var elm, startContainer, endContainer;
          if (!rng) {
            return root;
          }
          startContainer = rng.startContainer;
          endContainer = rng.endContainer;
          var startOffset = rng.startOffset;
          var endOffset = rng.endOffset;
          elm = rng.commonAncestorContainer;
          if (!rng.collapsed) {
            if (startContainer === endContainer) {
              if (endOffset - startOffset < 2) {
                if (startContainer.hasChildNodes()) {
                  elm = startContainer.childNodes[startOffset];
                }
              }
            }
            if (startContainer.nodeType === 3 && endContainer.nodeType === 3) {
              if (startContainer.length === startOffset) {
                startContainer = skipEmptyTextNodes(startContainer.nextSibling, true);
              } else {
                startContainer = startContainer.parentNode;
              }
              if (endOffset === 0) {
                endContainer = skipEmptyTextNodes(endContainer.previousSibling, false);
              } else {
                endContainer = endContainer.parentNode;
              }
              if (startContainer && startContainer === endContainer) {
                return startContainer;
              }
            }
          }
          if (elm && elm.nodeType === 3) {
            return elm.parentNode;
          }
          return elm;
        };
        var getSelectedBlocks = function(dom2, rng, startElm, endElm) {
          var node;
          var selectedBlocks = [];
          var root = dom2.getRoot();
          startElm = dom2.getParent(startElm || getStart(root, rng, rng.collapsed), dom2.isBlock);
          endElm = dom2.getParent(endElm || getEnd(root, rng, rng.collapsed), dom2.isBlock);
          if (startElm && startElm !== root) {
            selectedBlocks.push(startElm);
          }
          if (startElm && endElm && startElm !== endElm) {
            node = startElm;
            var walker = new DomTreeWalker(startElm, root);
            while ((node = walker.next()) && node !== endElm) {
              if (dom2.isBlock(node)) {
                selectedBlocks.push(node);
              }
            }
          }
          if (endElm && startElm !== endElm && endElm !== root) {
            selectedBlocks.push(endElm);
          }
          return selectedBlocks;
        };
        var select = function(dom2, node, content) {
          return Optional.from(node).map(function(node2) {
            var idx = dom2.nodeIndex(node2);
            var rng = dom2.createRng();
            rng.setStart(node2.parentNode, idx);
            rng.setEnd(node2.parentNode, idx + 1);
            if (content) {
              moveEndPoint(dom2, rng, node2, true);
              moveEndPoint(dom2, rng, node2, false);
            }
            return rng;
          });
        };
        var processRanges = function(editor, ranges) {
          return map$3(ranges, function(range2) {
            var evt = editor.fire("GetSelectionRange", { range: range2 });
            return evt.range !== range2 ? evt.range : range2;
          });
        };
        var typeLookup = {
          "#text": 3,
          "#comment": 8,
          "#cdata": 4,
          "#pi": 7,
          "#doctype": 10,
          "#document-fragment": 11
        };
        var walk$1 = function(node, root, prev) {
          var startName = prev ? "lastChild" : "firstChild";
          var siblingName = prev ? "prev" : "next";
          if (node[startName]) {
            return node[startName];
          }
          if (node !== root) {
            var sibling2 = node[siblingName];
            if (sibling2) {
              return sibling2;
            }
            for (var parent_1 = node.parent; parent_1 && parent_1 !== root; parent_1 = parent_1.parent) {
              sibling2 = parent_1[siblingName];
              if (sibling2) {
                return sibling2;
              }
            }
          }
        };
        var isEmptyTextNode = function(node) {
          if (!isWhitespaceText(node.value)) {
            return false;
          }
          var parentNode = node.parent;
          if (parentNode && (parentNode.name !== "span" || parentNode.attr("style")) && /^[ ]+$/.test(node.value)) {
            return false;
          }
          return true;
        };
        var isNonEmptyElement = function(node) {
          var isNamedAnchor2 = node.name === "a" && !node.attr("href") && node.attr("id");
          return node.attr("name") || node.attr("id") && !node.firstChild || node.attr("data-mce-bookmark") || isNamedAnchor2;
        };
        var AstNode = function() {
          function AstNode2(name2, type2) {
            this.name = name2;
            this.type = type2;
            if (type2 === 1) {
              this.attributes = [];
              this.attributes.map = {};
            }
          }
          AstNode2.create = function(name2, attrs) {
            var node = new AstNode2(name2, typeLookup[name2] || 1);
            if (attrs) {
              each$j(attrs, function(value2, attrName) {
                node.attr(attrName, value2);
              });
            }
            return node;
          };
          AstNode2.prototype.replace = function(node) {
            var self2 = this;
            if (node.parent) {
              node.remove();
            }
            self2.insert(node, self2);
            self2.remove();
            return self2;
          };
          AstNode2.prototype.attr = function(name2, value2) {
            var self2 = this;
            var attrs;
            if (typeof name2 !== "string") {
              if (name2 !== void 0 && name2 !== null) {
                each$j(name2, function(value3, key) {
                  self2.attr(key, value3);
                });
              }
              return self2;
            }
            if (attrs = self2.attributes) {
              if (value2 !== void 0) {
                if (value2 === null) {
                  if (name2 in attrs.map) {
                    delete attrs.map[name2];
                    var i2 = attrs.length;
                    while (i2--) {
                      if (attrs[i2].name === name2) {
                        attrs.splice(i2, 1);
                        return self2;
                      }
                    }
                  }
                  return self2;
                }
                if (name2 in attrs.map) {
                  var i2 = attrs.length;
                  while (i2--) {
                    if (attrs[i2].name === name2) {
                      attrs[i2].value = value2;
                      break;
                    }
                  }
                } else {
                  attrs.push({
                    name: name2,
                    value: value2
                  });
                }
                attrs.map[name2] = value2;
                return self2;
              }
              return attrs.map[name2];
            }
          };
          AstNode2.prototype.clone = function() {
            var self2 = this;
            var clone3 = new AstNode2(self2.name, self2.type);
            var selfAttrs;
            if (selfAttrs = self2.attributes) {
              var cloneAttrs = [];
              cloneAttrs.map = {};
              for (var i2 = 0, l2 = selfAttrs.length; i2 < l2; i2++) {
                var selfAttr = selfAttrs[i2];
                if (selfAttr.name !== "id") {
                  cloneAttrs[cloneAttrs.length] = {
                    name: selfAttr.name,
                    value: selfAttr.value
                  };
                  cloneAttrs.map[selfAttr.name] = selfAttr.value;
                }
              }
              clone3.attributes = cloneAttrs;
            }
            clone3.value = self2.value;
            clone3.shortEnded = self2.shortEnded;
            return clone3;
          };
          AstNode2.prototype.wrap = function(wrapper) {
            var self2 = this;
            self2.parent.insert(wrapper, self2);
            wrapper.append(self2);
            return self2;
          };
          AstNode2.prototype.unwrap = function() {
            var self2 = this;
            for (var node = self2.firstChild; node; ) {
              var next = node.next;
              self2.insert(node, self2, true);
              node = next;
            }
            self2.remove();
          };
          AstNode2.prototype.remove = function() {
            var self2 = this, parent2 = self2.parent, next = self2.next, prev = self2.prev;
            if (parent2) {
              if (parent2.firstChild === self2) {
                parent2.firstChild = next;
                if (next) {
                  next.prev = null;
                }
              } else {
                prev.next = next;
              }
              if (parent2.lastChild === self2) {
                parent2.lastChild = prev;
                if (prev) {
                  prev.next = null;
                }
              } else {
                next.prev = prev;
              }
              self2.parent = self2.next = self2.prev = null;
            }
            return self2;
          };
          AstNode2.prototype.append = function(node) {
            var self2 = this;
            if (node.parent) {
              node.remove();
            }
            var last2 = self2.lastChild;
            if (last2) {
              last2.next = node;
              node.prev = last2;
              self2.lastChild = node;
            } else {
              self2.lastChild = self2.firstChild = node;
            }
            node.parent = self2;
            return node;
          };
          AstNode2.prototype.insert = function(node, refNode, before2) {
            if (node.parent) {
              node.remove();
            }
            var parent2 = refNode.parent || this;
            if (before2) {
              if (refNode === parent2.firstChild) {
                parent2.firstChild = node;
              } else {
                refNode.prev.next = node;
              }
              node.prev = refNode.prev;
              node.next = refNode;
              refNode.prev = node;
            } else {
              if (refNode === parent2.lastChild) {
                parent2.lastChild = node;
              } else {
                refNode.next.prev = node;
              }
              node.next = refNode.next;
              node.prev = refNode;
              refNode.next = node;
            }
            node.parent = parent2;
            return node;
          };
          AstNode2.prototype.getAll = function(name2) {
            var self2 = this;
            var collection = [];
            for (var node = self2.firstChild; node; node = walk$1(node, self2)) {
              if (node.name === name2) {
                collection.push(node);
              }
            }
            return collection;
          };
          AstNode2.prototype.children = function() {
            var self2 = this;
            var collection = [];
            for (var node = self2.firstChild; node; node = node.next) {
              collection.push(node);
            }
            return collection;
          };
          AstNode2.prototype.empty = function() {
            var self2 = this;
            if (self2.firstChild) {
              var nodes = [];
              for (var node = self2.firstChild; node; node = walk$1(node, self2)) {
                nodes.push(node);
              }
              var i2 = nodes.length;
              while (i2--) {
                var node = nodes[i2];
                node.parent = node.firstChild = node.lastChild = node.next = node.prev = null;
              }
            }
            self2.firstChild = self2.lastChild = null;
            return self2;
          };
          AstNode2.prototype.isEmpty = function(elements2, whitespace2, predicate) {
            if (whitespace2 === void 0) {
              whitespace2 = {};
            }
            var self2 = this;
            var node = self2.firstChild;
            if (isNonEmptyElement(self2)) {
              return false;
            }
            if (node) {
              do {
                if (node.type === 1) {
                  if (node.attr("data-mce-bogus")) {
                    continue;
                  }
                  if (elements2[node.name]) {
                    return false;
                  }
                  if (isNonEmptyElement(node)) {
                    return false;
                  }
                }
                if (node.type === 8) {
                  return false;
                }
                if (node.type === 3 && !isEmptyTextNode(node)) {
                  return false;
                }
                if (node.type === 3 && node.parent && whitespace2[node.parent.name] && isWhitespaceText(node.value)) {
                  return false;
                }
                if (predicate && predicate(node)) {
                  return false;
                }
              } while (node = walk$1(node, self2));
            }
            return true;
          };
          AstNode2.prototype.walk = function(prev) {
            return walk$1(this, null, prev);
          };
          return AstNode2;
        }();
        var extractBase64DataUris = function(html) {
          var dataImageUri = /data:[^;]+;base64,([a-z0-9\+\/=\s]+)/gi;
          var chunks = [];
          var uris = {};
          var prefix = generate("img");
          var matches2;
          var index = 0;
          var count2 = 0;
          while (matches2 = dataImageUri.exec(html)) {
            var uri = matches2[0];
            var imageId = prefix + "_" + count2++;
            uris[imageId] = uri;
            if (index < matches2.index) {
              chunks.push(html.substr(index, matches2.index - index));
            }
            chunks.push(imageId);
            index = matches2.index + uri.length;
          }
          var re2 = new RegExp(prefix + "_[0-9]+", "g");
          if (index === 0) {
            return {
              prefix,
              uris,
              html,
              re: re2
            };
          } else {
            if (index < html.length) {
              chunks.push(html.substr(index));
            }
            return {
              prefix,
              uris,
              html: chunks.join(""),
              re: re2
            };
          }
        };
        var restoreDataUris = function(html, result) {
          return html.replace(result.re, function(imageId) {
            return get$9(result.uris, imageId).getOr(imageId);
          });
        };
        var parseDataUri$1 = function(uri) {
          var matches2 = /data:([^;]+);base64,([a-z0-9\+\/=\s]+)/i.exec(uri);
          if (matches2) {
            return Optional.some({
              type: matches2[1],
              data: decodeURIComponent(matches2[2])
            });
          } else {
            return Optional.none();
          }
        };
        var each$d = Tools.each, trim = Tools.trim;
        var queryParts = "source protocol authority userInfo user password host port relative path directory file query anchor".split(" ");
        var DEFAULT_PORTS = {
          ftp: 21,
          http: 80,
          https: 443,
          mailto: 25
        };
        var safeSvgDataUrlElements = [
          "img",
          "video"
        ];
        var blockSvgDataUris = function(allowSvgDataUrls, tagName) {
          if (isNonNullable(allowSvgDataUrls)) {
            return !allowSvgDataUrls;
          } else {
            return isNonNullable(tagName) ? !contains$3(safeSvgDataUrlElements, tagName) : true;
          }
        };
        var isInvalidUri = function(settings, uri, tagName) {
          if (settings.allow_html_data_urls) {
            return false;
          } else if (/^data:image\//i.test(uri)) {
            return blockSvgDataUris(settings.allow_svg_data_urls, tagName) && /^data:image\/svg\+xml/i.test(uri);
          } else {
            return /^data:/i.test(uri);
          }
        };
        var URI = function() {
          function URI2(url, settings) {
            url = trim(url);
            this.settings = settings || {};
            var baseUri = this.settings.base_uri;
            var self2 = this;
            if (/^([\w\-]+):([^\/]{2})/i.test(url) || /^\s*#/.test(url)) {
              self2.source = url;
              return;
            }
            var isProtocolRelative = url.indexOf("//") === 0;
            if (url.indexOf("/") === 0 && !isProtocolRelative) {
              url = (baseUri ? baseUri.protocol || "http" : "http") + "://mce_host" + url;
            }
            if (!/^[\w\-]*:?\/\//.test(url)) {
              var baseUrl = this.settings.base_uri ? this.settings.base_uri.path : new URI2(document.location.href).directory;
              if (this.settings.base_uri && this.settings.base_uri.protocol == "") {
                url = "//mce_host" + self2.toAbsPath(baseUrl, url);
              } else {
                var match3 = /([^#?]*)([#?]?.*)/.exec(url);
                url = (baseUri && baseUri.protocol || "http") + "://mce_host" + self2.toAbsPath(baseUrl, match3[1]) + match3[2];
              }
            }
            url = url.replace(/@@/g, "(mce_at)");
            var urlMatch = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@\/]*):?([^:@\/]*))?@)?(\[[a-zA-Z0-9:.%]+\]|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(url);
            each$d(queryParts, function(v2, i2) {
              var part = urlMatch[i2];
              if (part) {
                part = part.replace(/\(mce_at\)/g, "@@");
              }
              self2[v2] = part;
            });
            if (baseUri) {
              if (!self2.protocol) {
                self2.protocol = baseUri.protocol;
              }
              if (!self2.userInfo) {
                self2.userInfo = baseUri.userInfo;
              }
              if (!self2.port && self2.host === "mce_host") {
                self2.port = baseUri.port;
              }
              if (!self2.host || self2.host === "mce_host") {
                self2.host = baseUri.host;
              }
              self2.source = "";
            }
            if (isProtocolRelative) {
              self2.protocol = "";
            }
          }
          URI2.parseDataUri = function(uri) {
            var type2;
            var uriComponents = decodeURIComponent(uri).split(",");
            var matches2 = /data:([^;]+)/.exec(uriComponents[0]);
            if (matches2) {
              type2 = matches2[1];
            }
            return {
              type: type2,
              data: uriComponents[1]
            };
          };
          URI2.isDomSafe = function(uri, context2, options) {
            if (options === void 0) {
              options = {};
            }
            if (options.allow_script_urls) {
              return true;
            } else {
              var decodedUri = Entities.decode(uri).replace(/[\s\u0000-\u001F]+/g, "");
              try {
                decodedUri = decodeURIComponent(decodedUri);
              } catch (ex) {
                decodedUri = unescape(decodedUri);
              }
              if (/((java|vb)script|mhtml):/i.test(decodedUri)) {
                return false;
              }
              return !isInvalidUri(options, decodedUri, context2);
            }
          };
          URI2.getDocumentBaseUrl = function(loc) {
            var baseUrl;
            if (loc.protocol.indexOf("http") !== 0 && loc.protocol !== "file:") {
              baseUrl = loc.href;
            } else {
              baseUrl = loc.protocol + "//" + loc.host + loc.pathname;
            }
            if (/^[^:]+:\/\/\/?[^\/]+\//.test(baseUrl)) {
              baseUrl = baseUrl.replace(/[\?#].*$/, "").replace(/[\/\\][^\/]+$/, "");
              if (!/[\/\\]$/.test(baseUrl)) {
                baseUrl += "/";
              }
            }
            return baseUrl;
          };
          URI2.prototype.setPath = function(path) {
            var pathMatch = /^(.*?)\/?(\w+)?$/.exec(path);
            this.path = pathMatch[0];
            this.directory = pathMatch[1];
            this.file = pathMatch[2];
            this.source = "";
            this.getURI();
          };
          URI2.prototype.toRelative = function(uri) {
            var output;
            if (uri === "./") {
              return uri;
            }
            var relativeUri = new URI2(uri, { base_uri: this });
            if (relativeUri.host !== "mce_host" && this.host !== relativeUri.host && relativeUri.host || this.port !== relativeUri.port || this.protocol !== relativeUri.protocol && relativeUri.protocol !== "") {
              return relativeUri.getURI();
            }
            var tu = this.getURI(), uu = relativeUri.getURI();
            if (tu === uu || tu.charAt(tu.length - 1) === "/" && tu.substr(0, tu.length - 1) === uu) {
              return tu;
            }
            output = this.toRelPath(this.path, relativeUri.path);
            if (relativeUri.query) {
              output += "?" + relativeUri.query;
            }
            if (relativeUri.anchor) {
              output += "#" + relativeUri.anchor;
            }
            return output;
          };
          URI2.prototype.toAbsolute = function(uri, noHost) {
            var absoluteUri = new URI2(uri, { base_uri: this });
            return absoluteUri.getURI(noHost && this.isSameOrigin(absoluteUri));
          };
          URI2.prototype.isSameOrigin = function(uri) {
            if (this.host == uri.host && this.protocol == uri.protocol) {
              if (this.port == uri.port) {
                return true;
              }
              var defaultPort = DEFAULT_PORTS[this.protocol];
              if (defaultPort && (this.port || defaultPort) == (uri.port || defaultPort)) {
                return true;
              }
            }
            return false;
          };
          URI2.prototype.toRelPath = function(base, path) {
            var breakPoint = 0, out = "", i2, l2;
            var normalizedBase = base.substring(0, base.lastIndexOf("/")).split("/");
            var items = path.split("/");
            if (normalizedBase.length >= items.length) {
              for (i2 = 0, l2 = normalizedBase.length; i2 < l2; i2++) {
                if (i2 >= items.length || normalizedBase[i2] !== items[i2]) {
                  breakPoint = i2 + 1;
                  break;
                }
              }
            }
            if (normalizedBase.length < items.length) {
              for (i2 = 0, l2 = items.length; i2 < l2; i2++) {
                if (i2 >= normalizedBase.length || normalizedBase[i2] !== items[i2]) {
                  breakPoint = i2 + 1;
                  break;
                }
              }
            }
            if (breakPoint === 1) {
              return path;
            }
            for (i2 = 0, l2 = normalizedBase.length - (breakPoint - 1); i2 < l2; i2++) {
              out += "../";
            }
            for (i2 = breakPoint - 1, l2 = items.length; i2 < l2; i2++) {
              if (i2 !== breakPoint - 1) {
                out += "/" + items[i2];
              } else {
                out += items[i2];
              }
            }
            return out;
          };
          URI2.prototype.toAbsPath = function(base, path) {
            var i2, nb = 0, o2 = [], outPath;
            var tr = /\/$/.test(path) ? "/" : "";
            var normalizedBase = base.split("/");
            var normalizedPath = path.split("/");
            each$d(normalizedBase, function(k2) {
              if (k2) {
                o2.push(k2);
              }
            });
            normalizedBase = o2;
            for (i2 = normalizedPath.length - 1, o2 = []; i2 >= 0; i2--) {
              if (normalizedPath[i2].length === 0 || normalizedPath[i2] === ".") {
                continue;
              }
              if (normalizedPath[i2] === "..") {
                nb++;
                continue;
              }
              if (nb > 0) {
                nb--;
                continue;
              }
              o2.push(normalizedPath[i2]);
            }
            i2 = normalizedBase.length - nb;
            if (i2 <= 0) {
              outPath = reverse(o2).join("/");
            } else {
              outPath = normalizedBase.slice(0, i2).join("/") + "/" + reverse(o2).join("/");
            }
            if (outPath.indexOf("/") !== 0) {
              outPath = "/" + outPath;
            }
            if (tr && outPath.lastIndexOf("/") !== outPath.length - 1) {
              outPath += tr;
            }
            return outPath;
          };
          URI2.prototype.getURI = function(noProtoHost) {
            if (noProtoHost === void 0) {
              noProtoHost = false;
            }
            var s2;
            if (!this.source || noProtoHost) {
              s2 = "";
              if (!noProtoHost) {
                if (this.protocol) {
                  s2 += this.protocol + "://";
                } else {
                  s2 += "//";
                }
                if (this.userInfo) {
                  s2 += this.userInfo + "@";
                }
                if (this.host) {
                  s2 += this.host;
                }
                if (this.port) {
                  s2 += ":" + this.port;
                }
              }
              if (this.path) {
                s2 += this.path;
              }
              if (this.query) {
                s2 += "?" + this.query;
              }
              if (this.anchor) {
                s2 += "#" + this.anchor;
              }
              this.source = s2;
            }
            return this.source;
          };
          return URI2;
        }();
        var filteredClobberElements = Tools.makeMap("button,fieldset,form,iframe,img,image,input,object,output,select,textarea");
        var isValidPrefixAttrName = function(name2) {
          return name2.indexOf("data-") === 0 || name2.indexOf("aria-") === 0;
        };
        var findMatchingEndTagIndex = function(schema, html, startIndex) {
          var startTagRegExp = /<([!?\/])?([A-Za-z0-9\-_:.]+)/g;
          var endTagRegExp = /(?:\s(?:[^'">]+(?:"[^"]*"|'[^']*'))*[^"'>]*(?:"[^">]*|'[^'>]*)?|\s*|\/)>/g;
          var shortEndedElements = schema.getShortEndedElements();
          var count2 = 1, index = startIndex;
          while (count2 !== 0) {
            startTagRegExp.lastIndex = index;
            while (true) {
              var startMatch = startTagRegExp.exec(html);
              if (startMatch === null) {
                return index;
              } else if (startMatch[1] === "!") {
                if (startsWith(startMatch[2], "--")) {
                  index = findCommentEndIndex(html, false, startMatch.index + "!--".length);
                } else {
                  index = findCommentEndIndex(html, true, startMatch.index + 1);
                }
                break;
              } else {
                endTagRegExp.lastIndex = startTagRegExp.lastIndex;
                var endMatch = endTagRegExp.exec(html);
                if (isNull(endMatch) || endMatch.index !== startTagRegExp.lastIndex) {
                  continue;
                }
                if (startMatch[1] === "/") {
                  count2 -= 1;
                } else if (!has$2(shortEndedElements, startMatch[2])) {
                  count2 += 1;
                }
                index = startTagRegExp.lastIndex + endMatch[0].length;
                break;
              }
            }
          }
          return index;
        };
        var isConditionalComment = function(html, startIndex) {
          return /^\s*\[if [\w\W]+\]>.*<!\[endif\](--!?)?>/.test(html.substr(startIndex));
        };
        var findCommentEndIndex = function(html, isBogus2, startIndex) {
          if (startIndex === void 0) {
            startIndex = 0;
          }
          var lcHtml = html.toLowerCase();
          if (lcHtml.indexOf("[if ", startIndex) !== -1 && isConditionalComment(lcHtml, startIndex)) {
            var endIfIndex = lcHtml.indexOf("[endif]", startIndex);
            return lcHtml.indexOf(">", endIfIndex);
          } else {
            if (isBogus2) {
              var endIndex = lcHtml.indexOf(">", startIndex);
              return endIndex !== -1 ? endIndex : lcHtml.length;
            } else {
              var endCommentRegexp = /--!?>/g;
              endCommentRegexp.lastIndex = startIndex;
              var match3 = endCommentRegexp.exec(html);
              return match3 ? match3.index + match3[0].length : lcHtml.length;
            }
          }
        };
        var checkBogusAttribute = function(regExp, attrString) {
          var matches2 = regExp.exec(attrString);
          if (matches2) {
            var name_1 = matches2[1];
            var value2 = matches2[2];
            return typeof name_1 === "string" && name_1.toLowerCase() === "data-mce-bogus" ? value2 : null;
          } else {
            return null;
          }
        };
        var SaxParser = function(settings, schema) {
          var _a;
          if (schema === void 0) {
            schema = Schema();
          }
          settings = settings || {};
          var doc2 = (_a = settings.document) !== null && _a !== void 0 ? _a : document;
          var form = doc2.createElement("form");
          if (settings.fix_self_closing !== false) {
            settings.fix_self_closing = true;
          }
          var comment = settings.comment ? settings.comment : noop3;
          var cdata = settings.cdata ? settings.cdata : noop3;
          var text = settings.text ? settings.text : noop3;
          var start5 = settings.start ? settings.start : noop3;
          var end3 = settings.end ? settings.end : noop3;
          var pi2 = settings.pi ? settings.pi : noop3;
          var doctype = settings.doctype ? settings.doctype : noop3;
          var parseInternal = function(base64Extract, format3) {
            if (format3 === void 0) {
              format3 = "html";
            }
            var html = base64Extract.html;
            var matches2, index = 0, value2, endRegExp;
            var stack = [];
            var attrList, i2, textData, name2;
            var isInternalElement, isShortEnded;
            var elementRule, isValidElement, attr, attribsValue, validAttributesMap, validAttributePatterns;
            var attributesRequired, attributesDefault, attributesForced;
            var anyAttributesRequired, attrValue, idCount = 0;
            var decode2 = Entities.decode;
            var filteredUrlAttrs = Tools.makeMap("src,href,data,background,action,formaction,poster,xlink:href");
            var parsingMode = format3 === "html" ? 0 : 1;
            var processEndTag = function(name3) {
              var pos, i3;
              pos = stack.length;
              while (pos--) {
                if (stack[pos].name === name3) {
                  break;
                }
              }
              if (pos >= 0) {
                for (i3 = stack.length - 1; i3 >= pos; i3--) {
                  name3 = stack[i3];
                  if (name3.valid) {
                    end3(name3.name);
                  }
                }
                stack.length = pos;
              }
            };
            var processText = function(value3, raw) {
              return text(restoreDataUris(value3, base64Extract), raw);
            };
            var processComment = function(value3) {
              if (value3 === "") {
                return;
              }
              if (value3.charAt(0) === ">") {
                value3 = " " + value3;
              }
              if (!settings.allow_conditional_comments && value3.substr(0, 3).toLowerCase() === "[if") {
                value3 = " " + value3;
              }
              comment(restoreDataUris(value3, base64Extract));
            };
            var processAttr = function(value3) {
              return restoreDataUris(value3, base64Extract);
            };
            var processMalformedComment = function(value3, startIndex) {
              var startTag = value3 || "";
              var isBogus2 = !startsWith(startTag, "--");
              var endIndex = findCommentEndIndex(html, isBogus2, startIndex);
              value3 = html.substr(startIndex, endIndex - startIndex);
              processComment(isBogus2 ? startTag + value3 : value3);
              return endIndex + 1;
            };
            var parseAttribute = function(tagName, name3, value3, val2, val3) {
              name3 = name3.toLowerCase();
              value3 = processAttr(name3 in fillAttrsMap ? name3 : decode2(value3 || val2 || val3 || ""));
              if (validate2 && !isInternalElement && isValidPrefixAttrName(name3) === false) {
                var attrRule = validAttributesMap[name3];
                if (!attrRule && validAttributePatterns) {
                  var i_1 = validAttributePatterns.length;
                  while (i_1--) {
                    attrRule = validAttributePatterns[i_1];
                    if (attrRule.pattern.test(name3)) {
                      break;
                    }
                  }
                  if (i_1 === -1) {
                    attrRule = null;
                  }
                }
                if (!attrRule) {
                  return;
                }
                if (attrRule.validValues && !(value3 in attrRule.validValues)) {
                  return;
                }
              }
              var isNameOrId = name3 === "name" || name3 === "id";
              if (isNameOrId && tagName in filteredClobberElements && (value3 in doc2 || value3 in form)) {
                return;
              }
              if (filteredUrlAttrs[name3] && !URI.isDomSafe(value3, tagName, settings)) {
                return;
              }
              if (isInternalElement && (name3 in filteredUrlAttrs || name3.indexOf("on") === 0)) {
                return;
              }
              attrList.map[name3] = value3;
              attrList.push({
                name: name3,
                value: value3
              });
            };
            var tokenRegExp = new RegExp(`<(?:(?:!--([\\w\\W]*?)--!?>)|(?:!\\[CDATA\\[([\\w\\W]*?)\\]\\]>)|(?:![Dd][Oo][Cc][Tt][Yy][Pp][Ee]([\\w\\W]*?)>)|(?:!(--)?)|(?:\\?([^\\s\\/<>]+) ?([\\w\\W]*?)[?/]>)|(?:\\/([A-Za-z][A-Za-z0-9\\-_\\:\\.]*)>)|(?:([A-Za-z][A-Za-z0-9\\-_:.]*)(\\s(?:[^'">]+(?:"[^"]*"|'[^']*'))*[^"'>]*(?:"[^">]*|'[^'>]*)?|\\s*|\\/)>))`, "g");
            var attrRegExp = /([\w:\-]+)(?:\s*=\s*(?:(?:\"((?:[^\"])*)\")|(?:\'((?:[^\'])*)\')|([^>\s]+)))?/g;
            var shortEndedElements = schema.getShortEndedElements();
            var selfClosing = settings.self_closing_elements || schema.getSelfClosingElements();
            var fillAttrsMap = schema.getBoolAttrs();
            var validate2 = settings.validate;
            var removeInternalElements = settings.remove_internals;
            var fixSelfClosing = settings.fix_self_closing;
            var specialElements = schema.getSpecialElements();
            var processHtml = html + ">";
            while (matches2 = tokenRegExp.exec(processHtml)) {
              var matchText = matches2[0];
              if (index < matches2.index) {
                processText(decode2(html.substr(index, matches2.index - index)));
              }
              if (value2 = matches2[7]) {
                value2 = value2.toLowerCase();
                if (value2.charAt(0) === ":") {
                  value2 = value2.substr(1);
                }
                processEndTag(value2);
              } else if (value2 = matches2[8]) {
                if (matches2.index + matchText.length > html.length) {
                  processText(decode2(html.substr(matches2.index)));
                  index = matches2.index + matchText.length;
                  continue;
                }
                value2 = value2.toLowerCase();
                if (value2.charAt(0) === ":") {
                  value2 = value2.substr(1);
                }
                isShortEnded = value2 in shortEndedElements;
                if (fixSelfClosing && selfClosing[value2] && stack.length > 0 && stack[stack.length - 1].name === value2) {
                  processEndTag(value2);
                }
                var bogusValue = checkBogusAttribute(attrRegExp, matches2[9]);
                if (bogusValue !== null) {
                  if (bogusValue === "all") {
                    index = findMatchingEndTagIndex(schema, html, tokenRegExp.lastIndex);
                    tokenRegExp.lastIndex = index;
                    continue;
                  }
                  isValidElement = false;
                }
                if (!validate2 || (elementRule = schema.getElementRule(value2))) {
                  isValidElement = true;
                  if (validate2) {
                    validAttributesMap = elementRule.attributes;
                    validAttributePatterns = elementRule.attributePatterns;
                  }
                  if (attribsValue = matches2[9]) {
                    isInternalElement = attribsValue.indexOf("data-mce-type") !== -1;
                    if (isInternalElement && removeInternalElements) {
                      isValidElement = false;
                    }
                    attrList = [];
                    attrList.map = {};
                    attribsValue.replace(attrRegExp, function(match3, name3, val, val2, val3) {
                      parseAttribute(value2, name3, val, val2, val3);
                      return "";
                    });
                  } else {
                    attrList = [];
                    attrList.map = {};
                  }
                  if (validate2 && !isInternalElement) {
                    attributesRequired = elementRule.attributesRequired;
                    attributesDefault = elementRule.attributesDefault;
                    attributesForced = elementRule.attributesForced;
                    anyAttributesRequired = elementRule.removeEmptyAttrs;
                    if (anyAttributesRequired && !attrList.length) {
                      isValidElement = false;
                    }
                    if (attributesForced) {
                      i2 = attributesForced.length;
                      while (i2--) {
                        attr = attributesForced[i2];
                        name2 = attr.name;
                        attrValue = attr.value;
                        if (attrValue === "{$uid}") {
                          attrValue = "mce_" + idCount++;
                        }
                        attrList.map[name2] = attrValue;
                        attrList.push({
                          name: name2,
                          value: attrValue
                        });
                      }
                    }
                    if (attributesDefault) {
                      i2 = attributesDefault.length;
                      while (i2--) {
                        attr = attributesDefault[i2];
                        name2 = attr.name;
                        if (!(name2 in attrList.map)) {
                          attrValue = attr.value;
                          if (attrValue === "{$uid}") {
                            attrValue = "mce_" + idCount++;
                          }
                          attrList.map[name2] = attrValue;
                          attrList.push({
                            name: name2,
                            value: attrValue
                          });
                        }
                      }
                    }
                    if (attributesRequired) {
                      i2 = attributesRequired.length;
                      while (i2--) {
                        if (attributesRequired[i2] in attrList.map) {
                          break;
                        }
                      }
                      if (i2 === -1) {
                        isValidElement = false;
                      }
                    }
                    if (attr = attrList.map["data-mce-bogus"]) {
                      if (attr === "all") {
                        index = findMatchingEndTagIndex(schema, html, tokenRegExp.lastIndex);
                        tokenRegExp.lastIndex = index;
                        continue;
                      }
                      isValidElement = false;
                    }
                  }
                  if (isValidElement) {
                    start5(value2, attrList, isShortEnded);
                  }
                } else {
                  isValidElement = false;
                }
                if (endRegExp = specialElements[value2]) {
                  endRegExp.lastIndex = index = matches2.index + matchText.length;
                  if (matches2 = endRegExp.exec(html)) {
                    if (isValidElement) {
                      textData = html.substr(index, matches2.index - index);
                    }
                    index = matches2.index + matches2[0].length;
                  } else {
                    textData = html.substr(index);
                    index = html.length;
                  }
                  if (isValidElement) {
                    if (textData.length > 0) {
                      processText(textData, true);
                    }
                    end3(value2);
                  }
                  tokenRegExp.lastIndex = index;
                  continue;
                }
                if (!isShortEnded) {
                  if (!attribsValue || attribsValue.indexOf("/") !== attribsValue.length - 1) {
                    stack.push({
                      name: value2,
                      valid: isValidElement
                    });
                  } else if (isValidElement) {
                    end3(value2);
                  }
                }
              } else if (value2 = matches2[1]) {
                processComment(value2);
              } else if (value2 = matches2[2]) {
                var isValidCdataSection = parsingMode === 1 || settings.preserve_cdata || stack.length > 0 && schema.isValidChild(stack[stack.length - 1].name, "#cdata");
                if (isValidCdataSection) {
                  cdata(value2);
                } else {
                  index = processMalformedComment("", matches2.index + 2);
                  tokenRegExp.lastIndex = index;
                  continue;
                }
              } else if (value2 = matches2[3]) {
                doctype(value2);
              } else if ((value2 = matches2[4]) || matchText === "<!") {
                index = processMalformedComment(value2, matches2.index + matchText.length);
                tokenRegExp.lastIndex = index;
                continue;
              } else if (value2 = matches2[5]) {
                if (parsingMode === 1) {
                  pi2(value2, matches2[6]);
                } else {
                  index = processMalformedComment("?", matches2.index + 2);
                  tokenRegExp.lastIndex = index;
                  continue;
                }
              }
              index = matches2.index + matchText.length;
            }
            if (index < html.length) {
              processText(decode2(html.substr(index)));
            }
            for (i2 = stack.length - 1; i2 >= 0; i2--) {
              value2 = stack[i2];
              if (value2.valid) {
                end3(value2.name);
              }
            }
          };
          var parse3 = function(html, format3) {
            if (format3 === void 0) {
              format3 = "html";
            }
            parseInternal(extractBase64DataUris(html), format3);
          };
          return { parse: parse3 };
        };
        SaxParser.findEndTag = findMatchingEndTagIndex;
        var trimHtml = function(tempAttrs, html) {
          var trimContentRegExp = new RegExp(["\\s?(" + tempAttrs.join("|") + ')="[^"]+"'].join("|"), "gi");
          return html.replace(trimContentRegExp, "");
        };
        var trimInternal = function(serializer, html) {
          var bogusAllRegExp = /<(\w+) [^>]*data-mce-bogus="all"[^>]*>/g;
          var schema = serializer.schema;
          var content = trimHtml(serializer.getTempAttrs(), html);
          var shortEndedElements = schema.getShortEndedElements();
          var matches2;
          while (matches2 = bogusAllRegExp.exec(content)) {
            var index = bogusAllRegExp.lastIndex;
            var matchLength = matches2[0].length;
            var endTagIndex = void 0;
            if (shortEndedElements[matches2[1]]) {
              endTagIndex = index;
            } else {
              endTagIndex = SaxParser.findEndTag(schema, content, index);
            }
            content = content.substring(0, index - matchLength) + content.substring(endTagIndex);
            bogusAllRegExp.lastIndex = index - matchLength;
          }
          return trim$2(content);
        };
        var trimExternal = trimInternal;
        var trimEmptyContents = function(editor, html) {
          var blockName = getForcedRootBlock(editor);
          var emptyRegExp = new RegExp("^(<" + blockName + "[^>]*>(&nbsp;|&#160;|\\s|\xA0|<br \\/>|)<\\/" + blockName + ">[\r\n]*|<br \\/>[\r\n]*)$");
          return html.replace(emptyRegExp, "");
        };
        var setupArgs$3 = function(args, format3) {
          return __assign(__assign({}, args), {
            format: format3,
            get: true,
            getInner: true
          });
        };
        var getContentFromBody = function(editor, args, format3, body) {
          var defaultedArgs = setupArgs$3(args, format3);
          var updatedArgs = args.no_events ? defaultedArgs : editor.fire("BeforeGetContent", defaultedArgs);
          var content;
          if (updatedArgs.format === "raw") {
            content = Tools.trim(trimExternal(editor.serializer, body.innerHTML));
          } else if (updatedArgs.format === "text") {
            content = editor.dom.isEmpty(body) ? "" : trim$2(body.innerText || body.textContent);
          } else if (updatedArgs.format === "tree") {
            content = editor.serializer.serialize(body, updatedArgs);
          } else {
            content = trimEmptyContents(editor, editor.serializer.serialize(body, updatedArgs));
          }
          if (!contains$3([
            "text",
            "tree"
          ], updatedArgs.format) && !isWsPreserveElement(SugarElement.fromDom(body))) {
            updatedArgs.content = Tools.trim(content);
          } else {
            updatedArgs.content = content;
          }
          if (updatedArgs.no_events) {
            return updatedArgs.content;
          } else {
            return editor.fire("GetContent", updatedArgs).content;
          }
        };
        var getContentInternal = function(editor, args, format3) {
          return Optional.from(editor.getBody()).fold(constant(args.format === "tree" ? new AstNode("body", 11) : ""), function(body) {
            return getContentFromBody(editor, args, format3, body);
          });
        };
        var each$c = Tools.each;
        var ElementUtils = function(dom2) {
          var compare = function(node1, node2) {
            if (node1.nodeName !== node2.nodeName) {
              return false;
            }
            var getAttribs = function(node) {
              var attribs = {};
              each$c(dom2.getAttribs(node), function(attr) {
                var name2 = attr.nodeName.toLowerCase();
                if (name2.indexOf("_") !== 0 && name2 !== "style" && name2.indexOf("data-") !== 0) {
                  attribs[name2] = dom2.getAttrib(node, name2);
                }
              });
              return attribs;
            };
            var compareObjects = function(obj1, obj2) {
              var value2, name2;
              for (name2 in obj1) {
                if (has$2(obj1, name2)) {
                  value2 = obj2[name2];
                  if (typeof value2 === "undefined") {
                    return false;
                  }
                  if (obj1[name2] !== value2) {
                    return false;
                  }
                  delete obj2[name2];
                }
              }
              for (name2 in obj2) {
                if (has$2(obj2, name2)) {
                  return false;
                }
              }
              return true;
            };
            if (!compareObjects(getAttribs(node1), getAttribs(node2))) {
              return false;
            }
            if (!compareObjects(dom2.parseStyle(dom2.getAttrib(node1, "style")), dom2.parseStyle(dom2.getAttrib(node2, "style")))) {
              return false;
            }
            return !isBookmarkNode$1(node1) && !isBookmarkNode$1(node2);
          };
          return { compare };
        };
        var makeMap$1 = Tools.makeMap;
        var Writer = function(settings) {
          var html = [];
          settings = settings || {};
          var indent = settings.indent;
          var indentBefore = makeMap$1(settings.indent_before || "");
          var indentAfter = makeMap$1(settings.indent_after || "");
          var encode = Entities.getEncodeFunc(settings.entity_encoding || "raw", settings.entities);
          var htmlOutput = settings.element_format === "html";
          return {
            start: function(name2, attrs, empty2) {
              var i2, l2, attr, value2;
              if (indent && indentBefore[name2] && html.length > 0) {
                value2 = html[html.length - 1];
                if (value2.length > 0 && value2 !== "\n") {
                  html.push("\n");
                }
              }
              html.push("<", name2);
              if (attrs) {
                for (i2 = 0, l2 = attrs.length; i2 < l2; i2++) {
                  attr = attrs[i2];
                  html.push(" ", attr.name, '="', encode(attr.value, true), '"');
                }
              }
              if (!empty2 || htmlOutput) {
                html[html.length] = ">";
              } else {
                html[html.length] = " />";
              }
              if (empty2 && indent && indentAfter[name2] && html.length > 0) {
                value2 = html[html.length - 1];
                if (value2.length > 0 && value2 !== "\n") {
                  html.push("\n");
                }
              }
            },
            end: function(name2) {
              var value2;
              html.push("</", name2, ">");
              if (indent && indentAfter[name2] && html.length > 0) {
                value2 = html[html.length - 1];
                if (value2.length > 0 && value2 !== "\n") {
                  html.push("\n");
                }
              }
            },
            text: function(text, raw) {
              if (text.length > 0) {
                html[html.length] = raw ? text : encode(text);
              }
            },
            cdata: function(text) {
              html.push("<![CDATA[", text, "]]>");
            },
            comment: function(text) {
              html.push("<!--", text, "-->");
            },
            pi: function(name2, text) {
              if (text) {
                html.push("<?", name2, " ", encode(text), "?>");
              } else {
                html.push("<?", name2, "?>");
              }
              if (indent) {
                html.push("\n");
              }
            },
            doctype: function(text) {
              html.push("<!DOCTYPE", text, ">", indent ? "\n" : "");
            },
            reset: function() {
              html.length = 0;
            },
            getContent: function() {
              return html.join("").replace(/\n$/, "");
            }
          };
        };
        var HtmlSerializer = function(settings, schema) {
          if (schema === void 0) {
            schema = Schema();
          }
          var writer = Writer(settings);
          settings = settings || {};
          settings.validate = "validate" in settings ? settings.validate : true;
          var serialize2 = function(node) {
            var validate2 = settings.validate;
            var handlers = {
              3: function(node2) {
                writer.text(node2.value, node2.raw);
              },
              8: function(node2) {
                writer.comment(node2.value);
              },
              7: function(node2) {
                writer.pi(node2.name, node2.value);
              },
              10: function(node2) {
                writer.doctype(node2.value);
              },
              4: function(node2) {
                writer.cdata(node2.value);
              },
              11: function(node2) {
                if (node2 = node2.firstChild) {
                  do {
                    walk3(node2);
                  } while (node2 = node2.next);
                }
              }
            };
            writer.reset();
            var walk3 = function(node2) {
              var handler = handlers[node2.type];
              if (!handler) {
                var name_1 = node2.name;
                var isEmpty2 = node2.shortEnded;
                var attrs = node2.attributes;
                if (validate2 && attrs && attrs.length > 1) {
                  var sortedAttrs = [];
                  sortedAttrs.map = {};
                  var elementRule = schema.getElementRule(node2.name);
                  if (elementRule) {
                    for (var i2 = 0, l2 = elementRule.attributesOrder.length; i2 < l2; i2++) {
                      var attrName = elementRule.attributesOrder[i2];
                      if (attrName in attrs.map) {
                        var attrValue = attrs.map[attrName];
                        sortedAttrs.map[attrName] = attrValue;
                        sortedAttrs.push({
                          name: attrName,
                          value: attrValue
                        });
                      }
                    }
                    for (var i2 = 0, l2 = attrs.length; i2 < l2; i2++) {
                      var attrName = attrs[i2].name;
                      if (!(attrName in sortedAttrs.map)) {
                        var attrValue = attrs.map[attrName];
                        sortedAttrs.map[attrName] = attrValue;
                        sortedAttrs.push({
                          name: attrName,
                          value: attrValue
                        });
                      }
                    }
                    attrs = sortedAttrs;
                  }
                }
                writer.start(node2.name, attrs, isEmpty2);
                if (!isEmpty2) {
                  if (node2 = node2.firstChild) {
                    do {
                      walk3(node2);
                    } while (node2 = node2.next);
                  }
                  writer.end(name_1);
                }
              } else {
                handler(node2);
              }
            };
            if (node.type === 1 && !settings.inner) {
              walk3(node);
            } else {
              handlers[11](node);
            }
            return writer.getContent();
          };
          return { serialize: serialize2 };
        };
        var nonInheritableStyles = /* @__PURE__ */ new Set();
        (function() {
          var nonInheritableStylesArr = [
            "margin",
            "margin-left",
            "margin-right",
            "margin-top",
            "margin-bottom",
            "padding",
            "padding-left",
            "padding-right",
            "padding-top",
            "padding-bottom",
            "border",
            "border-width",
            "border-style",
            "border-color",
            "background",
            "background-attachment",
            "background-clip",
            "background-color",
            "background-image",
            "background-origin",
            "background-position",
            "background-repeat",
            "background-size",
            "float",
            "position",
            "left",
            "right",
            "top",
            "bottom",
            "z-index",
            "display",
            "transform",
            "width",
            "max-width",
            "min-width",
            "height",
            "max-height",
            "min-height",
            "overflow",
            "overflow-x",
            "overflow-y",
            "text-overflow",
            "vertical-align",
            "transition",
            "transition-delay",
            "transition-duration",
            "transition-property",
            "transition-timing-function"
          ];
          each$k(nonInheritableStylesArr, function(style) {
            nonInheritableStyles.add(style);
          });
        })();
        var shorthandStyleProps = [
          "font",
          "text-decoration",
          "text-emphasis"
        ];
        var getStyleProps = function(dom2, node) {
          return keys(dom2.parseStyle(dom2.getAttrib(node, "style")));
        };
        var isNonInheritableStyle = function(style) {
          return nonInheritableStyles.has(style);
        };
        var hasInheritableStyles = function(dom2, node) {
          return forall(getStyleProps(dom2, node), function(style) {
            return !isNonInheritableStyle(style);
          });
        };
        var getLonghandStyleProps = function(styles) {
          return filter$4(styles, function(style) {
            return exists(shorthandStyleProps, function(prop) {
              return startsWith(style, prop);
            });
          });
        };
        var hasStyleConflict = function(dom2, node, parentNode) {
          var nodeStyleProps = getStyleProps(dom2, node);
          var parentNodeStyleProps = getStyleProps(dom2, parentNode);
          var valueMismatch = function(prop) {
            var nodeValue = dom2.getStyle(node, prop);
            var parentValue = dom2.getStyle(parentNode, prop);
            return isNotEmpty(nodeValue) && isNotEmpty(parentValue) && nodeValue !== parentValue;
          };
          return exists(nodeStyleProps, function(nodeStyleProp) {
            var propExists = function(props) {
              return exists(props, function(prop) {
                return prop === nodeStyleProp;
              });
            };
            if (!propExists(parentNodeStyleProps) && propExists(shorthandStyleProps)) {
              var longhandProps = getLonghandStyleProps(parentNodeStyleProps);
              return exists(longhandProps, valueMismatch);
            } else {
              return valueMismatch(nodeStyleProp);
            }
          });
        };
        var isChar = function(forward, predicate, pos) {
          return Optional.from(pos.container()).filter(isText$7).exists(function(text) {
            var delta = forward ? 0 : -1;
            return predicate(text.data.charAt(pos.offset() + delta));
          });
        };
        var isBeforeSpace = curry(isChar, true, isWhiteSpace);
        var isAfterSpace = curry(isChar, false, isWhiteSpace);
        var isEmptyText = function(pos) {
          var container = pos.container();
          return isText$7(container) && (container.data.length === 0 || isZwsp(container.data) && BookmarkManager.isBookmarkNode(container.parentNode));
        };
        var matchesElementPosition = function(before2, predicate) {
          return function(pos) {
            return Optional.from(getChildNodeAtRelativeOffset(before2 ? 0 : -1, pos)).filter(predicate).isSome();
          };
        };
        var isImageBlock = function(node) {
          return isImg(node) && get$5(SugarElement.fromDom(node), "display") === "block";
        };
        var isCefNode = function(node) {
          return isContentEditableFalse$b(node) && !isBogusAll$1(node);
        };
        var isBeforeImageBlock = matchesElementPosition(true, isImageBlock);
        var isAfterImageBlock = matchesElementPosition(false, isImageBlock);
        var isBeforeMedia = matchesElementPosition(true, isMedia$2);
        var isAfterMedia = matchesElementPosition(false, isMedia$2);
        var isBeforeTable = matchesElementPosition(true, isTable$3);
        var isAfterTable = matchesElementPosition(false, isTable$3);
        var isBeforeContentEditableFalse = matchesElementPosition(true, isCefNode);
        var isAfterContentEditableFalse = matchesElementPosition(false, isCefNode);
        var getLastChildren = function(elm) {
          var children2 = [];
          var rawNode = elm.dom;
          while (rawNode) {
            children2.push(SugarElement.fromDom(rawNode));
            rawNode = rawNode.lastChild;
          }
          return children2;
        };
        var removeTrailingBr = function(elm) {
          var allBrs = descendants(elm, "br");
          var brs = filter$4(getLastChildren(elm).slice(-1), isBr$4);
          if (allBrs.length === brs.length) {
            each$k(brs, remove$7);
          }
        };
        var fillWithPaddingBr = function(elm) {
          empty(elm);
          append$1(elm, SugarElement.fromHtml('<br data-mce-bogus="1">'));
        };
        var trimBlockTrailingBr = function(elm) {
          lastChild(elm).each(function(lastChild2) {
            prevSibling(lastChild2).each(function(lastChildPrevSibling) {
              if (isBlock$2(elm) && isBr$4(lastChild2) && isBlock$2(lastChildPrevSibling)) {
                remove$7(lastChild2);
              }
            });
          });
        };
        var dropLast = function(xs) {
          return xs.slice(0, -1);
        };
        var parentsUntil = function(start5, root, predicate) {
          if (contains$1(root, start5)) {
            return dropLast(parents$1(start5, function(elm) {
              return predicate(elm) || eq2(elm, root);
            }));
          } else {
            return [];
          }
        };
        var parents = function(start5, root) {
          return parentsUntil(start5, root, never);
        };
        var parentsAndSelf = function(start5, root) {
          return [start5].concat(parents(start5, root));
        };
        var navigateIgnoreEmptyTextNodes = function(forward, root, from2) {
          return navigateIgnore(forward, root, from2, isEmptyText);
        };
        var getClosestBlock$1 = function(root, pos) {
          return find$3(parentsAndSelf(SugarElement.fromDom(pos.container()), root), isBlock$2);
        };
        var isAtBeforeAfterBlockBoundary = function(forward, root, pos) {
          return navigateIgnoreEmptyTextNodes(forward, root.dom, pos).forall(function(newPos) {
            return getClosestBlock$1(root, pos).fold(function() {
              return isInSameBlock(newPos, pos, root.dom) === false;
            }, function(fromBlock) {
              return isInSameBlock(newPos, pos, root.dom) === false && contains$1(fromBlock, SugarElement.fromDom(newPos.container()));
            });
          });
        };
        var isAtBlockBoundary = function(forward, root, pos) {
          return getClosestBlock$1(root, pos).fold(function() {
            return navigateIgnoreEmptyTextNodes(forward, root.dom, pos).forall(function(newPos) {
              return isInSameBlock(newPos, pos, root.dom) === false;
            });
          }, function(parent2) {
            return navigateIgnoreEmptyTextNodes(forward, parent2.dom, pos).isNone();
          });
        };
        var isAtStartOfBlock = curry(isAtBlockBoundary, false);
        var isAtEndOfBlock = curry(isAtBlockBoundary, true);
        var isBeforeBlock = curry(isAtBeforeAfterBlockBoundary, false);
        var isAfterBlock = curry(isAtBeforeAfterBlockBoundary, true);
        var isBr = function(pos) {
          return getElementFromPosition(pos).exists(isBr$4);
        };
        var findBr = function(forward, root, pos) {
          var parentBlocks = filter$4(parentsAndSelf(SugarElement.fromDom(pos.container()), root), isBlock$2);
          var scope = head(parentBlocks).getOr(root);
          return fromPosition(forward, scope.dom, pos).filter(isBr);
        };
        var isBeforeBr$1 = function(root, pos) {
          return getElementFromPosition(pos).exists(isBr$4) || findBr(true, root, pos).isSome();
        };
        var isAfterBr = function(root, pos) {
          return getElementFromPrevPosition(pos).exists(isBr$4) || findBr(false, root, pos).isSome();
        };
        var findPreviousBr = curry(findBr, false);
        var findNextBr = curry(findBr, true);
        var isInMiddleOfText = function(pos) {
          return CaretPosition.isTextPosition(pos) && !pos.isAtStart() && !pos.isAtEnd();
        };
        var getClosestBlock = function(root, pos) {
          var parentBlocks = filter$4(parentsAndSelf(SugarElement.fromDom(pos.container()), root), isBlock$2);
          return head(parentBlocks).getOr(root);
        };
        var hasSpaceBefore = function(root, pos) {
          if (isInMiddleOfText(pos)) {
            return isAfterSpace(pos);
          } else {
            return isAfterSpace(pos) || prevPosition(getClosestBlock(root, pos).dom, pos).exists(isAfterSpace);
          }
        };
        var hasSpaceAfter = function(root, pos) {
          if (isInMiddleOfText(pos)) {
            return isBeforeSpace(pos);
          } else {
            return isBeforeSpace(pos) || nextPosition(getClosestBlock(root, pos).dom, pos).exists(isBeforeSpace);
          }
        };
        var isPreValue = function(value2) {
          return contains$3([
            "pre",
            "pre-wrap"
          ], value2);
        };
        var isInPre = function(pos) {
          return getElementFromPosition(pos).bind(function(elm) {
            return closest$3(elm, isElement$6);
          }).exists(function(elm) {
            return isPreValue(get$5(elm, "white-space"));
          });
        };
        var isAtBeginningOfBody = function(root, pos) {
          return prevPosition(root.dom, pos).isNone();
        };
        var isAtEndOfBody = function(root, pos) {
          return nextPosition(root.dom, pos).isNone();
        };
        var isAtLineBoundary = function(root, pos) {
          return isAtBeginningOfBody(root, pos) || isAtEndOfBody(root, pos) || isAtStartOfBlock(root, pos) || isAtEndOfBlock(root, pos) || isAfterBr(root, pos) || isBeforeBr$1(root, pos);
        };
        var needsToHaveNbsp = function(root, pos) {
          if (isInPre(pos)) {
            return false;
          } else {
            return isAtLineBoundary(root, pos) || hasSpaceBefore(root, pos) || hasSpaceAfter(root, pos);
          }
        };
        var needsToBeNbspLeft = function(root, pos) {
          if (isInPre(pos)) {
            return false;
          } else {
            return isAtStartOfBlock(root, pos) || isBeforeBlock(root, pos) || isAfterBr(root, pos) || hasSpaceBefore(root, pos);
          }
        };
        var leanRight = function(pos) {
          var container = pos.container();
          var offset2 = pos.offset();
          if (isText$7(container) && offset2 < container.data.length) {
            return CaretPosition(container, offset2 + 1);
          } else {
            return pos;
          }
        };
        var needsToBeNbspRight = function(root, pos) {
          if (isInPre(pos)) {
            return false;
          } else {
            return isAtEndOfBlock(root, pos) || isAfterBlock(root, pos) || isBeforeBr$1(root, pos) || hasSpaceAfter(root, pos);
          }
        };
        var needsToBeNbsp = function(root, pos) {
          return needsToBeNbspLeft(root, pos) || needsToBeNbspRight(root, leanRight(pos));
        };
        var isNbspAt = function(text, offset2) {
          return isNbsp(text.charAt(offset2));
        };
        var hasNbsp = function(pos) {
          var container = pos.container();
          return isText$7(container) && contains$2(container.data, nbsp);
        };
        var normalizeNbspMiddle = function(text) {
          var chars = text.split("");
          return map$3(chars, function(chr, i2) {
            if (isNbsp(chr) && i2 > 0 && i2 < chars.length - 1 && isContent(chars[i2 - 1]) && isContent(chars[i2 + 1])) {
              return " ";
            } else {
              return chr;
            }
          }).join("");
        };
        var normalizeNbspAtStart = function(root, node) {
          var text = node.data;
          var firstPos = CaretPosition(node, 0);
          if (isNbspAt(text, 0) && !needsToBeNbsp(root, firstPos)) {
            node.data = " " + text.slice(1);
            return true;
          } else {
            return false;
          }
        };
        var normalizeNbspInMiddleOfTextNode = function(node) {
          var text = node.data;
          var newText = normalizeNbspMiddle(text);
          if (newText !== text) {
            node.data = newText;
            return true;
          } else {
            return false;
          }
        };
        var normalizeNbspAtEnd = function(root, node) {
          var text = node.data;
          var lastPos = CaretPosition(node, text.length - 1);
          if (isNbspAt(text, text.length - 1) && !needsToBeNbsp(root, lastPos)) {
            node.data = text.slice(0, -1) + " ";
            return true;
          } else {
            return false;
          }
        };
        var normalizeNbsps = function(root, pos) {
          return Optional.some(pos).filter(hasNbsp).bind(function(pos2) {
            var container = pos2.container();
            var normalized = normalizeNbspAtStart(root, container) || normalizeNbspInMiddleOfTextNode(container) || normalizeNbspAtEnd(root, container);
            return normalized ? Optional.some(pos2) : Optional.none();
          });
        };
        var normalizeNbspsInEditor = function(editor) {
          var root = SugarElement.fromDom(editor.getBody());
          if (editor.selection.isCollapsed()) {
            normalizeNbsps(root, CaretPosition.fromRangeStart(editor.selection.getRng())).each(function(pos) {
              editor.selection.setRng(pos.toRange());
            });
          }
        };
        var normalizeContent = function(content, isStartOfContent, isEndOfContent) {
          var result = foldl(content, function(acc, c2) {
            if (isWhiteSpace(c2) || isNbsp(c2)) {
              if (acc.previousCharIsSpace || acc.str === "" && isStartOfContent || acc.str.length === content.length - 1 && isEndOfContent) {
                return {
                  previousCharIsSpace: false,
                  str: acc.str + nbsp
                };
              } else {
                return {
                  previousCharIsSpace: true,
                  str: acc.str + " "
                };
              }
            } else {
              return {
                previousCharIsSpace: false,
                str: acc.str + c2
              };
            }
          }, {
            previousCharIsSpace: false,
            str: ""
          });
          return result.str;
        };
        var normalize$1 = function(node, offset2, count2) {
          if (count2 === 0) {
            return;
          }
          var elm = SugarElement.fromDom(node);
          var root = ancestor$3(elm, isBlock$2).getOr(elm);
          var whitespace2 = node.data.slice(offset2, offset2 + count2);
          var isEndOfContent = offset2 + count2 >= node.data.length && needsToBeNbspRight(root, CaretPosition(node, node.data.length));
          var isStartOfContent = offset2 === 0 && needsToBeNbspLeft(root, CaretPosition(node, 0));
          node.replaceData(offset2, count2, normalizeContent(whitespace2, isStartOfContent, isEndOfContent));
        };
        var normalizeWhitespaceAfter = function(node, offset2) {
          var content = node.data.slice(offset2);
          var whitespaceCount = content.length - lTrim(content).length;
          normalize$1(node, offset2, whitespaceCount);
        };
        var normalizeWhitespaceBefore = function(node, offset2) {
          var content = node.data.slice(0, offset2);
          var whitespaceCount = content.length - rTrim(content).length;
          normalize$1(node, offset2 - whitespaceCount, whitespaceCount);
        };
        var mergeTextNodes = function(prevNode, nextNode, normalizeWhitespace, mergeToPrev) {
          if (mergeToPrev === void 0) {
            mergeToPrev = true;
          }
          var whitespaceOffset = rTrim(prevNode.data).length;
          var newNode = mergeToPrev ? prevNode : nextNode;
          var removeNode2 = mergeToPrev ? nextNode : prevNode;
          if (mergeToPrev) {
            newNode.appendData(removeNode2.data);
          } else {
            newNode.insertData(0, removeNode2.data);
          }
          remove$7(SugarElement.fromDom(removeNode2));
          if (normalizeWhitespace) {
            normalizeWhitespaceAfter(newNode, whitespaceOffset);
          }
          return newNode;
        };
        var needsReposition = function(pos, elm) {
          var container = pos.container();
          var offset2 = pos.offset();
          return CaretPosition.isTextPosition(pos) === false && container === elm.parentNode && offset2 > CaretPosition.before(elm).offset();
        };
        var reposition = function(elm, pos) {
          return needsReposition(pos, elm) ? CaretPosition(pos.container(), pos.offset() - 1) : pos;
        };
        var beforeOrStartOf = function(node) {
          return isText$7(node) ? CaretPosition(node, 0) : CaretPosition.before(node);
        };
        var afterOrEndOf = function(node) {
          return isText$7(node) ? CaretPosition(node, node.data.length) : CaretPosition.after(node);
        };
        var getPreviousSiblingCaretPosition = function(elm) {
          if (isCaretCandidate$3(elm.previousSibling)) {
            return Optional.some(afterOrEndOf(elm.previousSibling));
          } else {
            return elm.previousSibling ? lastPositionIn(elm.previousSibling) : Optional.none();
          }
        };
        var getNextSiblingCaretPosition = function(elm) {
          if (isCaretCandidate$3(elm.nextSibling)) {
            return Optional.some(beforeOrStartOf(elm.nextSibling));
          } else {
            return elm.nextSibling ? firstPositionIn(elm.nextSibling) : Optional.none();
          }
        };
        var findCaretPositionBackwardsFromElm = function(rootElement, elm) {
          var startPosition = CaretPosition.before(elm.previousSibling ? elm.previousSibling : elm.parentNode);
          return prevPosition(rootElement, startPosition).fold(function() {
            return nextPosition(rootElement, CaretPosition.after(elm));
          }, Optional.some);
        };
        var findCaretPositionForwardsFromElm = function(rootElement, elm) {
          return nextPosition(rootElement, CaretPosition.after(elm)).fold(function() {
            return prevPosition(rootElement, CaretPosition.before(elm));
          }, Optional.some);
        };
        var findCaretPositionBackwards = function(rootElement, elm) {
          return getPreviousSiblingCaretPosition(elm).orThunk(function() {
            return getNextSiblingCaretPosition(elm);
          }).orThunk(function() {
            return findCaretPositionBackwardsFromElm(rootElement, elm);
          });
        };
        var findCaretPositionForward = function(rootElement, elm) {
          return getNextSiblingCaretPosition(elm).orThunk(function() {
            return getPreviousSiblingCaretPosition(elm);
          }).orThunk(function() {
            return findCaretPositionForwardsFromElm(rootElement, elm);
          });
        };
        var findCaretPosition = function(forward, rootElement, elm) {
          return forward ? findCaretPositionForward(rootElement, elm) : findCaretPositionBackwards(rootElement, elm);
        };
        var findCaretPosOutsideElmAfterDelete = function(forward, rootElement, elm) {
          return findCaretPosition(forward, rootElement, elm).map(curry(reposition, elm));
        };
        var setSelection$1 = function(editor, forward, pos) {
          pos.fold(function() {
            editor.focus();
          }, function(pos2) {
            editor.selection.setRng(pos2.toRange(), forward);
          });
        };
        var eqRawNode = function(rawNode) {
          return function(elm) {
            return elm.dom === rawNode;
          };
        };
        var isBlock = function(editor, elm) {
          return elm && has$2(editor.schema.getBlockElements(), name(elm));
        };
        var paddEmptyBlock = function(elm) {
          if (isEmpty$2(elm)) {
            var br = SugarElement.fromHtml('<br data-mce-bogus="1">');
            empty(elm);
            append$1(elm, br);
            return Optional.some(CaretPosition.before(br.dom));
          } else {
            return Optional.none();
          }
        };
        var deleteNormalized = function(elm, afterDeletePosOpt, normalizeWhitespace) {
          var prevTextOpt = prevSibling(elm).filter(isText$8);
          var nextTextOpt = nextSibling(elm).filter(isText$8);
          remove$7(elm);
          return lift3(prevTextOpt, nextTextOpt, afterDeletePosOpt, function(prev, next, pos) {
            var prevNode = prev.dom, nextNode = next.dom;
            var offset2 = prevNode.data.length;
            mergeTextNodes(prevNode, nextNode, normalizeWhitespace);
            return pos.container() === nextNode ? CaretPosition(prevNode, offset2) : pos;
          }).orThunk(function() {
            if (normalizeWhitespace) {
              prevTextOpt.each(function(elm2) {
                return normalizeWhitespaceBefore(elm2.dom, elm2.dom.length);
              });
              nextTextOpt.each(function(elm2) {
                return normalizeWhitespaceAfter(elm2.dom, 0);
              });
            }
            return afterDeletePosOpt;
          });
        };
        var isInlineElement = function(editor, element) {
          return has$2(editor.schema.getTextInlineElements(), name(element));
        };
        var deleteElement$2 = function(editor, forward, elm, moveCaret2) {
          if (moveCaret2 === void 0) {
            moveCaret2 = true;
          }
          var afterDeletePos = findCaretPosOutsideElmAfterDelete(forward, editor.getBody(), elm.dom);
          var parentBlock = ancestor$3(elm, curry(isBlock, editor), eqRawNode(editor.getBody()));
          var normalizedAfterDeletePos = deleteNormalized(elm, afterDeletePos, isInlineElement(editor, elm));
          if (editor.dom.isEmpty(editor.getBody())) {
            editor.setContent("");
            editor.selection.setCursorLocation();
          } else {
            parentBlock.bind(paddEmptyBlock).fold(function() {
              if (moveCaret2) {
                setSelection$1(editor, forward, normalizedAfterDeletePos);
              }
            }, function(paddPos) {
              if (moveCaret2) {
                setSelection$1(editor, forward, Optional.some(paddPos));
              }
            });
          }
        };
        var isRootFromElement = function(root) {
          return function(cur) {
            return eq2(root, cur);
          };
        };
        var getTableCells = function(table) {
          return descendants(table, "td,th");
        };
        var getTableDetailsFromRange = function(rng, isRoot) {
          var getTable2 = function(node) {
            return getClosestTable(SugarElement.fromDom(node), isRoot);
          };
          var startTable = getTable2(rng.startContainer);
          var endTable = getTable2(rng.endContainer);
          var isStartInTable = startTable.isSome();
          var isEndInTable = endTable.isSome();
          var isSameTable = lift2(startTable, endTable, eq2).getOr(false);
          var isMultiTable = !isSameTable && isStartInTable && isEndInTable;
          return {
            startTable,
            endTable,
            isStartInTable,
            isEndInTable,
            isSameTable,
            isMultiTable
          };
        };
        var tableCellRng = function(start5, end3) {
          return {
            start: start5,
            end: end3
          };
        };
        var tableSelection = function(rng, table, cells) {
          return {
            rng,
            table,
            cells
          };
        };
        var deleteAction = Adt.generate([
          {
            singleCellTable: [
              "rng",
              "cell"
            ]
          },
          { fullTable: ["table"] },
          {
            partialTable: [
              "cells",
              "outsideDetails"
            ]
          },
          {
            multiTable: [
              "startTableCells",
              "endTableCells",
              "betweenRng"
            ]
          }
        ]);
        var getClosestCell$1 = function(container, isRoot) {
          return closest$2(SugarElement.fromDom(container), "td,th", isRoot);
        };
        var isExpandedCellRng = function(cellRng) {
          return !eq2(cellRng.start, cellRng.end);
        };
        var getTableFromCellRng = function(cellRng, isRoot) {
          return getClosestTable(cellRng.start, isRoot).bind(function(startParentTable) {
            return getClosestTable(cellRng.end, isRoot).bind(function(endParentTable) {
              return someIf(eq2(startParentTable, endParentTable), startParentTable);
            });
          });
        };
        var isSingleCellTable = function(cellRng, isRoot) {
          return !isExpandedCellRng(cellRng) && getTableFromCellRng(cellRng, isRoot).exists(function(table) {
            var rows = table.dom.rows;
            return rows.length === 1 && rows[0].cells.length === 1;
          });
        };
        var getCellRng = function(rng, isRoot) {
          var startCell = getClosestCell$1(rng.startContainer, isRoot);
          var endCell = getClosestCell$1(rng.endContainer, isRoot);
          return lift2(startCell, endCell, tableCellRng);
        };
        var getCellRangeFromStartTable = function(isRoot) {
          return function(startCell) {
            return getClosestTable(startCell, isRoot).bind(function(table) {
              return last$2(getTableCells(table)).map(function(endCell) {
                return tableCellRng(startCell, endCell);
              });
            });
          };
        };
        var getCellRangeFromEndTable = function(isRoot) {
          return function(endCell) {
            return getClosestTable(endCell, isRoot).bind(function(table) {
              return head(getTableCells(table)).map(function(startCell) {
                return tableCellRng(startCell, endCell);
              });
            });
          };
        };
        var getTableSelectionFromCellRng = function(isRoot) {
          return function(cellRng) {
            return getTableFromCellRng(cellRng, isRoot).map(function(table) {
              return tableSelection(cellRng, table, getTableCells(table));
            });
          };
        };
        var getTableSelections = function(cellRng, selectionDetails, rng, isRoot) {
          if (rng.collapsed || !cellRng.forall(isExpandedCellRng)) {
            return Optional.none();
          } else if (selectionDetails.isSameTable) {
            var sameTableSelection = cellRng.bind(getTableSelectionFromCellRng(isRoot));
            return Optional.some({
              start: sameTableSelection,
              end: sameTableSelection
            });
          } else {
            var startCell = getClosestCell$1(rng.startContainer, isRoot);
            var endCell = getClosestCell$1(rng.endContainer, isRoot);
            var startTableSelection = startCell.bind(getCellRangeFromStartTable(isRoot)).bind(getTableSelectionFromCellRng(isRoot));
            var endTableSelection = endCell.bind(getCellRangeFromEndTable(isRoot)).bind(getTableSelectionFromCellRng(isRoot));
            return Optional.some({
              start: startTableSelection,
              end: endTableSelection
            });
          }
        };
        var getCellIndex = function(cells, cell) {
          return findIndex$2(cells, function(x2) {
            return eq2(x2, cell);
          });
        };
        var getSelectedCells = function(tableSelection2) {
          return lift2(getCellIndex(tableSelection2.cells, tableSelection2.rng.start), getCellIndex(tableSelection2.cells, tableSelection2.rng.end), function(startIndex, endIndex) {
            return tableSelection2.cells.slice(startIndex, endIndex + 1);
          });
        };
        var isSingleCellTableContentSelected = function(optCellRng, rng, isRoot) {
          return optCellRng.exists(function(cellRng) {
            return isSingleCellTable(cellRng, isRoot) && hasAllContentsSelected(cellRng.start, rng);
          });
        };
        var unselectCells = function(rng, selectionDetails) {
          var startTable = selectionDetails.startTable, endTable = selectionDetails.endTable;
          var otherContentRng = rng.cloneRange();
          startTable.each(function(table) {
            return otherContentRng.setStartAfter(table.dom);
          });
          endTable.each(function(table) {
            return otherContentRng.setEndBefore(table.dom);
          });
          return otherContentRng;
        };
        var handleSingleTable = function(cellRng, selectionDetails, rng, isRoot) {
          return getTableSelections(cellRng, selectionDetails, rng, isRoot).bind(function(_a) {
            var start5 = _a.start, end3 = _a.end;
            return start5.or(end3);
          }).bind(function(tableSelection2) {
            var isSameTable = selectionDetails.isSameTable;
            var selectedCells = getSelectedCells(tableSelection2).getOr([]);
            if (isSameTable && tableSelection2.cells.length === selectedCells.length) {
              return Optional.some(deleteAction.fullTable(tableSelection2.table));
            } else if (selectedCells.length > 0) {
              if (isSameTable) {
                return Optional.some(deleteAction.partialTable(selectedCells, Optional.none()));
              } else {
                var otherContentRng = unselectCells(rng, selectionDetails);
                return Optional.some(deleteAction.partialTable(selectedCells, Optional.some(__assign(__assign({}, selectionDetails), { rng: otherContentRng }))));
              }
            } else {
              return Optional.none();
            }
          });
        };
        var handleMultiTable = function(cellRng, selectionDetails, rng, isRoot) {
          return getTableSelections(cellRng, selectionDetails, rng, isRoot).bind(function(_a) {
            var start5 = _a.start, end3 = _a.end;
            var startTableSelectedCells = start5.bind(getSelectedCells).getOr([]);
            var endTableSelectedCells = end3.bind(getSelectedCells).getOr([]);
            if (startTableSelectedCells.length > 0 && endTableSelectedCells.length > 0) {
              var otherContentRng = unselectCells(rng, selectionDetails);
              return Optional.some(deleteAction.multiTable(startTableSelectedCells, endTableSelectedCells, otherContentRng));
            } else {
              return Optional.none();
            }
          });
        };
        var getActionFromRange = function(root, rng) {
          var isRoot = isRootFromElement(root);
          var optCellRng = getCellRng(rng, isRoot);
          var selectionDetails = getTableDetailsFromRange(rng, isRoot);
          if (isSingleCellTableContentSelected(optCellRng, rng, isRoot)) {
            return optCellRng.map(function(cellRng) {
              return deleteAction.singleCellTable(rng, cellRng.start);
            });
          } else if (selectionDetails.isMultiTable) {
            return handleMultiTable(optCellRng, selectionDetails, rng, isRoot);
          } else {
            return handleSingleTable(optCellRng, selectionDetails, rng, isRoot);
          }
        };
        var freefallRtl = function(root) {
          var child2 = isComment$1(root) ? prevSibling(root) : lastChild(root);
          return child2.bind(freefallRtl).orThunk(function() {
            return Optional.some(root);
          });
        };
        var cleanCells = function(cells) {
          return each$k(cells, function(cell) {
            remove$6(cell, "contenteditable");
            fillWithPaddingBr(cell);
          });
        };
        var getOutsideBlock = function(editor, container) {
          return Optional.from(editor.dom.getParent(container, editor.dom.isBlock)).map(SugarElement.fromDom);
        };
        var handleEmptyBlock = function(editor, startInTable, emptyBlock2) {
          emptyBlock2.each(function(block) {
            if (startInTable) {
              remove$7(block);
            } else {
              fillWithPaddingBr(block);
              editor.selection.setCursorLocation(block.dom, 0);
            }
          });
        };
        var deleteContentInsideCell = function(editor, cell, rng, isFirstCellInSelection) {
          var insideTableRng = rng.cloneRange();
          if (isFirstCellInSelection) {
            insideTableRng.setStart(rng.startContainer, rng.startOffset);
            insideTableRng.setEndAfter(cell.dom.lastChild);
          } else {
            insideTableRng.setStartBefore(cell.dom.firstChild);
            insideTableRng.setEnd(rng.endContainer, rng.endOffset);
          }
          deleteCellContents(editor, insideTableRng, cell, false);
        };
        var collapseAndRestoreCellSelection = function(editor) {
          var selectedCells = getCellsFromEditor(editor);
          var selectedNode = SugarElement.fromDom(editor.selection.getNode());
          if (isTableCell$5(selectedNode.dom) && isEmpty$2(selectedNode)) {
            editor.selection.setCursorLocation(selectedNode.dom, 0);
          } else {
            editor.selection.collapse(true);
          }
          if (selectedCells.length > 1 && exists(selectedCells, function(cell) {
            return eq2(cell, selectedNode);
          })) {
            set$1(selectedNode, "data-mce-selected", "1");
          }
        };
        var emptySingleTableCells = function(editor, cells, outsideDetails) {
          var editorRng = editor.selection.getRng();
          var cellsToClean = outsideDetails.bind(function(_a) {
            var rng = _a.rng, isStartInTable = _a.isStartInTable;
            var outsideBlock = getOutsideBlock(editor, isStartInTable ? rng.endContainer : rng.startContainer);
            rng.deleteContents();
            handleEmptyBlock(editor, isStartInTable, outsideBlock.filter(isEmpty$2));
            var endPointCell = isStartInTable ? cells[0] : cells[cells.length - 1];
            deleteContentInsideCell(editor, endPointCell, editorRng, isStartInTable);
            if (!isEmpty$2(endPointCell)) {
              return Optional.some(isStartInTable ? cells.slice(1) : cells.slice(0, -1));
            } else {
              return Optional.none();
            }
          }).getOr(cells);
          cleanCells(cellsToClean);
          collapseAndRestoreCellSelection(editor);
          return true;
        };
        var emptyMultiTableCells = function(editor, startTableCells, endTableCells, betweenRng) {
          var rng = editor.selection.getRng();
          var startCell = startTableCells[0];
          var endCell = endTableCells[endTableCells.length - 1];
          deleteContentInsideCell(editor, startCell, rng, true);
          deleteContentInsideCell(editor, endCell, rng, false);
          var startTableCellsToClean = isEmpty$2(startCell) ? startTableCells : startTableCells.slice(1);
          var endTableCellsToClean = isEmpty$2(endCell) ? endTableCells : endTableCells.slice(0, -1);
          cleanCells(startTableCellsToClean.concat(endTableCellsToClean));
          betweenRng.deleteContents();
          collapseAndRestoreCellSelection(editor);
          return true;
        };
        var deleteCellContents = function(editor, rng, cell, moveSelection2) {
          if (moveSelection2 === void 0) {
            moveSelection2 = true;
          }
          rng.deleteContents();
          var lastNode = freefallRtl(cell).getOr(cell);
          var lastBlock = SugarElement.fromDom(editor.dom.getParent(lastNode.dom, editor.dom.isBlock));
          if (isEmpty$2(lastBlock)) {
            fillWithPaddingBr(lastBlock);
            if (moveSelection2) {
              editor.selection.setCursorLocation(lastBlock.dom, 0);
            }
          }
          if (!eq2(cell, lastBlock)) {
            var additionalCleanupNodes = is$1(parent(lastBlock), cell) ? [] : siblings(lastBlock);
            each$k(additionalCleanupNodes.concat(children(cell)), function(node) {
              if (!eq2(node, lastBlock) && !contains$1(node, lastBlock) && isEmpty$2(node)) {
                remove$7(node);
              }
            });
          }
          return true;
        };
        var deleteTableElement = function(editor, table) {
          deleteElement$2(editor, false, table);
          return true;
        };
        var deleteCellRange = function(editor, rootElm, rng) {
          return getActionFromRange(rootElm, rng).map(function(action2) {
            return action2.fold(curry(deleteCellContents, editor), curry(deleteTableElement, editor), curry(emptySingleTableCells, editor), curry(emptyMultiTableCells, editor));
          });
        };
        var deleteCaptionRange = function(editor, caption) {
          return emptyElement(editor, caption);
        };
        var deleteTableRange = function(editor, rootElm, rng, startElm) {
          return getParentCaption(rootElm, startElm).fold(function() {
            return deleteCellRange(editor, rootElm, rng);
          }, function(caption) {
            return deleteCaptionRange(editor, caption);
          }).getOr(false);
        };
        var deleteRange$2 = function(editor, startElm, selectedCells) {
          var rootNode = SugarElement.fromDom(editor.getBody());
          var rng = editor.selection.getRng();
          return selectedCells.length !== 0 ? emptySingleTableCells(editor, selectedCells, Optional.none()) : deleteTableRange(editor, rootNode, rng, startElm);
        };
        var getParentCell = function(rootElm, elm) {
          return find$3(parentsAndSelf(elm, rootElm), isTableCell$4);
        };
        var getParentCaption = function(rootElm, elm) {
          return find$3(parentsAndSelf(elm, rootElm), isTag("caption"));
        };
        var deleteBetweenCells = function(editor, rootElm, forward, fromCell, from2) {
          return navigate(forward, editor.getBody(), from2).bind(function(to2) {
            return getParentCell(rootElm, SugarElement.fromDom(to2.getNode())).map(function(toCell) {
              return eq2(toCell, fromCell) === false;
            });
          });
        };
        var emptyElement = function(editor, elm) {
          fillWithPaddingBr(elm);
          editor.selection.setCursorLocation(elm.dom, 0);
          return Optional.some(true);
        };
        var isDeleteOfLastCharPos = function(fromCaption, forward, from2, to2) {
          return firstPositionIn(fromCaption.dom).bind(function(first2) {
            return lastPositionIn(fromCaption.dom).map(function(last2) {
              return forward ? from2.isEqual(first2) && to2.isEqual(last2) : from2.isEqual(last2) && to2.isEqual(first2);
            });
          }).getOr(true);
        };
        var emptyCaretCaption = function(editor, elm) {
          return emptyElement(editor, elm);
        };
        var validateCaretCaption = function(rootElm, fromCaption, to2) {
          return getParentCaption(rootElm, SugarElement.fromDom(to2.getNode())).map(function(toCaption) {
            return eq2(toCaption, fromCaption) === false;
          });
        };
        var deleteCaretInsideCaption = function(editor, rootElm, forward, fromCaption, from2) {
          return navigate(forward, editor.getBody(), from2).bind(function(to2) {
            return isDeleteOfLastCharPos(fromCaption, forward, from2, to2) ? emptyCaretCaption(editor, fromCaption) : validateCaretCaption(rootElm, fromCaption, to2);
          }).or(Optional.some(true));
        };
        var deleteCaretCells = function(editor, forward, rootElm, startElm) {
          var from2 = CaretPosition.fromRangeStart(editor.selection.getRng());
          return getParentCell(rootElm, startElm).bind(function(fromCell) {
            return isEmpty$2(fromCell) ? emptyElement(editor, fromCell) : deleteBetweenCells(editor, rootElm, forward, fromCell, from2);
          }).getOr(false);
        };
        var deleteCaretCaption = function(editor, forward, rootElm, fromCaption) {
          var from2 = CaretPosition.fromRangeStart(editor.selection.getRng());
          return isEmpty$2(fromCaption) ? emptyElement(editor, fromCaption) : deleteCaretInsideCaption(editor, rootElm, forward, fromCaption, from2);
        };
        var isNearTable = function(forward, pos) {
          return forward ? isBeforeTable(pos) : isAfterTable(pos);
        };
        var isBeforeOrAfterTable = function(editor, forward) {
          var fromPos = CaretPosition.fromRangeStart(editor.selection.getRng());
          return isNearTable(forward, fromPos) || fromPosition(forward, editor.getBody(), fromPos).exists(function(pos) {
            return isNearTable(forward, pos);
          });
        };
        var deleteCaret$3 = function(editor, forward, startElm) {
          var rootElm = SugarElement.fromDom(editor.getBody());
          return getParentCaption(rootElm, startElm).fold(function() {
            return deleteCaretCells(editor, forward, rootElm, startElm) || isBeforeOrAfterTable(editor, forward);
          }, function(fromCaption) {
            return deleteCaretCaption(editor, forward, rootElm, fromCaption).getOr(false);
          });
        };
        var backspaceDelete$9 = function(editor, forward) {
          var startElm = SugarElement.fromDom(editor.selection.getStart(true));
          var cells = getCellsFromEditor(editor);
          return editor.selection.isCollapsed() && cells.length === 0 ? deleteCaret$3(editor, forward, startElm) : deleteRange$2(editor, startElm, cells);
        };
        var createRange = function(sc, so, ec, eo) {
          var rng = document.createRange();
          rng.setStart(sc, so);
          rng.setEnd(ec, eo);
          return rng;
        };
        var normalizeBlockSelectionRange = function(rng) {
          var startPos = CaretPosition.fromRangeStart(rng);
          var endPos = CaretPosition.fromRangeEnd(rng);
          var rootNode = rng.commonAncestorContainer;
          return fromPosition(false, rootNode, endPos).map(function(newEndPos) {
            if (!isInSameBlock(startPos, endPos, rootNode) && isInSameBlock(startPos, newEndPos, rootNode)) {
              return createRange(startPos.container(), startPos.offset(), newEndPos.container(), newEndPos.offset());
            } else {
              return rng;
            }
          }).getOr(rng);
        };
        var normalize = function(rng) {
          return rng.collapsed ? rng : normalizeBlockSelectionRange(rng);
        };
        var hasOnlyOneChild$1 = function(node) {
          return node.firstChild && node.firstChild === node.lastChild;
        };
        var isPaddingNode = function(node) {
          return node.name === "br" || node.value === nbsp;
        };
        var isPaddedEmptyBlock = function(schema, node) {
          var blockElements = schema.getBlockElements();
          return blockElements[node.name] && hasOnlyOneChild$1(node) && isPaddingNode(node.firstChild);
        };
        var isEmptyFragmentElement = function(schema, node) {
          var nonEmptyElements = schema.getNonEmptyElements();
          return node && (node.isEmpty(nonEmptyElements) || isPaddedEmptyBlock(schema, node));
        };
        var isListFragment = function(schema, fragment) {
          var firstChild2 = fragment.firstChild;
          var lastChild2 = fragment.lastChild;
          if (firstChild2 && firstChild2.name === "meta") {
            firstChild2 = firstChild2.next;
          }
          if (lastChild2 && lastChild2.attr("id") === "mce_marker") {
            lastChild2 = lastChild2.prev;
          }
          if (isEmptyFragmentElement(schema, lastChild2)) {
            lastChild2 = lastChild2.prev;
          }
          if (!firstChild2 || firstChild2 !== lastChild2) {
            return false;
          }
          return firstChild2.name === "ul" || firstChild2.name === "ol";
        };
        var cleanupDomFragment = function(domFragment) {
          var firstChild2 = domFragment.firstChild;
          var lastChild2 = domFragment.lastChild;
          if (firstChild2 && firstChild2.nodeName === "META") {
            firstChild2.parentNode.removeChild(firstChild2);
          }
          if (lastChild2 && lastChild2.id === "mce_marker") {
            lastChild2.parentNode.removeChild(lastChild2);
          }
          return domFragment;
        };
        var toDomFragment = function(dom2, serializer, fragment) {
          var html = serializer.serialize(fragment);
          var domFragment = dom2.createFragment(html);
          return cleanupDomFragment(domFragment);
        };
        var listItems = function(elm) {
          return filter$4(elm.childNodes, function(child2) {
            return child2.nodeName === "LI";
          });
        };
        var isPadding = function(node) {
          return node.data === nbsp || isBr$5(node);
        };
        var isListItemPadded = function(node) {
          return node && node.firstChild && node.firstChild === node.lastChild && isPadding(node.firstChild);
        };
        var isEmptyOrPadded = function(elm) {
          return !elm.firstChild || isListItemPadded(elm);
        };
        var trimListItems = function(elms) {
          return elms.length > 0 && isEmptyOrPadded(elms[elms.length - 1]) ? elms.slice(0, -1) : elms;
        };
        var getParentLi = function(dom2, node) {
          var parentBlock = dom2.getParent(node, dom2.isBlock);
          return parentBlock && parentBlock.nodeName === "LI" ? parentBlock : null;
        };
        var isParentBlockLi = function(dom2, node) {
          return !!getParentLi(dom2, node);
        };
        var getSplit = function(parentNode, rng) {
          var beforeRng = rng.cloneRange();
          var afterRng = rng.cloneRange();
          beforeRng.setStartBefore(parentNode);
          afterRng.setEndAfter(parentNode);
          return [
            beforeRng.cloneContents(),
            afterRng.cloneContents()
          ];
        };
        var findFirstIn = function(node, rootNode) {
          var caretPos = CaretPosition.before(node);
          var caretWalker = CaretWalker(rootNode);
          var newCaretPos = caretWalker.next(caretPos);
          return newCaretPos ? newCaretPos.toRange() : null;
        };
        var findLastOf = function(node, rootNode) {
          var caretPos = CaretPosition.after(node);
          var caretWalker = CaretWalker(rootNode);
          var newCaretPos = caretWalker.prev(caretPos);
          return newCaretPos ? newCaretPos.toRange() : null;
        };
        var insertMiddle = function(target, elms, rootNode, rng) {
          var parts = getSplit(target, rng);
          var parentElm = target.parentNode;
          parentElm.insertBefore(parts[0], target);
          Tools.each(elms, function(li2) {
            parentElm.insertBefore(li2, target);
          });
          parentElm.insertBefore(parts[1], target);
          parentElm.removeChild(target);
          return findLastOf(elms[elms.length - 1], rootNode);
        };
        var insertBefore$1 = function(target, elms, rootNode) {
          var parentElm = target.parentNode;
          Tools.each(elms, function(elm) {
            parentElm.insertBefore(elm, target);
          });
          return findFirstIn(target, rootNode);
        };
        var insertAfter$1 = function(target, elms, rootNode, dom2) {
          dom2.insertAfter(elms.reverse(), target);
          return findLastOf(elms[0], rootNode);
        };
        var insertAtCaret$1 = function(serializer, dom2, rng, fragment) {
          var domFragment = toDomFragment(dom2, serializer, fragment);
          var liTarget = getParentLi(dom2, rng.startContainer);
          var liElms = trimListItems(listItems(domFragment.firstChild));
          var BEGINNING = 1, END = 2;
          var rootNode = dom2.getRoot();
          var isAt = function(location2) {
            var caretPos = CaretPosition.fromRangeStart(rng);
            var caretWalker = CaretWalker(dom2.getRoot());
            var newPos = location2 === BEGINNING ? caretWalker.prev(caretPos) : caretWalker.next(caretPos);
            return newPos ? getParentLi(dom2, newPos.getNode()) !== liTarget : true;
          };
          if (isAt(BEGINNING)) {
            return insertBefore$1(liTarget, liElms, rootNode);
          } else if (isAt(END)) {
            return insertAfter$1(liTarget, liElms, rootNode, dom2);
          }
          return insertMiddle(liTarget, liElms, rootNode, rng);
        };
        var trimOrPadLeftRight = function(dom2, rng, html) {
          var root = SugarElement.fromDom(dom2.getRoot());
          if (needsToBeNbspLeft(root, CaretPosition.fromRangeStart(rng))) {
            html = html.replace(/^ /, "&nbsp;");
          } else {
            html = html.replace(/^&nbsp;/, " ");
          }
          if (needsToBeNbspRight(root, CaretPosition.fromRangeEnd(rng))) {
            html = html.replace(/(&nbsp;| )(<br( \/)>)?$/, "&nbsp;");
          } else {
            html = html.replace(/&nbsp;(<br( \/)?>)?$/, " ");
          }
          return html;
        };
        var isTableCell$1 = isTableCell$5;
        var isTableCellContentSelected = function(dom2, rng, cell) {
          if (cell !== null) {
            var endCell = dom2.getParent(rng.endContainer, isTableCell$1);
            return cell === endCell && hasAllContentsSelected(SugarElement.fromDom(cell), rng);
          } else {
            return false;
          }
        };
        var validInsertion = function(editor, value2, parentNode) {
          if (parentNode.getAttribute("data-mce-bogus") === "all") {
            parentNode.parentNode.insertBefore(editor.dom.createFragment(value2), parentNode);
          } else {
            var node = parentNode.firstChild;
            var node2 = parentNode.lastChild;
            if (!node || node === node2 && node.nodeName === "BR") {
              editor.dom.setHTML(parentNode, value2);
            } else {
              editor.selection.setContent(value2);
            }
          }
        };
        var trimBrsFromTableCell = function(dom2, elm) {
          Optional.from(dom2.getParent(elm, "td,th")).map(SugarElement.fromDom).each(trimBlockTrailingBr);
        };
        var reduceInlineTextElements = function(editor, merge3) {
          var textInlineElements = editor.schema.getTextInlineElements();
          var dom2 = editor.dom;
          if (merge3) {
            var root_1 = editor.getBody();
            var elementUtils_1 = ElementUtils(dom2);
            Tools.each(dom2.select("*[data-mce-fragment]"), function(node) {
              var isInline2 = isNonNullable(textInlineElements[node.nodeName.toLowerCase()]);
              if (isInline2 && hasInheritableStyles(dom2, node)) {
                for (var parentNode = node.parentNode; isNonNullable(parentNode) && parentNode !== root_1; parentNode = parentNode.parentNode) {
                  var styleConflict = hasStyleConflict(dom2, node, parentNode);
                  if (styleConflict) {
                    break;
                  }
                  if (elementUtils_1.compare(parentNode, node)) {
                    dom2.remove(node, true);
                    break;
                  }
                }
              }
            });
          }
        };
        var markFragmentElements = function(fragment) {
          var node = fragment;
          while (node = node.walk()) {
            if (node.type === 1) {
              node.attr("data-mce-fragment", "1");
            }
          }
        };
        var unmarkFragmentElements = function(elm) {
          Tools.each(elm.getElementsByTagName("*"), function(elm2) {
            elm2.removeAttribute("data-mce-fragment");
          });
        };
        var isPartOfFragment = function(node) {
          return !!node.getAttribute("data-mce-fragment");
        };
        var canHaveChildren = function(editor, node) {
          return node && !editor.schema.getShortEndedElements()[node.nodeName];
        };
        var moveSelectionToMarker = function(editor, marker) {
          var nextRng;
          var dom2 = editor.dom;
          var selection = editor.selection;
          if (!marker) {
            return;
          }
          selection.scrollIntoView(marker);
          var parentEditableElm = getContentEditableRoot$1(editor.getBody(), marker);
          if (dom2.getContentEditable(parentEditableElm) === "false") {
            dom2.remove(marker);
            selection.select(parentEditableElm);
            return;
          }
          var rng = dom2.createRng();
          var node = marker.previousSibling;
          if (isText$7(node)) {
            rng.setStart(node, node.nodeValue.length);
            if (!Env.ie) {
              var node2 = marker.nextSibling;
              if (isText$7(node2)) {
                node.appendData(node2.data);
                node2.parentNode.removeChild(node2);
              }
            }
          } else {
            rng.setStartBefore(marker);
            rng.setEndBefore(marker);
          }
          var findNextCaretRng = function(rng2) {
            var caretPos = CaretPosition.fromRangeStart(rng2);
            var caretWalker = CaretWalker(editor.getBody());
            caretPos = caretWalker.next(caretPos);
            if (caretPos) {
              return caretPos.toRange();
            }
          };
          var parentBlock = dom2.getParent(marker, dom2.isBlock);
          dom2.remove(marker);
          if (parentBlock && dom2.isEmpty(parentBlock)) {
            editor.$(parentBlock).empty();
            rng.setStart(parentBlock, 0);
            rng.setEnd(parentBlock, 0);
            if (!isTableCell$1(parentBlock) && !isPartOfFragment(parentBlock) && (nextRng = findNextCaretRng(rng))) {
              rng = nextRng;
              dom2.remove(parentBlock);
            } else {
              dom2.add(parentBlock, dom2.create("br", { "data-mce-bogus": "1" }));
            }
          }
          selection.setRng(rng);
        };
        var deleteSelectedContent = function(editor) {
          var dom2 = editor.dom;
          var rng = normalize(editor.selection.getRng());
          editor.selection.setRng(rng);
          var startCell = dom2.getParent(rng.startContainer, isTableCell$1);
          if (isTableCellContentSelected(dom2, rng, startCell)) {
            deleteCellContents(editor, rng, SugarElement.fromDom(startCell));
          } else {
            editor.getDoc().execCommand("Delete", false, null);
          }
        };
        var insertHtmlAtCaret = function(editor, value2, details) {
          var parentNode;
          var rng, node;
          var selection = editor.selection;
          var dom2 = editor.dom;
          if (/^ | $/.test(value2)) {
            value2 = trimOrPadLeftRight(dom2, selection.getRng(), value2);
          }
          var parser = editor.parser;
          var merge3 = details.merge;
          var serializer = HtmlSerializer({ validate: shouldValidate(editor) }, editor.schema);
          var bookmarkHtml = '<span id="mce_marker" data-mce-type="bookmark">&#xFEFF;</span>';
          var args = editor.fire("BeforeSetContent", {
            content: value2,
            format: "html",
            selection: true,
            paste: details.paste
          });
          if (args.isDefaultPrevented()) {
            editor.fire("SetContent", {
              content: args.content,
              format: "html",
              selection: true,
              paste: details.paste
            });
            return;
          }
          value2 = args.content;
          if (value2.indexOf("{$caret}") === -1) {
            value2 += "{$caret}";
          }
          value2 = value2.replace(/\{\$caret\}/, bookmarkHtml);
          rng = selection.getRng();
          var caretElement = rng.startContainer || (rng.parentElement ? rng.parentElement() : null);
          var body = editor.getBody();
          if (caretElement === body && selection.isCollapsed()) {
            if (dom2.isBlock(body.firstChild) && canHaveChildren(editor, body.firstChild) && dom2.isEmpty(body.firstChild)) {
              rng = dom2.createRng();
              rng.setStart(body.firstChild, 0);
              rng.setEnd(body.firstChild, 0);
              selection.setRng(rng);
            }
          }
          if (!selection.isCollapsed()) {
            deleteSelectedContent(editor);
          }
          parentNode = selection.getNode();
          var parserArgs = {
            context: parentNode.nodeName.toLowerCase(),
            data: details.data,
            insert: true
          };
          var fragment = parser.parse(value2, parserArgs);
          if (details.paste === true && isListFragment(editor.schema, fragment) && isParentBlockLi(dom2, parentNode)) {
            rng = insertAtCaret$1(serializer, dom2, selection.getRng(), fragment);
            selection.setRng(rng);
            editor.fire("SetContent", args);
            return;
          }
          markFragmentElements(fragment);
          node = fragment.lastChild;
          if (node.attr("id") === "mce_marker") {
            var marker = node;
            for (node = node.prev; node; node = node.walk(true)) {
              if (node.type === 3 || !dom2.isBlock(node.name)) {
                if (editor.schema.isValidChild(node.parent.name, "span")) {
                  node.parent.insert(marker, node, node.name === "br");
                }
                break;
              }
            }
          }
          editor._selectionOverrides.showBlockCaretContainer(parentNode);
          if (!parserArgs.invalid) {
            value2 = serializer.serialize(fragment);
            validInsertion(editor, value2, parentNode);
          } else {
            editor.selection.setContent(bookmarkHtml);
            parentNode = selection.getNode();
            var rootNode = editor.getBody();
            if (parentNode.nodeType === 9) {
              parentNode = node = rootNode;
            } else {
              node = parentNode;
            }
            while (node !== rootNode) {
              parentNode = node;
              node = node.parentNode;
            }
            value2 = parentNode === rootNode ? rootNode.innerHTML : dom2.getOuterHTML(parentNode);
            value2 = serializer.serialize(parser.parse(value2.replace(/<span (id="mce_marker"|id=mce_marker).+?<\/span>/i, function() {
              return serializer.serialize(fragment);
            })));
            if (parentNode === rootNode) {
              dom2.setHTML(rootNode, value2);
            } else {
              dom2.setOuterHTML(parentNode, value2);
            }
          }
          reduceInlineTextElements(editor, merge3);
          moveSelectionToMarker(editor, dom2.get("mce_marker"));
          unmarkFragmentElements(editor.getBody());
          trimBrsFromTableCell(dom2, selection.getStart());
          editor.fire("SetContent", args);
          editor.addVisual();
        };
        var traverse = function(node, fn3) {
          fn3(node);
          if (node.firstChild) {
            traverse(node.firstChild, fn3);
          }
          if (node.next) {
            traverse(node.next, fn3);
          }
        };
        var findMatchingNodes = function(nodeFilters, attributeFilters, node) {
          var nodeMatches = {};
          var attrMatches = {};
          var matches2 = [];
          if (node.firstChild) {
            traverse(node.firstChild, function(node2) {
              each$k(nodeFilters, function(filter2) {
                if (filter2.name === node2.name) {
                  if (nodeMatches[filter2.name]) {
                    nodeMatches[filter2.name].nodes.push(node2);
                  } else {
                    nodeMatches[filter2.name] = {
                      filter: filter2,
                      nodes: [node2]
                    };
                  }
                }
              });
              each$k(attributeFilters, function(filter2) {
                if (typeof node2.attr(filter2.name) === "string") {
                  if (attrMatches[filter2.name]) {
                    attrMatches[filter2.name].nodes.push(node2);
                  } else {
                    attrMatches[filter2.name] = {
                      filter: filter2,
                      nodes: [node2]
                    };
                  }
                }
              });
            });
          }
          for (var name_1 in nodeMatches) {
            if (has$2(nodeMatches, name_1)) {
              matches2.push(nodeMatches[name_1]);
            }
          }
          for (var name_2 in attrMatches) {
            if (has$2(attrMatches, name_2)) {
              matches2.push(attrMatches[name_2]);
            }
          }
          return matches2;
        };
        var filter$1 = function(nodeFilters, attributeFilters, node) {
          var matches2 = findMatchingNodes(nodeFilters, attributeFilters, node);
          each$k(matches2, function(match3) {
            each$k(match3.filter.callbacks, function(callback2) {
              callback2(match3.nodes, match3.filter.name, {});
            });
          });
        };
        var defaultFormat$1 = "html";
        var isTreeNode = function(content) {
          return content instanceof AstNode;
        };
        var moveSelection = function(editor) {
          if (hasFocus(editor)) {
            firstPositionIn(editor.getBody()).each(function(pos) {
              var node = pos.getNode();
              var caretPos = isTable$3(node) ? firstPositionIn(node).getOr(pos) : pos;
              editor.selection.setRng(caretPos.toRange());
            });
          }
        };
        var setEditorHtml = function(editor, html, noSelection) {
          editor.dom.setHTML(editor.getBody(), html);
          if (noSelection !== true) {
            moveSelection(editor);
          }
        };
        var setContentString = function(editor, body, content, args) {
          if (content.length === 0 || /^\s+$/.test(content)) {
            var padd = '<br data-mce-bogus="1">';
            if (body.nodeName === "TABLE") {
              content = "<tr><td>" + padd + "</td></tr>";
            } else if (/^(UL|OL)$/.test(body.nodeName)) {
              content = "<li>" + padd + "</li>";
            }
            var forcedRootBlockName = getForcedRootBlock(editor);
            if (forcedRootBlockName && editor.schema.isValidChild(body.nodeName.toLowerCase(), forcedRootBlockName.toLowerCase())) {
              content = padd;
              content = editor.dom.createHTML(forcedRootBlockName, getForcedRootBlockAttrs(editor), content);
            } else if (!content) {
              content = '<br data-mce-bogus="1">';
            }
            setEditorHtml(editor, content, args.no_selection);
            editor.fire("SetContent", args);
          } else {
            if (args.format !== "raw") {
              content = HtmlSerializer({ validate: editor.validate }, editor.schema).serialize(editor.parser.parse(content, {
                isRootContent: true,
                insert: true
              }));
            }
            args.content = isWsPreserveElement(SugarElement.fromDom(body)) ? content : Tools.trim(content);
            setEditorHtml(editor, args.content, args.no_selection);
            if (!args.no_events) {
              editor.fire("SetContent", args);
            }
          }
          return args.content;
        };
        var setContentTree = function(editor, body, content, args) {
          filter$1(editor.parser.getNodeFilters(), editor.parser.getAttributeFilters(), content);
          var html = HtmlSerializer({ validate: editor.validate }, editor.schema).serialize(content);
          args.content = isWsPreserveElement(SugarElement.fromDom(body)) ? html : Tools.trim(html);
          setEditorHtml(editor, args.content, args.no_selection);
          if (!args.no_events) {
            editor.fire("SetContent", args);
          }
          return content;
        };
        var setupArgs$2 = function(args, content) {
          return __assign(__assign({ format: defaultFormat$1 }, args), {
            set: true,
            content: isTreeNode(content) ? "" : content
          });
        };
        var setContentInternal = function(editor, content, args) {
          var defaultedArgs = setupArgs$2(args, content);
          var updatedArgs = args.no_events ? defaultedArgs : editor.fire("BeforeSetContent", defaultedArgs);
          if (!isTreeNode(content)) {
            content = updatedArgs.content;
          }
          return Optional.from(editor.getBody()).fold(constant(content), function(body) {
            return isTreeNode(content) ? setContentTree(editor, body, content, updatedArgs) : setContentString(editor, body, content, updatedArgs);
          });
        };
        var sibling = function(scope, predicate) {
          return sibling$2(scope, predicate).isSome();
        };
        var ensureIsRoot = function(isRoot) {
          return isFunction2(isRoot) ? isRoot : never;
        };
        var ancestor = function(scope, transform, isRoot) {
          var element = scope.dom;
          var stop2 = ensureIsRoot(isRoot);
          while (element.parentNode) {
            element = element.parentNode;
            var el = SugarElement.fromDom(element);
            var transformed = transform(el);
            if (transformed.isSome()) {
              return transformed;
            } else if (stop2(el)) {
              break;
            }
          }
          return Optional.none();
        };
        var closest$1 = function(scope, transform, isRoot) {
          var current = transform(scope);
          var stop2 = ensureIsRoot(isRoot);
          return current.orThunk(function() {
            return stop2(scope) ? Optional.none() : ancestor(scope, transform, stop2);
          });
        };
        var isEq$3 = isEq$5;
        var matchesUnInheritedFormatSelector = function(ed, node, name2) {
          var formatList = ed.formatter.get(name2);
          if (formatList) {
            for (var i2 = 0; i2 < formatList.length; i2++) {
              var format3 = formatList[i2];
              if (isSelectorFormat(format3) && format3.inherit === false && ed.dom.is(node, format3.selector)) {
                return true;
              }
            }
          }
          return false;
        };
        var matchParents = function(editor, node, name2, vars, similar) {
          var root = editor.dom.getRoot();
          if (node === root) {
            return false;
          }
          node = editor.dom.getParent(node, function(node2) {
            if (matchesUnInheritedFormatSelector(editor, node2, name2)) {
              return true;
            }
            return node2.parentNode === root || !!matchNode(editor, node2, name2, vars, true);
          });
          return !!matchNode(editor, node, name2, vars, similar);
        };
        var matchName$1 = function(dom2, node, format3) {
          if (isEq$3(node, format3.inline)) {
            return true;
          }
          if (isEq$3(node, format3.block)) {
            return true;
          }
          if (format3.selector) {
            return node.nodeType === 1 && dom2.is(node, format3.selector);
          }
        };
        var matchItems = function(dom2, node, format3, itemName, similar, vars) {
          var items = format3[itemName];
          if (isFunction2(format3.onmatch)) {
            return format3.onmatch(node, format3, itemName);
          }
          if (items) {
            if (isUndefined(items.length)) {
              for (var key in items) {
                if (has$2(items, key)) {
                  var value2 = itemName === "attributes" ? dom2.getAttrib(node, key) : getStyle2(dom2, node, key);
                  var expectedValue = replaceVars(items[key], vars);
                  var isEmptyValue = isNullable(value2) || isEmpty$3(value2);
                  if (isEmptyValue && isNullable(expectedValue)) {
                    continue;
                  }
                  if (similar && isEmptyValue && !format3.exact) {
                    return false;
                  }
                  if ((!similar || format3.exact) && !isEq$3(value2, normalizeStyleValue(dom2, expectedValue, key))) {
                    return false;
                  }
                }
              }
            } else {
              for (var i2 = 0; i2 < items.length; i2++) {
                if (itemName === "attributes" ? dom2.getAttrib(node, items[i2]) : getStyle2(dom2, node, items[i2])) {
                  return true;
                }
              }
            }
          }
          return true;
        };
        var matchNode = function(ed, node, name2, vars, similar) {
          var formatList = ed.formatter.get(name2);
          var dom2 = ed.dom;
          if (formatList && node) {
            for (var i2 = 0; i2 < formatList.length; i2++) {
              var format3 = formatList[i2];
              if (matchName$1(ed.dom, node, format3) && matchItems(dom2, node, format3, "attributes", similar, vars) && matchItems(dom2, node, format3, "styles", similar, vars)) {
                var classes = format3.classes;
                if (classes) {
                  for (var x2 = 0; x2 < classes.length; x2++) {
                    if (!ed.dom.hasClass(node, replaceVars(classes[x2], vars))) {
                      return;
                    }
                  }
                }
                return format3;
              }
            }
          }
        };
        var match$2 = function(editor, name2, vars, node, similar) {
          if (node) {
            return matchParents(editor, node, name2, vars, similar);
          }
          node = editor.selection.getNode();
          if (matchParents(editor, node, name2, vars, similar)) {
            return true;
          }
          var startNode = editor.selection.getStart();
          if (startNode !== node) {
            if (matchParents(editor, startNode, name2, vars, similar)) {
              return true;
            }
          }
          return false;
        };
        var matchAll = function(editor, names2, vars) {
          var matchedFormatNames = [];
          var checkedMap = {};
          var startElement = editor.selection.getStart();
          editor.dom.getParent(startElement, function(node) {
            for (var i2 = 0; i2 < names2.length; i2++) {
              var name_1 = names2[i2];
              if (!checkedMap[name_1] && matchNode(editor, node, name_1, vars)) {
                checkedMap[name_1] = true;
                matchedFormatNames.push(name_1);
              }
            }
          }, editor.dom.getRoot());
          return matchedFormatNames;
        };
        var closest = function(editor, names2) {
          var isRoot = function(elm) {
            return eq2(elm, SugarElement.fromDom(editor.getBody()));
          };
          var match3 = function(elm, name2) {
            return matchNode(editor, elm.dom, name2) ? Optional.some(name2) : Optional.none();
          };
          return Optional.from(editor.selection.getStart(true)).bind(function(rawElm) {
            return closest$1(SugarElement.fromDom(rawElm), function(elm) {
              return findMap(names2, function(name2) {
                return match3(elm, name2);
              });
            }, isRoot);
          }).getOrNull();
        };
        var canApply = function(editor, name2) {
          var formatList = editor.formatter.get(name2);
          var dom2 = editor.dom;
          if (formatList) {
            var startNode = editor.selection.getStart();
            var parents2 = getParents$2(dom2, startNode);
            for (var x2 = formatList.length - 1; x2 >= 0; x2--) {
              var format3 = formatList[x2];
              if (!isSelectorFormat(format3) || isNonNullable(format3.defaultBlock)) {
                return true;
              }
              for (var i2 = parents2.length - 1; i2 >= 0; i2--) {
                if (dom2.is(parents2[i2], format3.selector)) {
                  return true;
                }
              }
            }
          }
          return false;
        };
        var matchAllOnNode = function(editor, node, formatNames) {
          return foldl(formatNames, function(acc, name2) {
            var matchSimilar = isVariableFormatName(editor, name2);
            if (editor.formatter.matchNode(node, name2, {}, matchSimilar)) {
              return acc.concat([name2]);
            } else {
              return acc;
            }
          }, []);
        };
        var ZWSP = ZWSP$1, CARET_ID = "_mce_caret";
        var importNode = function(ownerDocument, node) {
          return ownerDocument.importNode(node, true);
        };
        var getEmptyCaretContainers = function(node) {
          var nodes = [];
          while (node) {
            if (node.nodeType === 3 && node.nodeValue !== ZWSP || node.childNodes.length > 1) {
              return [];
            }
            if (node.nodeType === 1) {
              nodes.push(node);
            }
            node = node.firstChild;
          }
          return nodes;
        };
        var isCaretContainerEmpty = function(node) {
          return getEmptyCaretContainers(node).length > 0;
        };
        var findFirstTextNode = function(node) {
          if (node) {
            var walker = new DomTreeWalker(node, node);
            for (node = walker.current(); node; node = walker.next()) {
              if (isText$7(node)) {
                return node;
              }
            }
          }
          return null;
        };
        var createCaretContainer = function(fill) {
          var caretContainer = SugarElement.fromTag("span");
          setAll$1(caretContainer, {
            "id": CARET_ID,
            "data-mce-bogus": "1",
            "data-mce-type": "format-caret"
          });
          if (fill) {
            append$1(caretContainer, SugarElement.fromText(ZWSP));
          }
          return caretContainer;
        };
        var trimZwspFromCaretContainer = function(caretContainerNode) {
          var textNode = findFirstTextNode(caretContainerNode);
          if (textNode && textNode.nodeValue.charAt(0) === ZWSP) {
            textNode.deleteData(0, 1);
          }
          return textNode;
        };
        var removeCaretContainerNode = function(editor, node, moveCaret2) {
          if (moveCaret2 === void 0) {
            moveCaret2 = true;
          }
          var dom2 = editor.dom, selection = editor.selection;
          if (isCaretContainerEmpty(node)) {
            deleteElement$2(editor, false, SugarElement.fromDom(node), moveCaret2);
          } else {
            var rng = selection.getRng();
            var block = dom2.getParent(node, dom2.isBlock);
            var startContainer = rng.startContainer;
            var startOffset = rng.startOffset;
            var endContainer = rng.endContainer;
            var endOffset = rng.endOffset;
            var textNode = trimZwspFromCaretContainer(node);
            dom2.remove(node, true);
            if (startContainer === textNode && startOffset > 0) {
              rng.setStart(textNode, startOffset - 1);
            }
            if (endContainer === textNode && endOffset > 0) {
              rng.setEnd(textNode, endOffset - 1);
            }
            if (block && dom2.isEmpty(block)) {
              fillWithPaddingBr(SugarElement.fromDom(block));
            }
            selection.setRng(rng);
          }
        };
        var removeCaretContainer = function(editor, node, moveCaret2) {
          if (moveCaret2 === void 0) {
            moveCaret2 = true;
          }
          var dom2 = editor.dom, selection = editor.selection;
          if (!node) {
            node = getParentCaretContainer(editor.getBody(), selection.getStart());
            if (!node) {
              while (node = dom2.get(CARET_ID)) {
                removeCaretContainerNode(editor, node, false);
              }
            }
          } else {
            removeCaretContainerNode(editor, node, moveCaret2);
          }
        };
        var insertCaretContainerNode = function(editor, caretContainer, formatNode) {
          var dom2 = editor.dom, block = dom2.getParent(formatNode, curry(isTextBlock$1, editor));
          if (block && dom2.isEmpty(block)) {
            formatNode.parentNode.replaceChild(caretContainer, formatNode);
          } else {
            removeTrailingBr(SugarElement.fromDom(formatNode));
            if (dom2.isEmpty(formatNode)) {
              formatNode.parentNode.replaceChild(caretContainer, formatNode);
            } else {
              dom2.insertAfter(caretContainer, formatNode);
            }
          }
        };
        var appendNode = function(parentNode, node) {
          parentNode.appendChild(node);
          return node;
        };
        var insertFormatNodesIntoCaretContainer = function(formatNodes, caretContainer) {
          var innerMostFormatNode = foldr(formatNodes, function(parentNode, formatNode) {
            return appendNode(parentNode, formatNode.cloneNode(false));
          }, caretContainer);
          return appendNode(innerMostFormatNode, innerMostFormatNode.ownerDocument.createTextNode(ZWSP));
        };
        var cleanFormatNode = function(editor, caretContainer, formatNode, name2, vars, similar) {
          var formatter = editor.formatter;
          var dom2 = editor.dom;
          var validFormats = filter$4(keys(formatter.get()), function(formatName) {
            return formatName !== name2 && !contains$2(formatName, "removeformat");
          });
          var matchedFormats = matchAllOnNode(editor, formatNode, validFormats);
          var uniqueFormats = filter$4(matchedFormats, function(fmtName) {
            return !areSimilarFormats(editor, fmtName, name2);
          });
          if (uniqueFormats.length > 0) {
            var clonedFormatNode = formatNode.cloneNode(false);
            dom2.add(caretContainer, clonedFormatNode);
            formatter.remove(name2, vars, clonedFormatNode, similar);
            dom2.remove(clonedFormatNode);
            return Optional.some(clonedFormatNode);
          } else {
            return Optional.none();
          }
        };
        var applyCaretFormat = function(editor, name2, vars) {
          var caretContainer, textNode;
          var selection = editor.selection;
          var selectionRng = selection.getRng();
          var offset2 = selectionRng.startOffset;
          var container = selectionRng.startContainer;
          var text = container.nodeValue;
          caretContainer = getParentCaretContainer(editor.getBody(), selection.getStart());
          if (caretContainer) {
            textNode = findFirstTextNode(caretContainer);
          }
          var wordcharRegex = /[^\s\u00a0\u00ad\u200b\ufeff]/;
          if (text && offset2 > 0 && offset2 < text.length && wordcharRegex.test(text.charAt(offset2)) && wordcharRegex.test(text.charAt(offset2 - 1))) {
            var bookmark = selection.getBookmark();
            selectionRng.collapse(true);
            var rng = expandRng(editor, selectionRng, editor.formatter.get(name2));
            rng = split(rng);
            editor.formatter.apply(name2, vars, rng);
            selection.moveToBookmark(bookmark);
          } else {
            if (!caretContainer || textNode.nodeValue !== ZWSP) {
              caretContainer = importNode(editor.getDoc(), createCaretContainer(true).dom);
              textNode = caretContainer.firstChild;
              selectionRng.insertNode(caretContainer);
              offset2 = 1;
              editor.formatter.apply(name2, vars, caretContainer);
            } else {
              editor.formatter.apply(name2, vars, caretContainer);
            }
            selection.setCursorLocation(textNode, offset2);
          }
        };
        var removeCaretFormat = function(editor, name2, vars, similar) {
          var dom2 = editor.dom;
          var selection = editor.selection;
          var hasContentAfter, node, formatNode;
          var parents2 = [];
          var rng = selection.getRng();
          var container = rng.startContainer;
          var offset2 = rng.startOffset;
          node = container;
          if (container.nodeType === 3) {
            if (offset2 !== container.nodeValue.length) {
              hasContentAfter = true;
            }
            node = node.parentNode;
          }
          while (node) {
            if (matchNode(editor, node, name2, vars, similar)) {
              formatNode = node;
              break;
            }
            if (node.nextSibling) {
              hasContentAfter = true;
            }
            parents2.push(node);
            node = node.parentNode;
          }
          if (!formatNode) {
            return;
          }
          if (hasContentAfter) {
            var bookmark = selection.getBookmark();
            rng.collapse(true);
            var expandedRng = expandRng(editor, rng, editor.formatter.get(name2), true);
            expandedRng = split(expandedRng);
            editor.formatter.remove(name2, vars, expandedRng, similar);
            selection.moveToBookmark(bookmark);
          } else {
            var caretContainer = getParentCaretContainer(editor.getBody(), formatNode);
            var newCaretContainer = createCaretContainer(false).dom;
            insertCaretContainerNode(editor, newCaretContainer, caretContainer !== null ? caretContainer : formatNode);
            var cleanedFormatNode = cleanFormatNode(editor, newCaretContainer, formatNode, name2, vars, similar);
            var caretTextNode = insertFormatNodesIntoCaretContainer(parents2.concat(cleanedFormatNode.toArray()), newCaretContainer);
            removeCaretContainerNode(editor, caretContainer, false);
            selection.setCursorLocation(caretTextNode, 1);
            if (dom2.isEmpty(formatNode)) {
              dom2.remove(formatNode);
            }
          }
        };
        var disableCaretContainer = function(editor, keyCode) {
          var selection = editor.selection, body = editor.getBody();
          removeCaretContainer(editor, null, false);
          if ((keyCode === 8 || keyCode === 46) && selection.isCollapsed() && selection.getStart().innerHTML === ZWSP) {
            removeCaretContainer(editor, getParentCaretContainer(body, selection.getStart()));
          }
          if (keyCode === 37 || keyCode === 39) {
            removeCaretContainer(editor, getParentCaretContainer(body, selection.getStart()));
          }
        };
        var setup$k = function(editor) {
          editor.on("mouseup keydown", function(e2) {
            disableCaretContainer(editor, e2.keyCode);
          });
        };
        var replaceWithCaretFormat = function(targetNode, formatNodes) {
          var caretContainer = createCaretContainer(false);
          var innerMost = insertFormatNodesIntoCaretContainer(formatNodes, caretContainer.dom);
          before$4(SugarElement.fromDom(targetNode), caretContainer);
          remove$7(SugarElement.fromDom(targetNode));
          return CaretPosition(innerMost, 0);
        };
        var isFormatElement = function(editor, element) {
          var inlineElements = editor.schema.getTextInlineElements();
          return has$2(inlineElements, name(element)) && !isCaretNode(element.dom) && !isBogus$2(element.dom);
        };
        var isEmptyCaretFormatElement = function(element) {
          return isCaretNode(element.dom) && isCaretContainerEmpty(element.dom);
        };
        var postProcessHooks = {};
        var filter = filter$2;
        var each$b = each$i;
        var addPostProcessHook = function(name2, hook) {
          var hooks = postProcessHooks[name2];
          if (!hooks) {
            postProcessHooks[name2] = [];
          }
          postProcessHooks[name2].push(hook);
        };
        var postProcess$1 = function(name2, editor) {
          each$b(postProcessHooks[name2], function(hook) {
            hook(editor);
          });
        };
        addPostProcessHook("pre", function(editor) {
          var rng = editor.selection.getRng();
          var blocks2;
          var hasPreSibling = function(pre) {
            return isPre(pre.previousSibling) && indexOf$1(blocks2, pre.previousSibling) !== -1;
          };
          var joinPre = function(pre1, pre2) {
            DomQuery(pre2).remove();
            DomQuery(pre1).append("<br><br>").append(pre2.childNodes);
          };
          var isPre = matchNodeNames(["pre"]);
          if (!rng.collapsed) {
            blocks2 = editor.selection.getSelectedBlocks();
            each$b(filter(filter(blocks2, isPre), hasPreSibling), function(pre) {
              joinPre(pre.previousSibling, pre);
            });
          }
        });
        var each$a = Tools.each;
        var isElementNode$1 = function(node) {
          return isElement$5(node) && !isBookmarkNode$1(node) && !isCaretNode(node) && !isBogus$2(node);
        };
        var findElementSibling = function(node, siblingName) {
          for (var sibling2 = node; sibling2; sibling2 = sibling2[siblingName]) {
            if (isText$7(sibling2) && isNotEmpty(sibling2.data)) {
              return node;
            }
            if (isElement$5(sibling2) && !isBookmarkNode$1(sibling2)) {
              return sibling2;
            }
          }
          return node;
        };
        var mergeSiblingsNodes = function(dom2, prev, next) {
          var elementUtils = ElementUtils(dom2);
          if (prev && next) {
            prev = findElementSibling(prev, "previousSibling");
            next = findElementSibling(next, "nextSibling");
            if (elementUtils.compare(prev, next)) {
              for (var sibling2 = prev.nextSibling; sibling2 && sibling2 !== next; ) {
                var tmpSibling = sibling2;
                sibling2 = sibling2.nextSibling;
                prev.appendChild(tmpSibling);
              }
              dom2.remove(next);
              Tools.each(Tools.grep(next.childNodes), function(node) {
                prev.appendChild(node);
              });
              return prev;
            }
          }
          return next;
        };
        var mergeSiblings = function(dom2, format3, vars, node) {
          if (node && format3.merge_siblings !== false) {
            var newNode = mergeSiblingsNodes(dom2, getNonWhiteSpaceSibling(node), node);
            mergeSiblingsNodes(dom2, newNode, getNonWhiteSpaceSibling(newNode, true));
          }
        };
        var clearChildStyles = function(dom2, format3, node) {
          if (format3.clear_child_styles) {
            var selector = format3.links ? "*:not(a)" : "*";
            each$a(dom2.select(selector, node), function(node2) {
              if (isElementNode$1(node2)) {
                each$a(format3.styles, function(value2, name2) {
                  dom2.setStyle(node2, name2, "");
                });
              }
            });
          }
        };
        var processChildElements = function(node, filter2, process3) {
          each$a(node.childNodes, function(node2) {
            if (isElementNode$1(node2)) {
              if (filter2(node2)) {
                process3(node2);
              }
              if (node2.hasChildNodes()) {
                processChildElements(node2, filter2, process3);
              }
            }
          });
        };
        var unwrapEmptySpan = function(dom2, node) {
          if (node.nodeName === "SPAN" && dom2.getAttribs(node).length === 0) {
            dom2.remove(node, true);
          }
        };
        var hasStyle = function(dom2, name2) {
          return function(node) {
            return !!(node && getStyle2(dom2, node, name2));
          };
        };
        var applyStyle = function(dom2, name2, value2) {
          return function(node) {
            dom2.setStyle(node, name2, value2);
            if (node.getAttribute("style") === "") {
              node.removeAttribute("style");
            }
            unwrapEmptySpan(dom2, node);
          };
        };
        var removeResult = Adt.generate([
          { keep: [] },
          { rename: ["name"] },
          { removed: [] }
        ]);
        var MCE_ATTR_RE = /^(src|href|style)$/;
        var each$9 = Tools.each;
        var isEq$2 = isEq$5;
        var isTableCellOrRow = function(node) {
          return /^(TR|TH|TD)$/.test(node.nodeName);
        };
        var isChildOfInlineParent = function(dom2, node, parent2) {
          return dom2.isChildOf(node, parent2) && node !== parent2 && !dom2.isBlock(parent2);
        };
        var getContainer = function(ed, rng, start5) {
          var container = rng[start5 ? "startContainer" : "endContainer"];
          var offset2 = rng[start5 ? "startOffset" : "endOffset"];
          if (isElement$5(container)) {
            var lastIdx = container.childNodes.length - 1;
            if (!start5 && offset2) {
              offset2--;
            }
            container = container.childNodes[offset2 > lastIdx ? lastIdx : offset2];
          }
          if (isText$7(container) && start5 && offset2 >= container.nodeValue.length) {
            container = new DomTreeWalker(container, ed.getBody()).next() || container;
          }
          if (isText$7(container) && !start5 && offset2 === 0) {
            container = new DomTreeWalker(container, ed.getBody()).prev() || container;
          }
          return container;
        };
        var normalizeTableSelection = function(node, start5) {
          var prop = start5 ? "firstChild" : "lastChild";
          if (isTableCellOrRow(node) && node[prop]) {
            var childNode = node[prop];
            if (node.nodeName === "TR") {
              return childNode[prop] || childNode;
            } else {
              return childNode;
            }
          }
          return node;
        };
        var wrap$1 = function(dom2, node, name2, attrs) {
          var wrapper = dom2.create(name2, attrs);
          node.parentNode.insertBefore(wrapper, node);
          wrapper.appendChild(node);
          return wrapper;
        };
        var wrapWithSiblings = function(dom2, node, next, name2, attrs) {
          var start5 = SugarElement.fromDom(node);
          var wrapper = SugarElement.fromDom(dom2.create(name2, attrs));
          var siblings2 = next ? nextSiblings(start5) : prevSiblings(start5);
          append(wrapper, siblings2);
          if (next) {
            before$4(start5, wrapper);
            prepend(wrapper, start5);
          } else {
            after$3(start5, wrapper);
            append$1(wrapper, start5);
          }
          return wrapper.dom;
        };
        var matchName = function(dom2, node, format3) {
          if (isInlineFormat(format3) && isEq$2(node, format3.inline)) {
            return true;
          }
          if (isBlockFormat(format3) && isEq$2(node, format3.block)) {
            return true;
          }
          if (isSelectorFormat(format3)) {
            return isElement$5(node) && dom2.is(node, format3.selector);
          }
        };
        var isColorFormatAndAnchor = function(node, format3) {
          return format3.links && node.nodeName === "A";
        };
        var find = function(dom2, node, next, inc) {
          var sibling2 = getNonWhiteSpaceSibling(node, next, inc);
          return isNullable(sibling2) || sibling2.nodeName === "BR" || dom2.isBlock(sibling2);
        };
        var removeNode = function(ed, node, format3) {
          var parentNode = node.parentNode;
          var rootBlockElm;
          var dom2 = ed.dom, forcedRootBlock = getForcedRootBlock(ed);
          if (isBlockFormat(format3)) {
            if (!forcedRootBlock) {
              if (dom2.isBlock(node) && !dom2.isBlock(parentNode)) {
                if (!find(dom2, node, false) && !find(dom2, node.firstChild, true, true)) {
                  node.insertBefore(dom2.create("br"), node.firstChild);
                }
                if (!find(dom2, node, true) && !find(dom2, node.lastChild, false, true)) {
                  node.appendChild(dom2.create("br"));
                }
              }
            } else {
              if (parentNode === dom2.getRoot()) {
                if (!format3.list_block || !isEq$2(node, format3.list_block)) {
                  each$k(from(node.childNodes), function(node2) {
                    if (isValid2(ed, forcedRootBlock, node2.nodeName.toLowerCase())) {
                      if (!rootBlockElm) {
                        rootBlockElm = wrap$1(dom2, node2, forcedRootBlock);
                        dom2.setAttribs(rootBlockElm, ed.settings.forced_root_block_attrs);
                      } else {
                        rootBlockElm.appendChild(node2);
                      }
                    } else {
                      rootBlockElm = null;
                    }
                  });
                }
              }
            }
          }
          if (isMixedFormat(format3) && !isEq$2(format3.inline, node)) {
            return;
          }
          dom2.remove(node, true);
        };
        var removeFormatInternal = function(ed, format3, vars, node, compareNode) {
          var stylesModified;
          var dom2 = ed.dom;
          if (!matchName(dom2, node, format3) && !isColorFormatAndAnchor(node, format3)) {
            return removeResult.keep();
          }
          var elm = node;
          if (isInlineFormat(format3) && format3.remove === "all" && isArray$1(format3.preserve_attributes)) {
            var attrsToPreserve = filter$4(dom2.getAttribs(elm), function(attr) {
              return contains$3(format3.preserve_attributes, attr.name.toLowerCase());
            });
            dom2.removeAllAttribs(elm);
            each$k(attrsToPreserve, function(attr) {
              return dom2.setAttrib(elm, attr.name, attr.value);
            });
            if (attrsToPreserve.length > 0) {
              return removeResult.rename("span");
            }
          }
          if (format3.remove !== "all") {
            each$9(format3.styles, function(value2, name2) {
              value2 = normalizeStyleValue(dom2, replaceVars(value2, vars), name2 + "");
              if (isNumber2(name2)) {
                name2 = value2;
                compareNode = null;
              }
              if (format3.remove_similar || (!compareNode || isEq$2(getStyle2(dom2, compareNode, name2), value2))) {
                dom2.setStyle(elm, name2, "");
              }
              stylesModified = true;
            });
            if (stylesModified && dom2.getAttrib(elm, "style") === "") {
              elm.removeAttribute("style");
              elm.removeAttribute("data-mce-style");
            }
            each$9(format3.attributes, function(value2, name2) {
              var valueOut;
              value2 = replaceVars(value2, vars);
              if (isNumber2(name2)) {
                name2 = value2;
                compareNode = null;
              }
              if (format3.remove_similar || (!compareNode || isEq$2(dom2.getAttrib(compareNode, name2), value2))) {
                if (name2 === "class") {
                  value2 = dom2.getAttrib(elm, name2);
                  if (value2) {
                    valueOut = "";
                    each$k(value2.split(/\s+/), function(cls) {
                      if (/mce\-\w+/.test(cls)) {
                        valueOut += (valueOut ? " " : "") + cls;
                      }
                    });
                    if (valueOut) {
                      dom2.setAttrib(elm, name2, valueOut);
                      return;
                    }
                  }
                }
                if (MCE_ATTR_RE.test(name2)) {
                  elm.removeAttribute("data-mce-" + name2);
                }
                if (name2 === "style" && matchNodeNames(["li"])(elm) && dom2.getStyle(elm, "list-style-type") === "none") {
                  elm.removeAttribute(name2);
                  dom2.setStyle(elm, "list-style-type", "none");
                  return;
                }
                if (name2 === "class") {
                  elm.removeAttribute("className");
                }
                elm.removeAttribute(name2);
              }
            });
            each$9(format3.classes, function(value2) {
              value2 = replaceVars(value2, vars);
              if (!compareNode || dom2.hasClass(compareNode, value2)) {
                dom2.removeClass(elm, value2);
              }
            });
            var attrs = dom2.getAttribs(elm);
            for (var i2 = 0; i2 < attrs.length; i2++) {
              var attrName = attrs[i2].nodeName;
              if (attrName.indexOf("_") !== 0 && attrName.indexOf("data-") !== 0) {
                return removeResult.keep();
              }
            }
          }
          if (format3.remove !== "none") {
            removeNode(ed, elm, format3);
            return removeResult.removed();
          }
          return removeResult.keep();
        };
        var removeFormat$1 = function(ed, format3, vars, node, compareNode) {
          return removeFormatInternal(ed, format3, vars, node, compareNode).fold(never, function(newName) {
            ed.dom.rename(node, newName);
            return true;
          }, always);
        };
        var findFormatRoot = function(editor, container, name2, vars, similar) {
          var formatRoot;
          each$k(getParents$2(editor.dom, container.parentNode).reverse(), function(parent2) {
            if (!formatRoot && parent2.id !== "_start" && parent2.id !== "_end") {
              var format3 = matchNode(editor, parent2, name2, vars, similar);
              if (format3 && format3.split !== false) {
                formatRoot = parent2;
              }
            }
          });
          return formatRoot;
        };
        var removeFormatFromClone = function(editor, format3, vars, clone3) {
          return removeFormatInternal(editor, format3, vars, clone3, clone3).fold(constant(clone3), function(newName) {
            var fragment = editor.dom.createFragment();
            fragment.appendChild(clone3);
            return editor.dom.rename(clone3, newName);
          }, constant(null));
        };
        var wrapAndSplit = function(editor, formatList, formatRoot, container, target, split2, format3, vars) {
          var clone3, lastClone, firstClone;
          var dom2 = editor.dom;
          if (formatRoot) {
            var formatRootParent = formatRoot.parentNode;
            for (var parent_1 = container.parentNode; parent_1 && parent_1 !== formatRootParent; parent_1 = parent_1.parentNode) {
              clone3 = dom2.clone(parent_1, false);
              for (var i2 = 0; i2 < formatList.length; i2++) {
                clone3 = removeFormatFromClone(editor, formatList[i2], vars, clone3);
                if (clone3 === null) {
                  break;
                }
              }
              if (clone3) {
                if (lastClone) {
                  clone3.appendChild(lastClone);
                }
                if (!firstClone) {
                  firstClone = clone3;
                }
                lastClone = clone3;
              }
            }
            if (split2 && (!format3.mixed || !dom2.isBlock(formatRoot))) {
              container = dom2.split(formatRoot, container);
            }
            if (lastClone) {
              target.parentNode.insertBefore(lastClone, target);
              firstClone.appendChild(target);
              if (isInlineFormat(format3)) {
                mergeSiblings(dom2, format3, vars, lastClone);
              }
            }
          }
          return container;
        };
        var remove$1 = function(ed, name2, vars, node, similar) {
          var formatList = ed.formatter.get(name2);
          var format3 = formatList[0];
          var contentEditable = true;
          var dom2 = ed.dom;
          var selection = ed.selection;
          var splitToFormatRoot = function(container) {
            var formatRoot = findFormatRoot(ed, container, name2, vars, similar);
            return wrapAndSplit(ed, formatList, formatRoot, container, container, true, format3, vars);
          };
          var isRemoveBookmarkNode = function(node2) {
            return isBookmarkNode$1(node2) && isElement$5(node2) && (node2.id === "_start" || node2.id === "_end");
          };
          var removeNodeFormat = function(node2) {
            return exists(formatList, function(fmt) {
              return removeFormat$1(ed, fmt, vars, node2, node2);
            });
          };
          var process3 = function(node2) {
            var lastContentEditable = true;
            var hasContentEditableState2 = false;
            if (isElement$5(node2) && dom2.getContentEditable(node2)) {
              lastContentEditable = contentEditable;
              contentEditable = dom2.getContentEditable(node2) === "true";
              hasContentEditableState2 = true;
            }
            var children2 = from(node2.childNodes);
            if (contentEditable && !hasContentEditableState2) {
              var removed = removeNodeFormat(node2);
              var parentNode = node2.parentNode;
              if (!removed && isNonNullable(parentNode) && shouldExpandToSelector(format3)) {
                removeNodeFormat(parentNode);
              }
            }
            if (format3.deep) {
              if (children2.length) {
                for (var i3 = 0; i3 < children2.length; i3++) {
                  process3(children2[i3]);
                }
                if (hasContentEditableState2) {
                  contentEditable = lastContentEditable;
                }
              }
            }
            var textDecorations = [
              "underline",
              "line-through",
              "overline"
            ];
            each$k(textDecorations, function(decoration) {
              if (isElement$5(node2) && ed.dom.getStyle(node2, "text-decoration") === decoration && node2.parentNode && getTextDecoration(dom2, node2.parentNode) === decoration) {
                removeFormat$1(ed, {
                  deep: false,
                  exact: true,
                  inline: "span",
                  styles: { textDecoration: decoration }
                }, null, node2);
              }
            });
          };
          var unwrap2 = function(start5) {
            var node2 = dom2.get(start5 ? "_start" : "_end");
            var out = node2[start5 ? "firstChild" : "lastChild"];
            if (isRemoveBookmarkNode(out)) {
              out = out[start5 ? "firstChild" : "lastChild"];
            }
            if (isText$7(out) && out.data.length === 0) {
              out = start5 ? node2.previousSibling || node2.nextSibling : node2.nextSibling || node2.previousSibling;
            }
            dom2.remove(node2, true);
            return out;
          };
          var removeRngStyle = function(rng2) {
            var startContainer, endContainer;
            var expandedRng = expandRng(ed, rng2, formatList, rng2.collapsed);
            if (format3.split) {
              expandedRng = split(expandedRng);
              startContainer = getContainer(ed, expandedRng, true);
              endContainer = getContainer(ed, expandedRng);
              if (startContainer !== endContainer) {
                startContainer = normalizeTableSelection(startContainer, true);
                endContainer = normalizeTableSelection(endContainer, false);
                if (isChildOfInlineParent(dom2, startContainer, endContainer)) {
                  var marker = Optional.from(startContainer.firstChild).getOr(startContainer);
                  splitToFormatRoot(wrapWithSiblings(dom2, marker, true, "span", {
                    "id": "_start",
                    "data-mce-type": "bookmark"
                  }));
                  unwrap2(true);
                  return;
                }
                if (isChildOfInlineParent(dom2, endContainer, startContainer)) {
                  var marker = Optional.from(endContainer.lastChild).getOr(endContainer);
                  splitToFormatRoot(wrapWithSiblings(dom2, marker, false, "span", {
                    "id": "_end",
                    "data-mce-type": "bookmark"
                  }));
                  unwrap2(false);
                  return;
                }
                startContainer = wrap$1(dom2, startContainer, "span", {
                  "id": "_start",
                  "data-mce-type": "bookmark"
                });
                endContainer = wrap$1(dom2, endContainer, "span", {
                  "id": "_end",
                  "data-mce-type": "bookmark"
                });
                var newRng = dom2.createRng();
                newRng.setStartAfter(startContainer);
                newRng.setEndBefore(endContainer);
                walk$2(dom2, newRng, function(nodes) {
                  each$k(nodes, function(n2) {
                    if (!isBookmarkNode$1(n2) && !isBookmarkNode$1(n2.parentNode)) {
                      splitToFormatRoot(n2);
                    }
                  });
                });
                splitToFormatRoot(startContainer);
                splitToFormatRoot(endContainer);
                startContainer = unwrap2(true);
                endContainer = unwrap2();
              } else {
                startContainer = endContainer = splitToFormatRoot(startContainer);
              }
              expandedRng.startContainer = startContainer.parentNode ? startContainer.parentNode : startContainer;
              expandedRng.startOffset = dom2.nodeIndex(startContainer);
              expandedRng.endContainer = endContainer.parentNode ? endContainer.parentNode : endContainer;
              expandedRng.endOffset = dom2.nodeIndex(endContainer) + 1;
            }
            walk$2(dom2, expandedRng, function(nodes) {
              each$k(nodes, process3);
            });
          };
          if (node) {
            if (isNode(node)) {
              var rng = dom2.createRng();
              rng.setStartBefore(node);
              rng.setEndAfter(node);
              removeRngStyle(rng);
            } else {
              removeRngStyle(node);
            }
            fireFormatRemove(ed, name2, node, vars);
            return;
          }
          if (dom2.getContentEditable(selection.getNode()) === "false") {
            node = selection.getNode();
            for (var i2 = 0; i2 < formatList.length; i2++) {
              if (formatList[i2].ceFalseOverride) {
                if (removeFormat$1(ed, formatList[i2], vars, node, node)) {
                  break;
                }
              }
            }
            fireFormatRemove(ed, name2, node, vars);
            return;
          }
          if (!selection.isCollapsed() || !isInlineFormat(format3) || getCellsFromEditor(ed).length) {
            preserve(selection, true, function() {
              runOnRanges(ed, removeRngStyle);
            });
            if (isInlineFormat(format3) && match$2(ed, name2, vars, selection.getStart())) {
              moveStart(dom2, selection, selection.getRng());
            }
            ed.nodeChanged();
          } else {
            removeCaretFormat(ed, name2, vars, similar);
          }
          fireFormatRemove(ed, name2, node, vars);
        };
        var each$8 = Tools.each;
        var mergeTextDecorationsAndColor = function(dom2, format3, vars, node) {
          var processTextDecorationsAndColor = function(n2) {
            if (n2.nodeType === 1 && n2.parentNode && n2.parentNode.nodeType === 1) {
              var textDecoration = getTextDecoration(dom2, n2.parentNode);
              if (dom2.getStyle(n2, "color") && textDecoration) {
                dom2.setStyle(n2, "text-decoration", textDecoration);
              } else if (dom2.getStyle(n2, "text-decoration") === textDecoration) {
                dom2.setStyle(n2, "text-decoration", null);
              }
            }
          };
          if (format3.styles && (format3.styles.color || format3.styles.textDecoration)) {
            Tools.walk(node, processTextDecorationsAndColor, "childNodes");
            processTextDecorationsAndColor(node);
          }
        };
        var mergeBackgroundColorAndFontSize = function(dom2, format3, vars, node) {
          if (format3.styles && format3.styles.backgroundColor) {
            processChildElements(node, hasStyle(dom2, "fontSize"), applyStyle(dom2, "backgroundColor", replaceVars(format3.styles.backgroundColor, vars)));
          }
        };
        var mergeSubSup = function(dom2, format3, vars, node) {
          if (isInlineFormat(format3) && (format3.inline === "sub" || format3.inline === "sup")) {
            processChildElements(node, hasStyle(dom2, "fontSize"), applyStyle(dom2, "fontSize", ""));
            dom2.remove(dom2.select(format3.inline === "sup" ? "sub" : "sup", node), true);
          }
        };
        var mergeWithChildren = function(editor, formatList, vars, node) {
          each$8(formatList, function(format3) {
            if (isInlineFormat(format3)) {
              each$8(editor.dom.select(format3.inline, node), function(child2) {
                if (!isElementNode$1(child2)) {
                  return;
                }
                removeFormat$1(editor, format3, vars, child2, format3.exact ? child2 : null);
              });
            }
            clearChildStyles(editor.dom, format3, node);
          });
        };
        var mergeWithParents = function(editor, format3, name2, vars, node) {
          if (matchNode(editor, node.parentNode, name2, vars)) {
            if (removeFormat$1(editor, format3, vars, node)) {
              return;
            }
          }
          if (format3.merge_with_parents) {
            editor.dom.getParent(node.parentNode, function(parent2) {
              if (matchNode(editor, parent2, name2, vars)) {
                removeFormat$1(editor, format3, vars, node);
                return true;
              }
            });
          }
        };
        var each$7 = Tools.each;
        var isElementNode = function(node) {
          return isElement$5(node) && !isBookmarkNode$1(node) && !isCaretNode(node) && !isBogus$2(node);
        };
        var canFormatBR = function(editor, format3, node, parentName) {
          if (canFormatEmptyLines(editor) && isInlineFormat(format3)) {
            var validBRParentElements = __assign(__assign({}, editor.schema.getTextBlockElements()), {
              td: {},
              th: {},
              li: {},
              dt: {},
              dd: {},
              figcaption: {},
              caption: {},
              details: {},
              summary: {}
            });
            var hasCaretNodeSibling = sibling(SugarElement.fromDom(node), function(sibling2) {
              return isCaretNode(sibling2.dom);
            });
            return hasNonNullableKey(validBRParentElements, parentName) && isEmpty$2(SugarElement.fromDom(node.parentNode), false) && !hasCaretNodeSibling;
          } else {
            return false;
          }
        };
        var applyFormat$1 = function(ed, name2, vars, node) {
          var formatList = ed.formatter.get(name2);
          var format3 = formatList[0];
          var isCollapsed = !node && ed.selection.isCollapsed();
          var dom2 = ed.dom;
          var selection = ed.selection;
          var setElementFormat = function(elm, fmt) {
            if (fmt === void 0) {
              fmt = format3;
            }
            if (isFunction2(fmt.onformat)) {
              fmt.onformat(elm, fmt, vars, node);
            }
            each$7(fmt.styles, function(value2, name3) {
              dom2.setStyle(elm, name3, replaceVars(value2, vars));
            });
            if (fmt.styles) {
              var styleVal = dom2.getAttrib(elm, "style");
              if (styleVal) {
                dom2.setAttrib(elm, "data-mce-style", styleVal);
              }
            }
            each$7(fmt.attributes, function(value2, name3) {
              dom2.setAttrib(elm, name3, replaceVars(value2, vars));
            });
            each$7(fmt.classes, function(value2) {
              value2 = replaceVars(value2, vars);
              if (!dom2.hasClass(elm, value2)) {
                dom2.addClass(elm, value2);
              }
            });
          };
          var applyNodeStyle = function(formatList2, node2) {
            var found = false;
            each$7(formatList2, function(format4) {
              if (!isSelectorFormat(format4)) {
                return false;
              }
              if (isNonNullable(format4.collapsed) && format4.collapsed !== isCollapsed) {
                return;
              }
              if (dom2.is(node2, format4.selector) && !isCaretNode(node2)) {
                setElementFormat(node2, format4);
                found = true;
                return false;
              }
            });
            return found;
          };
          var createWrapElement = function(wrapName) {
            if (isString$1(wrapName)) {
              var wrapElm = dom2.create(wrapName);
              setElementFormat(wrapElm);
              return wrapElm;
            } else {
              return null;
            }
          };
          var applyRngStyle = function(dom3, rng2, nodeSpecific) {
            var newWrappers = [];
            var contentEditable = true;
            var wrapName = format3.inline || format3.block;
            var wrapElm = createWrapElement(wrapName);
            walk$2(dom3, rng2, function(nodes) {
              var currentWrapElm;
              var process3 = function(node2) {
                var hasContentEditableState2 = false;
                var lastContentEditable = contentEditable;
                var nodeName = node2.nodeName.toLowerCase();
                var parentNode = node2.parentNode;
                var parentName = parentNode.nodeName.toLowerCase();
                if (isElement$5(node2) && dom3.getContentEditable(node2)) {
                  lastContentEditable = contentEditable;
                  contentEditable = dom3.getContentEditable(node2) === "true";
                  hasContentEditableState2 = true;
                }
                if (isBr$5(node2) && !canFormatBR(ed, format3, node2, parentName)) {
                  currentWrapElm = null;
                  if (isBlockFormat(format3)) {
                    dom3.remove(node2);
                  }
                  return;
                }
                if (isBlockFormat(format3) && format3.wrapper && matchNode(ed, node2, name2, vars)) {
                  currentWrapElm = null;
                  return;
                }
                if (contentEditable && !hasContentEditableState2 && isBlockFormat(format3) && !format3.wrapper && isTextBlock$1(ed, nodeName) && isValid2(ed, parentName, wrapName)) {
                  var elm = dom3.rename(node2, wrapName);
                  setElementFormat(elm);
                  newWrappers.push(elm);
                  currentWrapElm = null;
                  return;
                }
                if (isSelectorFormat(format3)) {
                  var found = applyNodeStyle(formatList, node2);
                  if (!found && isNonNullable(parentNode) && shouldExpandToSelector(format3)) {
                    found = applyNodeStyle(formatList, parentNode);
                  }
                  if (!isInlineFormat(format3) || found) {
                    currentWrapElm = null;
                    return;
                  }
                }
                if (contentEditable && !hasContentEditableState2 && isValid2(ed, wrapName, nodeName) && isValid2(ed, parentName, wrapName) && !(!nodeSpecific && isText$7(node2) && isZwsp(node2.data)) && !isCaretNode(node2) && (!isInlineFormat(format3) || !dom3.isBlock(node2))) {
                  if (!currentWrapElm) {
                    currentWrapElm = dom3.clone(wrapElm, false);
                    node2.parentNode.insertBefore(currentWrapElm, node2);
                    newWrappers.push(currentWrapElm);
                  }
                  currentWrapElm.appendChild(node2);
                } else {
                  currentWrapElm = null;
                  each$k(from(node2.childNodes), process3);
                  if (hasContentEditableState2) {
                    contentEditable = lastContentEditable;
                  }
                  currentWrapElm = null;
                }
              };
              each$k(nodes, process3);
            });
            if (format3.links === true) {
              each$k(newWrappers, function(node2) {
                var process3 = function(node3) {
                  if (node3.nodeName === "A") {
                    setElementFormat(node3, format3);
                  }
                  each$k(from(node3.childNodes), process3);
                };
                process3(node2);
              });
            }
            each$k(newWrappers, function(node2) {
              var getChildCount = function(node3) {
                var count2 = 0;
                each$k(node3.childNodes, function(node4) {
                  if (!isEmptyTextNode$1(node4) && !isBookmarkNode$1(node4)) {
                    count2++;
                  }
                });
                return count2;
              };
              var mergeStyles = function(node3) {
                var childElement = find$3(node3.childNodes, isElementNode).filter(function(child2) {
                  return matchName$1(dom3, child2, format3);
                });
                return childElement.map(function(child2) {
                  var clone3 = dom3.clone(child2, false);
                  setElementFormat(clone3);
                  dom3.replace(clone3, node3, true);
                  dom3.remove(child2, true);
                  return clone3;
                }).getOr(node3);
              };
              var childCount = getChildCount(node2);
              if ((newWrappers.length > 1 || !dom3.isBlock(node2)) && childCount === 0) {
                dom3.remove(node2, true);
                return;
              }
              if (isInlineFormat(format3) || isBlockFormat(format3) && format3.wrapper) {
                if (!format3.exact && childCount === 1) {
                  node2 = mergeStyles(node2);
                }
                mergeWithChildren(ed, formatList, vars, node2);
                mergeWithParents(ed, format3, name2, vars, node2);
                mergeBackgroundColorAndFontSize(dom3, format3, vars, node2);
                mergeTextDecorationsAndColor(dom3, format3, vars, node2);
                mergeSubSup(dom3, format3, vars, node2);
                mergeSiblings(dom3, format3, vars, node2);
              }
            });
          };
          if (dom2.getContentEditable(selection.getNode()) === "false") {
            node = selection.getNode();
            for (var i2 = 0, l2 = formatList.length; i2 < l2; i2++) {
              var formatItem = formatList[i2];
              if (formatItem.ceFalseOverride && isSelectorFormat(formatItem) && dom2.is(node, formatItem.selector)) {
                setElementFormat(node, formatItem);
                break;
              }
            }
            fireFormatApply(ed, name2, node, vars);
            return;
          }
          if (format3) {
            if (node) {
              if (isNode(node)) {
                if (!applyNodeStyle(formatList, node)) {
                  var rng = dom2.createRng();
                  rng.setStartBefore(node);
                  rng.setEndAfter(node);
                  applyRngStyle(dom2, expandRng(ed, rng, formatList), true);
                }
              } else {
                applyRngStyle(dom2, node, true);
              }
            } else {
              if (!isCollapsed || !isInlineFormat(format3) || getCellsFromEditor(ed).length) {
                var curSelNode = selection.getNode();
                var firstFormat = formatList[0];
                if (!ed.settings.forced_root_block && firstFormat.defaultBlock && !dom2.getParent(curSelNode, dom2.isBlock)) {
                  applyFormat$1(ed, firstFormat.defaultBlock);
                }
                selection.setRng(normalize(selection.getRng()));
                preserve(selection, true, function() {
                  runOnRanges(ed, function(selectionRng, fake) {
                    var expandedRng = fake ? selectionRng : expandRng(ed, selectionRng, formatList);
                    applyRngStyle(dom2, expandedRng, false);
                  });
                });
                moveStart(dom2, selection, selection.getRng());
                ed.nodeChanged();
              } else {
                applyCaretFormat(ed, name2, vars);
              }
            }
            postProcess$1(name2, ed);
          }
          fireFormatApply(ed, name2, node, vars);
        };
        var hasVars = function(value2) {
          return has$2(value2, "vars");
        };
        var setup$j = function(registeredFormatListeners, editor) {
          registeredFormatListeners.set({});
          editor.on("NodeChange", function(e2) {
            updateAndFireChangeCallbacks(editor, e2.element, registeredFormatListeners.get());
          });
          editor.on("FormatApply FormatRemove", function(e2) {
            var element = Optional.from(e2.node).map(function(nodeOrRange) {
              return isNode(nodeOrRange) ? nodeOrRange : nodeOrRange.startContainer;
            }).bind(function(node) {
              return isElement$5(node) ? Optional.some(node) : Optional.from(node.parentElement);
            }).getOrThunk(function() {
              return fallbackElement(editor);
            });
            updateAndFireChangeCallbacks(editor, element, registeredFormatListeners.get());
          });
        };
        var fallbackElement = function(editor) {
          return editor.selection.getStart();
        };
        var matchingNode = function(editor, parents2, format3, similar, vars) {
          var isMatchingNode = function(node) {
            var matchingFormat = editor.formatter.matchNode(node, format3, vars !== null && vars !== void 0 ? vars : {}, similar);
            return !isUndefined(matchingFormat);
          };
          var isUnableToMatch = function(node) {
            if (matchesUnInheritedFormatSelector(editor, node, format3)) {
              return true;
            } else {
              if (!similar) {
                return isNonNullable(editor.formatter.matchNode(node, format3, vars, true));
              } else {
                return false;
              }
            }
          };
          return findUntil$1(parents2, isMatchingNode, isUnableToMatch);
        };
        var getParents = function(editor, elm) {
          var element = elm !== null && elm !== void 0 ? elm : fallbackElement(editor);
          return filter$4(getParents$2(editor.dom, element), function(node) {
            return isElement$5(node) && !isBogus$2(node);
          });
        };
        var updateAndFireChangeCallbacks = function(editor, elm, registeredCallbacks) {
          var parents2 = getParents(editor, elm);
          each$j(registeredCallbacks, function(data2, format3) {
            var runIfChanged = function(spec) {
              var match3 = matchingNode(editor, parents2, format3, spec.similar, hasVars(spec) ? spec.vars : void 0);
              var isSet = match3.isSome();
              if (spec.state.get() !== isSet) {
                spec.state.set(isSet);
                var node_1 = match3.getOr(elm);
                if (hasVars(spec)) {
                  spec.callback(isSet, {
                    node: node_1,
                    format: format3,
                    parents: parents2
                  });
                } else {
                  each$k(spec.callbacks, function(callback2) {
                    return callback2(isSet, {
                      node: node_1,
                      format: format3,
                      parents: parents2
                    });
                  });
                }
              }
            };
            each$k([
              data2.withSimilar,
              data2.withoutSimilar
            ], runIfChanged);
            each$k(data2.withVars, runIfChanged);
          });
        };
        var addListeners = function(editor, registeredFormatListeners, formats, callback2, similar, vars) {
          var formatChangeItems = registeredFormatListeners.get();
          each$k(formats.split(","), function(format3) {
            var group = get$9(formatChangeItems, format3).getOrThunk(function() {
              var base = {
                withSimilar: {
                  state: Cell(false),
                  similar: true,
                  callbacks: []
                },
                withoutSimilar: {
                  state: Cell(false),
                  similar: false,
                  callbacks: []
                },
                withVars: []
              };
              formatChangeItems[format3] = base;
              return base;
            });
            var getCurrent = function() {
              var parents2 = getParents(editor);
              return matchingNode(editor, parents2, format3, similar, vars).isSome();
            };
            if (isUndefined(vars)) {
              var toAppendTo = similar ? group.withSimilar : group.withoutSimilar;
              toAppendTo.callbacks.push(callback2);
              if (toAppendTo.callbacks.length === 1) {
                toAppendTo.state.set(getCurrent());
              }
            } else {
              group.withVars.push({
                state: Cell(getCurrent()),
                similar,
                vars,
                callback: callback2
              });
            }
          });
          registeredFormatListeners.set(formatChangeItems);
        };
        var removeListeners = function(registeredFormatListeners, formats, callback2) {
          var formatChangeItems = registeredFormatListeners.get();
          each$k(formats.split(","), function(format3) {
            return get$9(formatChangeItems, format3).each(function(group) {
              formatChangeItems[format3] = {
                withSimilar: __assign(__assign({}, group.withSimilar), {
                  callbacks: filter$4(group.withSimilar.callbacks, function(cb) {
                    return cb !== callback2;
                  })
                }),
                withoutSimilar: __assign(__assign({}, group.withoutSimilar), {
                  callbacks: filter$4(group.withoutSimilar.callbacks, function(cb) {
                    return cb !== callback2;
                  })
                }),
                withVars: filter$4(group.withVars, function(item) {
                  return item.callback !== callback2;
                })
              };
            });
          });
          registeredFormatListeners.set(formatChangeItems);
        };
        var formatChangedInternal = function(editor, registeredFormatListeners, formats, callback2, similar, vars) {
          if (registeredFormatListeners.get() === null) {
            setup$j(registeredFormatListeners, editor);
          }
          addListeners(editor, registeredFormatListeners, formats, callback2, similar, vars);
          return {
            unbind: function() {
              return removeListeners(registeredFormatListeners, formats, callback2);
            }
          };
        };
        var toggle = function(editor, name2, vars, node) {
          var fmt = editor.formatter.get(name2);
          if (match$2(editor, name2, vars, node) && (!("toggle" in fmt[0]) || fmt[0].toggle)) {
            remove$1(editor, name2, vars, node);
          } else {
            applyFormat$1(editor, name2, vars, node);
          }
        };
        var fromElements = function(elements2, scope) {
          var doc2 = scope || document;
          var fragment = doc2.createDocumentFragment();
          each$k(elements2, function(element) {
            fragment.appendChild(element.dom);
          });
          return SugarElement.fromDom(fragment);
        };
        var tableModel = function(element, width, rows) {
          return {
            element,
            width,
            rows
          };
        };
        var tableRow = function(element, cells) {
          return {
            element,
            cells
          };
        };
        var cellPosition = function(x2, y2) {
          return {
            x: x2,
            y: y2
          };
        };
        var getSpan = function(td, key) {
          var value2 = parseInt(get$6(td, key), 10);
          return isNaN(value2) ? 1 : value2;
        };
        var fillout = function(table, x2, y2, tr, td) {
          var rowspan = getSpan(td, "rowspan");
          var colspan = getSpan(td, "colspan");
          var rows = table.rows;
          for (var y22 = y2; y22 < y2 + rowspan; y22++) {
            if (!rows[y22]) {
              rows[y22] = tableRow(deep$1(tr), []);
            }
            for (var x22 = x2; x22 < x2 + colspan; x22++) {
              var cells = rows[y22].cells;
              cells[x22] = y22 === y2 && x22 === x2 ? td : shallow(td);
            }
          }
        };
        var cellExists = function(table, x2, y2) {
          var rows = table.rows;
          var cells = rows[y2] ? rows[y2].cells : [];
          return !!cells[x2];
        };
        var skipCellsX = function(table, x2, y2) {
          while (cellExists(table, x2, y2)) {
            x2++;
          }
          return x2;
        };
        var getWidth = function(rows) {
          return foldl(rows, function(acc, row) {
            return row.cells.length > acc ? row.cells.length : acc;
          }, 0);
        };
        var findElementPos = function(table, element) {
          var rows = table.rows;
          for (var y2 = 0; y2 < rows.length; y2++) {
            var cells = rows[y2].cells;
            for (var x2 = 0; x2 < cells.length; x2++) {
              if (eq2(cells[x2], element)) {
                return Optional.some(cellPosition(x2, y2));
              }
            }
          }
          return Optional.none();
        };
        var extractRows = function(table, sx, sy, ex, ey) {
          var newRows = [];
          var rows = table.rows;
          for (var y2 = sy; y2 <= ey; y2++) {
            var cells = rows[y2].cells;
            var slice2 = sx < ex ? cells.slice(sx, ex + 1) : cells.slice(ex, sx + 1);
            newRows.push(tableRow(rows[y2].element, slice2));
          }
          return newRows;
        };
        var subTable = function(table, startPos, endPos) {
          var sx = startPos.x, sy = startPos.y;
          var ex = endPos.x, ey = endPos.y;
          var newRows = sy < ey ? extractRows(table, sx, sy, ex, ey) : extractRows(table, sx, ey, ex, sy);
          return tableModel(table.element, getWidth(newRows), newRows);
        };
        var createDomTable = function(table, rows) {
          var tableElement = shallow(table.element);
          var tableBody = SugarElement.fromTag("tbody");
          append(tableBody, rows);
          append$1(tableElement, tableBody);
          return tableElement;
        };
        var modelRowsToDomRows = function(table) {
          return map$3(table.rows, function(row) {
            var cells = map$3(row.cells, function(cell) {
              var td = deep$1(cell);
              remove$6(td, "colspan");
              remove$6(td, "rowspan");
              return td;
            });
            var tr = shallow(row.element);
            append(tr, cells);
            return tr;
          });
        };
        var fromDom = function(tableElm) {
          var table = tableModel(shallow(tableElm), 0, []);
          each$k(descendants(tableElm, "tr"), function(tr, y2) {
            each$k(descendants(tr, "td,th"), function(td, x2) {
              fillout(table, skipCellsX(table, x2, y2), y2, tr, td);
            });
          });
          return tableModel(table.element, getWidth(table.rows), table.rows);
        };
        var toDom = function(table) {
          return createDomTable(table, modelRowsToDomRows(table));
        };
        var subsection = function(table, startElement, endElement) {
          return findElementPos(table, startElement).bind(function(startPos) {
            return findElementPos(table, endElement).map(function(endPos) {
              return subTable(table, startPos, endPos);
            });
          });
        };
        var findParentListContainer = function(parents2) {
          return find$3(parents2, function(elm) {
            return name(elm) === "ul" || name(elm) === "ol";
          });
        };
        var getFullySelectedListWrappers = function(parents2, rng) {
          return find$3(parents2, function(elm) {
            return name(elm) === "li" && hasAllContentsSelected(elm, rng);
          }).fold(constant([]), function(_li) {
            return findParentListContainer(parents2).map(function(listCont) {
              var listElm = SugarElement.fromTag(name(listCont));
              var listStyles = filter$3(getAllRaw(listCont), function(_style, name2) {
                return startsWith(name2, "list-style");
              });
              setAll(listElm, listStyles);
              return [
                SugarElement.fromTag("li"),
                listElm
              ];
            }).getOr([]);
          });
        };
        var wrap = function(innerElm, elms) {
          var wrapped = foldl(elms, function(acc, elm) {
            append$1(elm, acc);
            return elm;
          }, innerElm);
          return elms.length > 0 ? fromElements([wrapped]) : wrapped;
        };
        var directListWrappers = function(commonAnchorContainer) {
          if (isListItem(commonAnchorContainer)) {
            return parent(commonAnchorContainer).filter(isList).fold(constant([]), function(listElm) {
              return [
                commonAnchorContainer,
                listElm
              ];
            });
          } else {
            return isList(commonAnchorContainer) ? [commonAnchorContainer] : [];
          }
        };
        var getWrapElements = function(rootNode, rng) {
          var commonAnchorContainer = SugarElement.fromDom(rng.commonAncestorContainer);
          var parents2 = parentsAndSelf(commonAnchorContainer, rootNode);
          var wrapElements = filter$4(parents2, function(elm) {
            return isInline$1(elm) || isHeading(elm);
          });
          var listWrappers = getFullySelectedListWrappers(parents2, rng);
          var allWrappers = wrapElements.concat(listWrappers.length ? listWrappers : directListWrappers(commonAnchorContainer));
          return map$3(allWrappers, shallow);
        };
        var emptyFragment = function() {
          return fromElements([]);
        };
        var getFragmentFromRange = function(rootNode, rng) {
          return wrap(SugarElement.fromDom(rng.cloneContents()), getWrapElements(rootNode, rng));
        };
        var getParentTable = function(rootElm, cell) {
          return ancestor$2(cell, "table", curry(eq2, rootElm));
        };
        var getTableFragment = function(rootNode, selectedTableCells) {
          return getParentTable(rootNode, selectedTableCells[0]).bind(function(tableElm) {
            var firstCell = selectedTableCells[0];
            var lastCell = selectedTableCells[selectedTableCells.length - 1];
            var fullTableModel = fromDom(tableElm);
            return subsection(fullTableModel, firstCell, lastCell).map(function(sectionedTableModel) {
              return fromElements([toDom(sectionedTableModel)]);
            });
          }).getOrThunk(emptyFragment);
        };
        var getSelectionFragment = function(rootNode, ranges) {
          return ranges.length > 0 && ranges[0].collapsed ? emptyFragment() : getFragmentFromRange(rootNode, ranges[0]);
        };
        var read$3 = function(rootNode, ranges) {
          var selectedCells = getCellsFromElementOrRanges(ranges, rootNode);
          return selectedCells.length > 0 ? getTableFragment(rootNode, selectedCells) : getSelectionFragment(rootNode, ranges);
        };
        var trimLeadingCollapsibleText = function(text) {
          return text.replace(/^[ \f\n\r\t\v]+/, "");
        };
        var isCollapsibleWhitespace = function(text, index) {
          return index >= 0 && index < text.length && isWhiteSpace(text.charAt(index));
        };
        var getInnerText = function(bin, shouldTrim) {
          var text = trim$2(bin.innerText);
          return shouldTrim ? trimLeadingCollapsibleText(text) : text;
        };
        var getContextNodeName = function(parentBlockOpt) {
          return parentBlockOpt.map(function(block) {
            return block.nodeName;
          }).getOr("div").toLowerCase();
        };
        var getTextContent = function(editor) {
          return Optional.from(editor.selection.getRng()).map(function(rng) {
            var parentBlockOpt = Optional.from(editor.dom.getParent(rng.commonAncestorContainer, editor.dom.isBlock));
            var body = editor.getBody();
            var contextNodeName = getContextNodeName(parentBlockOpt);
            var shouldTrimSpaces = Env.browser.isIE() && contextNodeName !== "pre";
            var bin = editor.dom.add(body, contextNodeName, {
              "data-mce-bogus": "all",
              "style": "overflow: hidden; opacity: 0;"
            }, rng.cloneContents());
            var text = getInnerText(bin, shouldTrimSpaces);
            var nonRenderedText = trim$2(bin.textContent);
            editor.dom.remove(bin);
            if (isCollapsibleWhitespace(nonRenderedText, 0) || isCollapsibleWhitespace(nonRenderedText, nonRenderedText.length - 1)) {
              var parentBlock = parentBlockOpt.getOr(body);
              var parentBlockText = getInnerText(parentBlock, shouldTrimSpaces);
              var textIndex = parentBlockText.indexOf(text);
              if (textIndex === -1) {
                return text;
              } else {
                var hasProceedingSpace = isCollapsibleWhitespace(parentBlockText, textIndex - 1);
                var hasTrailingSpace = isCollapsibleWhitespace(parentBlockText, textIndex + text.length);
                return (hasProceedingSpace ? " " : "") + text + (hasTrailingSpace ? " " : "");
              }
            } else {
              return text;
            }
          }).getOr("");
        };
        var getSerializedContent = function(editor, args) {
          var rng = editor.selection.getRng(), tmpElm = editor.dom.create("body");
          var sel = editor.selection.getSel();
          var ranges = processRanges(editor, getRanges(sel));
          var fragment = args.contextual ? read$3(SugarElement.fromDom(editor.getBody()), ranges).dom : rng.cloneContents();
          if (fragment) {
            tmpElm.appendChild(fragment);
          }
          return editor.selection.serializer.serialize(tmpElm, args);
        };
        var setupArgs$1 = function(args, format3) {
          return __assign(__assign({}, args), {
            format: format3,
            get: true,
            selection: true
          });
        };
        var getSelectedContentInternal = function(editor, format3, args) {
          if (args === void 0) {
            args = {};
          }
          var defaultedArgs = setupArgs$1(args, format3);
          var updatedArgs = editor.fire("BeforeGetContent", defaultedArgs);
          if (updatedArgs.isDefaultPrevented()) {
            editor.fire("GetContent", updatedArgs);
            return updatedArgs.content;
          }
          if (updatedArgs.format === "text") {
            return getTextContent(editor);
          } else {
            updatedArgs.getInner = true;
            var content = getSerializedContent(editor, updatedArgs);
            if (updatedArgs.format === "tree") {
              return content;
            } else {
              updatedArgs.content = editor.selection.isCollapsed() ? "" : content;
              editor.fire("GetContent", updatedArgs);
              return updatedArgs.content;
            }
          }
        };
        var KEEP = 0, INSERT = 1, DELETE = 2;
        var diff = function(left2, right2) {
          var size = left2.length + right2.length + 2;
          var vDown = new Array(size);
          var vUp = new Array(size);
          var snake = function(start5, end3, diag) {
            return {
              start: start5,
              end: end3,
              diag
            };
          };
          var buildScript = function(start1, end1, start22, end22, script2) {
            var middle = getMiddleSnake(start1, end1, start22, end22);
            if (middle === null || middle.start === end1 && middle.diag === end1 - end22 || middle.end === start1 && middle.diag === start1 - start22) {
              var i2 = start1;
              var j2 = start22;
              while (i2 < end1 || j2 < end22) {
                if (i2 < end1 && j2 < end22 && left2[i2] === right2[j2]) {
                  script2.push([
                    KEEP,
                    left2[i2]
                  ]);
                  ++i2;
                  ++j2;
                } else {
                  if (end1 - start1 > end22 - start22) {
                    script2.push([
                      DELETE,
                      left2[i2]
                    ]);
                    ++i2;
                  } else {
                    script2.push([
                      INSERT,
                      right2[j2]
                    ]);
                    ++j2;
                  }
                }
              }
            } else {
              buildScript(start1, middle.start, start22, middle.start - middle.diag, script2);
              for (var i22 = middle.start; i22 < middle.end; ++i22) {
                script2.push([
                  KEEP,
                  left2[i22]
                ]);
              }
              buildScript(middle.end, end1, middle.end - middle.diag, end22, script2);
            }
          };
          var buildSnake = function(start5, diag, end1, end22) {
            var end3 = start5;
            while (end3 - diag < end22 && end3 < end1 && left2[end3] === right2[end3 - diag]) {
              ++end3;
            }
            return snake(start5, end3, diag);
          };
          var getMiddleSnake = function(start1, end1, start22, end22) {
            var m2 = end1 - start1;
            var n2 = end22 - start22;
            if (m2 === 0 || n2 === 0) {
              return null;
            }
            var delta = m2 - n2;
            var sum = n2 + m2;
            var offset2 = (sum % 2 === 0 ? sum : sum + 1) / 2;
            vDown[1 + offset2] = start1;
            vUp[1 + offset2] = end1 + 1;
            var d2, k2, i2, x2, y2;
            for (d2 = 0; d2 <= offset2; ++d2) {
              for (k2 = -d2; k2 <= d2; k2 += 2) {
                i2 = k2 + offset2;
                if (k2 === -d2 || k2 !== d2 && vDown[i2 - 1] < vDown[i2 + 1]) {
                  vDown[i2] = vDown[i2 + 1];
                } else {
                  vDown[i2] = vDown[i2 - 1] + 1;
                }
                x2 = vDown[i2];
                y2 = x2 - start1 + start22 - k2;
                while (x2 < end1 && y2 < end22 && left2[x2] === right2[y2]) {
                  vDown[i2] = ++x2;
                  ++y2;
                }
                if (delta % 2 !== 0 && delta - d2 <= k2 && k2 <= delta + d2) {
                  if (vUp[i2 - delta] <= vDown[i2]) {
                    return buildSnake(vUp[i2 - delta], k2 + start1 - start22, end1, end22);
                  }
                }
              }
              for (k2 = delta - d2; k2 <= delta + d2; k2 += 2) {
                i2 = k2 + offset2 - delta;
                if (k2 === delta - d2 || k2 !== delta + d2 && vUp[i2 + 1] <= vUp[i2 - 1]) {
                  vUp[i2] = vUp[i2 + 1] - 1;
                } else {
                  vUp[i2] = vUp[i2 - 1];
                }
                x2 = vUp[i2] - 1;
                y2 = x2 - start1 + start22 - k2;
                while (x2 >= start1 && y2 >= start22 && left2[x2] === right2[y2]) {
                  vUp[i2] = x2--;
                  y2--;
                }
                if (delta % 2 === 0 && -d2 <= k2 && k2 <= d2) {
                  if (vUp[i2] <= vDown[i2 + delta]) {
                    return buildSnake(vUp[i2], k2 + start1 - start22, end1, end22);
                  }
                }
              }
            }
          };
          var script = [];
          buildScript(0, left2.length, 0, right2.length, script);
          return script;
        };
        var getOuterHtml = function(elm) {
          if (isElement$5(elm)) {
            return elm.outerHTML;
          } else if (isText$7(elm)) {
            return Entities.encodeRaw(elm.data, false);
          } else if (isComment(elm)) {
            return "<!--" + elm.data + "-->";
          }
          return "";
        };
        var createFragment = function(html) {
          var node;
          var container = document.createElement("div");
          var frag = document.createDocumentFragment();
          if (html) {
            container.innerHTML = html;
          }
          while (node = container.firstChild) {
            frag.appendChild(node);
          }
          return frag;
        };
        var insertAt = function(elm, html, index) {
          var fragment = createFragment(html);
          if (elm.hasChildNodes() && index < elm.childNodes.length) {
            var target = elm.childNodes[index];
            target.parentNode.insertBefore(fragment, target);
          } else {
            elm.appendChild(fragment);
          }
        };
        var removeAt = function(elm, index) {
          if (elm.hasChildNodes() && index < elm.childNodes.length) {
            var target = elm.childNodes[index];
            target.parentNode.removeChild(target);
          }
        };
        var applyDiff = function(diff2, elm) {
          var index = 0;
          each$k(diff2, function(action2) {
            if (action2[0] === KEEP) {
              index++;
            } else if (action2[0] === INSERT) {
              insertAt(elm, action2[1], index);
              index++;
            } else if (action2[0] === DELETE) {
              removeAt(elm, index);
            }
          });
        };
        var read$2 = function(elm) {
          return filter$4(map$3(from(elm.childNodes), getOuterHtml), function(item) {
            return item.length > 0;
          });
        };
        var write2 = function(fragments, elm) {
          var currentFragments = map$3(from(elm.childNodes), getOuterHtml);
          applyDiff(diff(currentFragments, fragments), elm);
          return elm;
        };
        var lazyTempDocument = cached(function() {
          return document.implementation.createHTMLDocument("undo");
        });
        var hasIframes = function(html) {
          return html.indexOf("</iframe>") !== -1;
        };
        var createFragmentedLevel = function(fragments) {
          return {
            type: "fragmented",
            fragments,
            content: "",
            bookmark: null,
            beforeBookmark: null
          };
        };
        var createCompleteLevel = function(content) {
          return {
            type: "complete",
            fragments: null,
            content,
            bookmark: null,
            beforeBookmark: null
          };
        };
        var createFromEditor = function(editor) {
          var fragments = read$2(editor.getBody());
          var trimmedFragments = bind(fragments, function(html) {
            var trimmed = trimInternal(editor.serializer, html);
            return trimmed.length > 0 ? [trimmed] : [];
          });
          var content = trimmedFragments.join("");
          return hasIframes(content) ? createFragmentedLevel(trimmedFragments) : createCompleteLevel(content);
        };
        var applyToEditor = function(editor, level, before2) {
          var bookmark = before2 ? level.beforeBookmark : level.bookmark;
          if (level.type === "fragmented") {
            write2(level.fragments, editor.getBody());
          } else {
            editor.setContent(level.content, {
              format: "raw",
              no_selection: isNonNullable(bookmark) && isPathBookmark(bookmark) ? !bookmark.isFakeCaret : true
            });
          }
          editor.selection.moveToBookmark(bookmark);
        };
        var getLevelContent = function(level) {
          return level.type === "fragmented" ? level.fragments.join("") : level.content;
        };
        var getCleanLevelContent = function(level) {
          var elm = SugarElement.fromTag("body", lazyTempDocument());
          set2(elm, getLevelContent(level));
          each$k(descendants(elm, "*[data-mce-bogus]"), unwrap);
          return get$3(elm);
        };
        var hasEqualContent = function(level1, level2) {
          return getLevelContent(level1) === getLevelContent(level2);
        };
        var hasEqualCleanedContent = function(level1, level2) {
          return getCleanLevelContent(level1) === getCleanLevelContent(level2);
        };
        var isEq$1 = function(level1, level2) {
          if (!level1 || !level2) {
            return false;
          } else if (hasEqualContent(level1, level2)) {
            return true;
          } else {
            return hasEqualCleanedContent(level1, level2);
          }
        };
        var isUnlocked = function(locks) {
          return locks.get() === 0;
        };
        var setTyping = function(undoManager, typing, locks) {
          if (isUnlocked(locks)) {
            undoManager.typing = typing;
          }
        };
        var endTyping = function(undoManager, locks) {
          if (undoManager.typing) {
            setTyping(undoManager, false, locks);
            undoManager.add();
          }
        };
        var endTypingLevelIgnoreLocks = function(undoManager) {
          if (undoManager.typing) {
            undoManager.typing = false;
            undoManager.add();
          }
        };
        var beforeChange$1 = function(editor, locks, beforeBookmark) {
          if (isUnlocked(locks)) {
            beforeBookmark.set(getUndoBookmark(editor.selection));
          }
        };
        var addUndoLevel$1 = function(editor, undoManager, index, locks, beforeBookmark, level, event) {
          var currentLevel = createFromEditor(editor);
          level = level || {};
          level = Tools.extend(level, currentLevel);
          if (isUnlocked(locks) === false || editor.removed) {
            return null;
          }
          var lastLevel = undoManager.data[index.get()];
          if (editor.fire("BeforeAddUndo", {
            level,
            lastLevel,
            originalEvent: event
          }).isDefaultPrevented()) {
            return null;
          }
          if (lastLevel && isEq$1(lastLevel, level)) {
            return null;
          }
          if (undoManager.data[index.get()]) {
            beforeBookmark.get().each(function(bm) {
              undoManager.data[index.get()].beforeBookmark = bm;
            });
          }
          var customUndoRedoLevels = getCustomUndoRedoLevels(editor);
          if (customUndoRedoLevels) {
            if (undoManager.data.length > customUndoRedoLevels) {
              for (var i2 = 0; i2 < undoManager.data.length - 1; i2++) {
                undoManager.data[i2] = undoManager.data[i2 + 1];
              }
              undoManager.data.length--;
              index.set(undoManager.data.length);
            }
          }
          level.bookmark = getUndoBookmark(editor.selection);
          if (index.get() < undoManager.data.length - 1) {
            undoManager.data.length = index.get() + 1;
          }
          undoManager.data.push(level);
          index.set(undoManager.data.length - 1);
          var args = {
            level,
            lastLevel,
            originalEvent: event
          };
          if (index.get() > 0) {
            editor.setDirty(true);
            editor.fire("AddUndo", args);
            editor.fire("change", args);
          } else {
            editor.fire("AddUndo", args);
          }
          return level;
        };
        var clear$1 = function(editor, undoManager, index) {
          undoManager.data = [];
          index.set(0);
          undoManager.typing = false;
          editor.fire("ClearUndos");
        };
        var extra$1 = function(editor, undoManager, index, callback1, callback2) {
          if (undoManager.transact(callback1)) {
            var bookmark = undoManager.data[index.get()].bookmark;
            var lastLevel = undoManager.data[index.get() - 1];
            applyToEditor(editor, lastLevel, true);
            if (undoManager.transact(callback2)) {
              undoManager.data[index.get() - 1].beforeBookmark = bookmark;
            }
          }
        };
        var redo$1 = function(editor, index, data2) {
          var level;
          if (index.get() < data2.length - 1) {
            index.set(index.get() + 1);
            level = data2[index.get()];
            applyToEditor(editor, level, false);
            editor.setDirty(true);
            editor.fire("Redo", { level });
          }
          return level;
        };
        var undo$1 = function(editor, undoManager, locks, index) {
          var level;
          if (undoManager.typing) {
            undoManager.add();
            undoManager.typing = false;
            setTyping(undoManager, false, locks);
          }
          if (index.get() > 0) {
            index.set(index.get() - 1);
            level = undoManager.data[index.get()];
            applyToEditor(editor, level, true);
            editor.setDirty(true);
            editor.fire("Undo", { level });
          }
          return level;
        };
        var reset$1 = function(undoManager) {
          undoManager.clear();
          undoManager.add();
        };
        var hasUndo$1 = function(editor, undoManager, index) {
          return index.get() > 0 || undoManager.typing && undoManager.data[0] && !isEq$1(createFromEditor(editor), undoManager.data[0]);
        };
        var hasRedo$1 = function(undoManager, index) {
          return index.get() < undoManager.data.length - 1 && !undoManager.typing;
        };
        var transact$1 = function(undoManager, locks, callback2) {
          endTyping(undoManager, locks);
          undoManager.beforeChange();
          undoManager.ignore(callback2);
          return undoManager.add();
        };
        var ignore$1 = function(locks, callback2) {
          try {
            locks.set(locks.get() + 1);
            callback2();
          } finally {
            locks.set(locks.get() - 1);
          }
        };
        var addVisualInternal = function(editor, elm) {
          var dom2 = editor.dom;
          var scope = isNonNullable(elm) ? elm : editor.getBody();
          if (isUndefined(editor.hasVisual)) {
            editor.hasVisual = isVisualAidsEnabled(editor);
          }
          each$k(dom2.select("table,a", scope), function(matchedElm) {
            switch (matchedElm.nodeName) {
              case "TABLE":
                var cls = getVisualAidsTableClass(editor);
                var value2 = dom2.getAttrib(matchedElm, "border");
                if ((!value2 || value2 === "0") && editor.hasVisual) {
                  dom2.addClass(matchedElm, cls);
                } else {
                  dom2.removeClass(matchedElm, cls);
                }
                break;
              case "A":
                if (!dom2.getAttrib(matchedElm, "href")) {
                  var value_1 = dom2.getAttrib(matchedElm, "name") || matchedElm.id;
                  var cls_1 = getVisualAidsAnchorClass(editor);
                  if (value_1 && editor.hasVisual) {
                    dom2.addClass(matchedElm, cls_1);
                  } else {
                    dom2.removeClass(matchedElm, cls_1);
                  }
                }
                break;
            }
          });
          editor.fire("VisualAid", {
            element: elm,
            hasVisual: editor.hasVisual
          });
        };
        var makePlainAdaptor = function(editor) {
          return {
            undoManager: {
              beforeChange: function(locks, beforeBookmark) {
                return beforeChange$1(editor, locks, beforeBookmark);
              },
              add: function(undoManager, index, locks, beforeBookmark, level, event) {
                return addUndoLevel$1(editor, undoManager, index, locks, beforeBookmark, level, event);
              },
              undo: function(undoManager, locks, index) {
                return undo$1(editor, undoManager, locks, index);
              },
              redo: function(index, data2) {
                return redo$1(editor, index, data2);
              },
              clear: function(undoManager, index) {
                return clear$1(editor, undoManager, index);
              },
              reset: function(undoManager) {
                return reset$1(undoManager);
              },
              hasUndo: function(undoManager, index) {
                return hasUndo$1(editor, undoManager, index);
              },
              hasRedo: function(undoManager, index) {
                return hasRedo$1(undoManager, index);
              },
              transact: function(undoManager, locks, callback2) {
                return transact$1(undoManager, locks, callback2);
              },
              ignore: function(locks, callback2) {
                return ignore$1(locks, callback2);
              },
              extra: function(undoManager, index, callback1, callback2) {
                return extra$1(editor, undoManager, index, callback1, callback2);
              }
            },
            formatter: {
              match: function(name2, vars, node, similar) {
                return match$2(editor, name2, vars, node, similar);
              },
              matchAll: function(names2, vars) {
                return matchAll(editor, names2, vars);
              },
              matchNode: function(node, name2, vars, similar) {
                return matchNode(editor, node, name2, vars, similar);
              },
              canApply: function(name2) {
                return canApply(editor, name2);
              },
              closest: function(names2) {
                return closest(editor, names2);
              },
              apply: function(name2, vars, node) {
                return applyFormat$1(editor, name2, vars, node);
              },
              remove: function(name2, vars, node, similar) {
                return remove$1(editor, name2, vars, node, similar);
              },
              toggle: function(name2, vars, node) {
                return toggle(editor, name2, vars, node);
              },
              formatChanged: function(registeredFormatListeners, formats, callback2, similar, vars) {
                return formatChangedInternal(editor, registeredFormatListeners, formats, callback2, similar, vars);
              }
            },
            editor: {
              getContent: function(args, format3) {
                return getContentInternal(editor, args, format3);
              },
              setContent: function(content, args) {
                return setContentInternal(editor, content, args);
              },
              insertContent: function(value2, details) {
                return insertHtmlAtCaret(editor, value2, details);
              },
              addVisual: function(elm) {
                return addVisualInternal(editor, elm);
              }
            },
            selection: {
              getContent: function(format3, args) {
                return getSelectedContentInternal(editor, format3, args);
              }
            },
            raw: {
              getModel: function() {
                return Optional.none();
              }
            }
          };
        };
        var makeRtcAdaptor = function(rtcEditor) {
          var defaultVars = function(vars) {
            return isObject2(vars) ? vars : {};
          };
          var undoManager = rtcEditor.undoManager, formatter = rtcEditor.formatter, editor = rtcEditor.editor, selection = rtcEditor.selection, raw = rtcEditor.raw;
          return {
            undoManager: {
              beforeChange: undoManager.beforeChange,
              add: undoManager.add,
              undo: undoManager.undo,
              redo: undoManager.redo,
              clear: undoManager.clear,
              reset: undoManager.reset,
              hasUndo: undoManager.hasUndo,
              hasRedo: undoManager.hasRedo,
              transact: function(_undoManager, _locks, fn3) {
                return undoManager.transact(fn3);
              },
              ignore: function(_locks, callback2) {
                return undoManager.ignore(callback2);
              },
              extra: function(_undoManager, _index, callback1, callback2) {
                return undoManager.extra(callback1, callback2);
              }
            },
            formatter: {
              match: function(name2, vars, _node, similar) {
                return formatter.match(name2, defaultVars(vars), similar);
              },
              matchAll: formatter.matchAll,
              matchNode: formatter.matchNode,
              canApply: function(name2) {
                return formatter.canApply(name2);
              },
              closest: function(names2) {
                return formatter.closest(names2);
              },
              apply: function(name2, vars, _node) {
                return formatter.apply(name2, defaultVars(vars));
              },
              remove: function(name2, vars, _node, _similar) {
                return formatter.remove(name2, defaultVars(vars));
              },
              toggle: function(name2, vars, _node) {
                return formatter.toggle(name2, defaultVars(vars));
              },
              formatChanged: function(_rfl, formats, callback2, similar, vars) {
                return formatter.formatChanged(formats, callback2, similar, vars);
              }
            },
            editor: {
              getContent: function(args, _format) {
                return editor.getContent(args);
              },
              setContent: function(content, args) {
                return editor.setContent(content, args);
              },
              insertContent: function(content, _details) {
                return editor.insertContent(content);
              },
              addVisual: editor.addVisual
            },
            selection: {
              getContent: function(_format, args) {
                return selection.getContent(args);
              }
            },
            raw: {
              getModel: function() {
                return Optional.some(raw.getRawModel());
              }
            }
          };
        };
        var makeNoopAdaptor = function() {
          var nul = constant(null);
          var empty2 = constant("");
          return {
            undoManager: {
              beforeChange: noop3,
              add: nul,
              undo: nul,
              redo: nul,
              clear: noop3,
              reset: noop3,
              hasUndo: never,
              hasRedo: never,
              transact: nul,
              ignore: noop3,
              extra: noop3
            },
            formatter: {
              match: never,
              matchAll: constant([]),
              matchNode: constant(void 0),
              canApply: never,
              closest: empty2,
              apply: noop3,
              remove: noop3,
              toggle: noop3,
              formatChanged: constant({ unbind: noop3 })
            },
            editor: {
              getContent: empty2,
              setContent: empty2,
              insertContent: noop3,
              addVisual: noop3
            },
            selection: { getContent: empty2 },
            raw: { getModel: constant(Optional.none()) }
          };
        };
        var isRtc = function(editor) {
          return has$2(editor.plugins, "rtc");
        };
        var getRtcSetup = function(editor) {
          return get$9(editor.plugins, "rtc").bind(function(rtcPlugin) {
            return Optional.from(rtcPlugin.setup);
          });
        };
        var setup$i = function(editor) {
          var editorCast = editor;
          return getRtcSetup(editor).fold(function() {
            editorCast.rtcInstance = makePlainAdaptor(editor);
            return Optional.none();
          }, function(setup2) {
            editorCast.rtcInstance = makeNoopAdaptor();
            return Optional.some(function() {
              return setup2().then(function(rtcEditor) {
                editorCast.rtcInstance = makeRtcAdaptor(rtcEditor);
                return rtcEditor.rtc.isRemote;
              });
            });
          });
        };
        var getRtcInstanceWithFallback = function(editor) {
          return editor.rtcInstance ? editor.rtcInstance : makePlainAdaptor(editor);
        };
        var getRtcInstanceWithError = function(editor) {
          var rtcInstance = editor.rtcInstance;
          if (!rtcInstance) {
            throw new Error("Failed to get RTC instance not yet initialized.");
          } else {
            return rtcInstance;
          }
        };
        var beforeChange = function(editor, locks, beforeBookmark) {
          getRtcInstanceWithError(editor).undoManager.beforeChange(locks, beforeBookmark);
        };
        var addUndoLevel = function(editor, undoManager, index, locks, beforeBookmark, level, event) {
          return getRtcInstanceWithError(editor).undoManager.add(undoManager, index, locks, beforeBookmark, level, event);
        };
        var undo = function(editor, undoManager, locks, index) {
          return getRtcInstanceWithError(editor).undoManager.undo(undoManager, locks, index);
        };
        var redo = function(editor, index, data2) {
          return getRtcInstanceWithError(editor).undoManager.redo(index, data2);
        };
        var clear = function(editor, undoManager, index) {
          getRtcInstanceWithError(editor).undoManager.clear(undoManager, index);
        };
        var reset = function(editor, undoManager) {
          getRtcInstanceWithError(editor).undoManager.reset(undoManager);
        };
        var hasUndo = function(editor, undoManager, index) {
          return getRtcInstanceWithError(editor).undoManager.hasUndo(undoManager, index);
        };
        var hasRedo = function(editor, undoManager, index) {
          return getRtcInstanceWithError(editor).undoManager.hasRedo(undoManager, index);
        };
        var transact = function(editor, undoManager, locks, callback2) {
          return getRtcInstanceWithError(editor).undoManager.transact(undoManager, locks, callback2);
        };
        var ignore = function(editor, locks, callback2) {
          getRtcInstanceWithError(editor).undoManager.ignore(locks, callback2);
        };
        var extra = function(editor, undoManager, index, callback1, callback2) {
          getRtcInstanceWithError(editor).undoManager.extra(undoManager, index, callback1, callback2);
        };
        var matchFormat = function(editor, name2, vars, node, similar) {
          return getRtcInstanceWithError(editor).formatter.match(name2, vars, node, similar);
        };
        var matchAllFormats = function(editor, names2, vars) {
          return getRtcInstanceWithError(editor).formatter.matchAll(names2, vars);
        };
        var matchNodeFormat = function(editor, node, name2, vars, similar) {
          return getRtcInstanceWithError(editor).formatter.matchNode(node, name2, vars, similar);
        };
        var canApplyFormat = function(editor, name2) {
          return getRtcInstanceWithError(editor).formatter.canApply(name2);
        };
        var closestFormat = function(editor, names2) {
          return getRtcInstanceWithError(editor).formatter.closest(names2);
        };
        var applyFormat = function(editor, name2, vars, node) {
          getRtcInstanceWithError(editor).formatter.apply(name2, vars, node);
        };
        var removeFormat = function(editor, name2, vars, node, similar) {
          getRtcInstanceWithError(editor).formatter.remove(name2, vars, node, similar);
        };
        var toggleFormat = function(editor, name2, vars, node) {
          getRtcInstanceWithError(editor).formatter.toggle(name2, vars, node);
        };
        var formatChanged = function(editor, registeredFormatListeners, formats, callback2, similar, vars) {
          return getRtcInstanceWithError(editor).formatter.formatChanged(registeredFormatListeners, formats, callback2, similar, vars);
        };
        var getContent$2 = function(editor, args, format3) {
          return getRtcInstanceWithFallback(editor).editor.getContent(args, format3);
        };
        var setContent$2 = function(editor, content, args) {
          return getRtcInstanceWithFallback(editor).editor.setContent(content, args);
        };
        var insertContent = function(editor, value2, details) {
          return getRtcInstanceWithFallback(editor).editor.insertContent(value2, details);
        };
        var getSelectedContent = function(editor, format3, args) {
          return getRtcInstanceWithError(editor).selection.getContent(format3, args);
        };
        var addVisual$1 = function(editor, elm) {
          return getRtcInstanceWithError(editor).editor.addVisual(elm);
        };
        var getContent$1 = function(editor, args) {
          if (args === void 0) {
            args = {};
          }
          var format3 = args.format ? args.format : "html";
          return getSelectedContent(editor, format3, args);
        };
        var removeEmpty = function(text) {
          if (text.dom.length === 0) {
            remove$7(text);
            return Optional.none();
          } else {
            return Optional.some(text);
          }
        };
        var walkPastBookmark = function(node, start5) {
          return node.filter(function(elm) {
            return BookmarkManager.isBookmarkNode(elm.dom);
          }).bind(start5 ? nextSibling : prevSibling);
        };
        var merge2 = function(outer, inner, rng, start5) {
          var outerElm = outer.dom;
          var innerElm = inner.dom;
          var oldLength = start5 ? outerElm.length : innerElm.length;
          if (start5) {
            mergeTextNodes(outerElm, innerElm, false, !start5);
            rng.setStart(innerElm, oldLength);
          } else {
            mergeTextNodes(innerElm, outerElm, false, !start5);
            rng.setEnd(innerElm, oldLength);
          }
        };
        var normalizeTextIfRequired = function(inner, start5) {
          parent(inner).each(function(root) {
            var text = inner.dom;
            if (start5 && needsToBeNbspLeft(root, CaretPosition(text, 0))) {
              normalizeWhitespaceAfter(text, 0);
            } else if (!start5 && needsToBeNbspRight(root, CaretPosition(text, text.length))) {
              normalizeWhitespaceBefore(text, text.length);
            }
          });
        };
        var mergeAndNormalizeText = function(outerNode, innerNode, rng, start5) {
          outerNode.bind(function(outer) {
            var normalizer = start5 ? normalizeWhitespaceBefore : normalizeWhitespaceAfter;
            normalizer(outer.dom, start5 ? outer.dom.length : 0);
            return innerNode.filter(isText$8).map(function(inner) {
              return merge2(outer, inner, rng, start5);
            });
          }).orThunk(function() {
            var innerTextNode = walkPastBookmark(innerNode, start5).or(innerNode).filter(isText$8);
            return innerTextNode.map(function(inner) {
              return normalizeTextIfRequired(inner, start5);
            });
          });
        };
        var rngSetContent = function(rng, fragment) {
          var firstChild2 = Optional.from(fragment.firstChild).map(SugarElement.fromDom);
          var lastChild2 = Optional.from(fragment.lastChild).map(SugarElement.fromDom);
          rng.deleteContents();
          rng.insertNode(fragment);
          var prevText = firstChild2.bind(prevSibling).filter(isText$8).bind(removeEmpty);
          var nextText = lastChild2.bind(nextSibling).filter(isText$8).bind(removeEmpty);
          mergeAndNormalizeText(prevText, firstChild2, rng, true);
          mergeAndNormalizeText(nextText, lastChild2, rng, false);
          rng.collapse(false);
        };
        var setupArgs = function(args, content) {
          return __assign(__assign({ format: "html" }, args), {
            set: true,
            selection: true,
            content
          });
        };
        var cleanContent = function(editor, args) {
          if (args.format !== "raw") {
            var rng = editor.selection.getRng();
            var contextBlock = editor.dom.getParent(rng.commonAncestorContainer, editor.dom.isBlock);
            var contextArgs = contextBlock ? { context: contextBlock.nodeName.toLowerCase() } : {};
            var node = editor.parser.parse(args.content, __assign(__assign({
              isRootContent: true,
              forced_root_block: false
            }, contextArgs), args));
            return HtmlSerializer({ validate: editor.validate }, editor.schema).serialize(node);
          } else {
            return args.content;
          }
        };
        var setContent$1 = function(editor, content, args) {
          if (args === void 0) {
            args = {};
          }
          var defaultedArgs = setupArgs(args, content);
          var updatedArgs = defaultedArgs;
          if (!defaultedArgs.no_events) {
            var eventArgs = editor.fire("BeforeSetContent", defaultedArgs);
            if (eventArgs.isDefaultPrevented()) {
              editor.fire("SetContent", eventArgs);
              return;
            } else {
              updatedArgs = eventArgs;
            }
          }
          updatedArgs.content = cleanContent(editor, updatedArgs);
          var rng = editor.selection.getRng();
          rngSetContent(rng, rng.createContextualFragment(updatedArgs.content));
          editor.selection.setRng(rng);
          scrollRangeIntoView(editor, rng);
          if (!updatedArgs.no_events) {
            editor.fire("SetContent", updatedArgs);
          }
        };
        var deleteFromCallbackMap = function(callbackMap, selector, callback2) {
          if (callbackMap && has$2(callbackMap, selector)) {
            var newCallbacks = filter$4(callbackMap[selector], function(cb) {
              return cb !== callback2;
            });
            if (newCallbacks.length === 0) {
              delete callbackMap[selector];
            } else {
              callbackMap[selector] = newCallbacks;
            }
          }
        };
        function SelectorChanged(dom2, editor) {
          var selectorChangedData;
          var currentSelectors;
          var findMatchingNode = function(selector, nodes) {
            return find$3(nodes, function(node) {
              return dom2.is(node, selector);
            });
          };
          var getParents2 = function(elem) {
            return dom2.getParents(elem, null, dom2.getRoot());
          };
          return {
            selectorChangedWithUnbind: function(selector, callback2) {
              if (!selectorChangedData) {
                selectorChangedData = {};
                currentSelectors = {};
                editor.on("NodeChange", function(e2) {
                  var node = e2.element;
                  var parents2 = getParents2(node);
                  var matchedSelectors = {};
                  Tools.each(selectorChangedData, function(callbacks, selector2) {
                    findMatchingNode(selector2, parents2).each(function(node2) {
                      if (!currentSelectors[selector2]) {
                        each$k(callbacks, function(callback3) {
                          callback3(true, {
                            node: node2,
                            selector: selector2,
                            parents: parents2
                          });
                        });
                        currentSelectors[selector2] = callbacks;
                      }
                      matchedSelectors[selector2] = callbacks;
                    });
                  });
                  Tools.each(currentSelectors, function(callbacks, selector2) {
                    if (!matchedSelectors[selector2]) {
                      delete currentSelectors[selector2];
                      Tools.each(callbacks, function(callback3) {
                        callback3(false, {
                          node,
                          selector: selector2,
                          parents: parents2
                        });
                      });
                    }
                  });
                });
              }
              if (!selectorChangedData[selector]) {
                selectorChangedData[selector] = [];
              }
              selectorChangedData[selector].push(callback2);
              findMatchingNode(selector, getParents2(editor.selection.getStart())).each(function() {
                currentSelectors[selector] = selectorChangedData[selector];
              });
              return {
                unbind: function() {
                  deleteFromCallbackMap(selectorChangedData, selector, callback2);
                  deleteFromCallbackMap(currentSelectors, selector, callback2);
                }
              };
            }
          };
        }
        var isNativeIeSelection = function(rng) {
          return !!rng.select;
        };
        var isAttachedToDom = function(node) {
          return !!(node && node.ownerDocument) && contains$1(SugarElement.fromDom(node.ownerDocument), SugarElement.fromDom(node));
        };
        var isValidRange = function(rng) {
          if (!rng) {
            return false;
          } else if (isNativeIeSelection(rng)) {
            return true;
          } else {
            return isAttachedToDom(rng.startContainer) && isAttachedToDom(rng.endContainer);
          }
        };
        var EditorSelection = function(dom2, win, serializer, editor) {
          var selectedRange;
          var explicitRange;
          var selectorChangedWithUnbind = SelectorChanged(dom2, editor).selectorChangedWithUnbind;
          var setCursorLocation = function(node, offset2) {
            var rng = dom2.createRng();
            if (isNonNullable(node) && isNonNullable(offset2)) {
              rng.setStart(node, offset2);
              rng.setEnd(node, offset2);
              setRng(rng);
              collapse2(false);
            } else {
              moveEndPoint(dom2, rng, editor.getBody(), true);
              setRng(rng);
            }
          };
          var getContent2 = function(args) {
            return getContent$1(editor, args);
          };
          var setContent2 = function(content, args) {
            return setContent$1(editor, content, args);
          };
          var getStart$12 = function(real) {
            return getStart(editor.getBody(), getRng$1(), real);
          };
          var getEnd$1 = function(real) {
            return getEnd(editor.getBody(), getRng$1(), real);
          };
          var getBookmark2 = function(type2, normalized) {
            return bookmarkManager.getBookmark(type2, normalized);
          };
          var moveToBookmark2 = function(bookmark) {
            return bookmarkManager.moveToBookmark(bookmark);
          };
          var select$12 = function(node, content) {
            select(dom2, node, content).each(setRng);
            return node;
          };
          var isCollapsed = function() {
            var rng = getRng$1(), sel = getSel();
            if (!rng || rng.item) {
              return false;
            }
            if (rng.compareEndPoints) {
              return rng.compareEndPoints("StartToEnd", rng) === 0;
            }
            return !sel || rng.collapsed;
          };
          var collapse2 = function(toStart) {
            var rng = getRng$1();
            rng.collapse(!!toStart);
            setRng(rng);
          };
          var getSel = function() {
            return win.getSelection ? win.getSelection() : win.document.selection;
          };
          var getRng$1 = function() {
            var selection, rng, elm;
            var tryCompareBoundaryPoints = function(how, sourceRange, destinationRange) {
              try {
                return sourceRange.compareBoundaryPoints(how, destinationRange);
              } catch (ex) {
                return -1;
              }
            };
            var doc2 = win.document;
            if (editor.bookmark !== void 0 && hasFocus(editor) === false) {
              var bookmark = getRng(editor);
              if (bookmark.isSome()) {
                return bookmark.map(function(r3) {
                  return processRanges(editor, [r3])[0];
                }).getOr(doc2.createRange());
              }
            }
            try {
              if ((selection = getSel()) && !isRestrictedNode(selection.anchorNode)) {
                if (selection.rangeCount > 0) {
                  rng = selection.getRangeAt(0);
                } else {
                  rng = selection.createRange ? selection.createRange() : doc2.createRange();
                }
                rng = processRanges(editor, [rng])[0];
              }
            } catch (ex) {
            }
            if (!rng) {
              rng = doc2.createRange ? doc2.createRange() : doc2.body.createTextRange();
            }
            if (rng.setStart && rng.startContainer.nodeType === 9 && rng.collapsed) {
              elm = dom2.getRoot();
              rng.setStart(elm, 0);
              rng.setEnd(elm, 0);
            }
            if (selectedRange && explicitRange) {
              if (tryCompareBoundaryPoints(rng.START_TO_START, rng, selectedRange) === 0 && tryCompareBoundaryPoints(rng.END_TO_END, rng, selectedRange) === 0) {
                rng = explicitRange;
              } else {
                selectedRange = null;
                explicitRange = null;
              }
            }
            return rng;
          };
          var setRng = function(rng, forward) {
            var node;
            if (!isValidRange(rng)) {
              return;
            }
            var ieRange = isNativeIeSelection(rng) ? rng : null;
            if (ieRange) {
              explicitRange = null;
              try {
                ieRange.select();
              } catch (ex) {
              }
              return;
            }
            var sel = getSel();
            var evt = editor.fire("SetSelectionRange", {
              range: rng,
              forward
            });
            rng = evt.range;
            if (sel) {
              explicitRange = rng;
              try {
                sel.removeAllRanges();
                sel.addRange(rng);
              } catch (ex) {
              }
              if (forward === false && sel.extend) {
                sel.collapse(rng.endContainer, rng.endOffset);
                sel.extend(rng.startContainer, rng.startOffset);
              }
              selectedRange = sel.rangeCount > 0 ? sel.getRangeAt(0) : null;
            }
            if (!rng.collapsed && rng.startContainer === rng.endContainer && sel.setBaseAndExtent && !Env.ie) {
              if (rng.endOffset - rng.startOffset < 2) {
                if (rng.startContainer.hasChildNodes()) {
                  node = rng.startContainer.childNodes[rng.startOffset];
                  if (node && node.tagName === "IMG") {
                    sel.setBaseAndExtent(rng.startContainer, rng.startOffset, rng.endContainer, rng.endOffset);
                    if (sel.anchorNode !== rng.startContainer || sel.focusNode !== rng.endContainer) {
                      sel.setBaseAndExtent(node, 0, node, 1);
                    }
                  }
                }
              }
            }
            editor.fire("AfterSetSelectionRange", {
              range: rng,
              forward
            });
          };
          var setNode = function(elm) {
            setContent2(dom2.getOuterHTML(elm));
            return elm;
          };
          var getNode$12 = function() {
            return getNode(editor.getBody(), getRng$1());
          };
          var getSelectedBlocks$1 = function(startElm, endElm) {
            return getSelectedBlocks(dom2, getRng$1(), startElm, endElm);
          };
          var isForward = function() {
            var sel = getSel();
            var anchorNode = sel === null || sel === void 0 ? void 0 : sel.anchorNode;
            var focusNode = sel === null || sel === void 0 ? void 0 : sel.focusNode;
            if (!sel || !anchorNode || !focusNode || isRestrictedNode(anchorNode) || isRestrictedNode(focusNode)) {
              return true;
            }
            var anchorRange = dom2.createRng();
            anchorRange.setStart(anchorNode, sel.anchorOffset);
            anchorRange.collapse(true);
            var focusRange = dom2.createRng();
            focusRange.setStart(focusNode, sel.focusOffset);
            focusRange.collapse(true);
            return anchorRange.compareBoundaryPoints(anchorRange.START_TO_START, focusRange) <= 0;
          };
          var normalize2 = function() {
            var rng = getRng$1();
            var sel = getSel();
            if (!hasMultipleRanges(sel) && hasAnyRanges(editor)) {
              var normRng = normalize$2(dom2, rng);
              normRng.each(function(normRng2) {
                setRng(normRng2, isForward());
              });
              return normRng.getOr(rng);
            }
            return rng;
          };
          var selectorChanged = function(selector, callback2) {
            selectorChangedWithUnbind(selector, callback2);
            return exports2;
          };
          var getScrollContainer = function() {
            var scrollContainer;
            var node = dom2.getRoot();
            while (node && node.nodeName !== "BODY") {
              if (node.scrollHeight > node.clientHeight) {
                scrollContainer = node;
                break;
              }
              node = node.parentNode;
            }
            return scrollContainer;
          };
          var scrollIntoView = function(elm, alignToTop) {
            if (isNonNullable(elm)) {
              scrollElementIntoView(editor, elm, alignToTop);
            } else {
              scrollRangeIntoView(editor, getRng$1(), alignToTop);
            }
          };
          var placeCaretAt = function(clientX, clientY) {
            return setRng(fromPoint(clientX, clientY, editor.getDoc()));
          };
          var getBoundingClientRect3 = function() {
            var rng = getRng$1();
            return rng.collapsed ? CaretPosition.fromRangeStart(rng).getClientRects()[0] : rng.getBoundingClientRect();
          };
          var destroy2 = function() {
            win = selectedRange = explicitRange = null;
            controlSelection.destroy();
          };
          var exports2 = {
            bookmarkManager: null,
            controlSelection: null,
            dom: dom2,
            win,
            serializer,
            editor,
            collapse: collapse2,
            setCursorLocation,
            getContent: getContent2,
            setContent: setContent2,
            getBookmark: getBookmark2,
            moveToBookmark: moveToBookmark2,
            select: select$12,
            isCollapsed,
            isForward,
            setNode,
            getNode: getNode$12,
            getSel,
            setRng,
            getRng: getRng$1,
            getStart: getStart$12,
            getEnd: getEnd$1,
            getSelectedBlocks: getSelectedBlocks$1,
            normalize: normalize2,
            selectorChanged,
            selectorChangedWithUnbind,
            getScrollContainer,
            scrollIntoView,
            placeCaretAt,
            getBoundingClientRect: getBoundingClientRect3,
            destroy: destroy2
          };
          var bookmarkManager = BookmarkManager(exports2);
          var controlSelection = ControlSelection(exports2, editor);
          exports2.bookmarkManager = bookmarkManager;
          exports2.controlSelection = controlSelection;
          return exports2;
        };
        var removeAttrs = function(node, names2) {
          each$k(names2, function(name2) {
            node.attr(name2, null);
          });
        };
        var addFontToSpansFilter = function(domParser, styles, fontSizes) {
          domParser.addNodeFilter("font", function(nodes) {
            each$k(nodes, function(node) {
              var props = styles.parse(node.attr("style"));
              var color2 = node.attr("color");
              var face = node.attr("face");
              var size = node.attr("size");
              if (color2) {
                props.color = color2;
              }
              if (face) {
                props["font-family"] = face;
              }
              if (size) {
                props["font-size"] = fontSizes[parseInt(node.attr("size"), 10) - 1];
              }
              node.name = "span";
              node.attr("style", styles.serialize(props));
              removeAttrs(node, [
                "color",
                "face",
                "size"
              ]);
            });
          });
        };
        var addStrikeToSpanFilter = function(domParser, styles) {
          domParser.addNodeFilter("strike", function(nodes) {
            each$k(nodes, function(node) {
              var props = styles.parse(node.attr("style"));
              props["text-decoration"] = "line-through";
              node.name = "span";
              node.attr("style", styles.serialize(props));
            });
          });
        };
        var addFilters = function(domParser, settings) {
          var styles = Styles();
          if (settings.convert_fonts_to_spans) {
            addFontToSpansFilter(domParser, styles, Tools.explode(settings.font_size_legacy_values));
          }
          addStrikeToSpanFilter(domParser, styles);
        };
        var register$2 = function(domParser, settings) {
          if (settings.inline_styles) {
            addFilters(domParser, settings);
          }
        };
        var blobUriToBlob = function(url) {
          return new promiseObj(function(resolve3, reject) {
            var rejectWithError = function() {
              reject("Cannot convert " + url + " to Blob. Resource might not exist or is inaccessible.");
            };
            try {
              var xhr_1 = new XMLHttpRequest();
              xhr_1.open("GET", url, true);
              xhr_1.responseType = "blob";
              xhr_1.onload = function() {
                if (xhr_1.status === 200) {
                  resolve3(xhr_1.response);
                } else {
                  rejectWithError();
                }
              };
              xhr_1.onerror = rejectWithError;
              xhr_1.send();
            } catch (ex) {
              rejectWithError();
            }
          });
        };
        var parseDataUri = function(uri) {
          var type2;
          var uriParts = decodeURIComponent(uri).split(",");
          var matches2 = /data:([^;]+)/.exec(uriParts[0]);
          if (matches2) {
            type2 = matches2[1];
          }
          return {
            type: type2,
            data: uriParts[1]
          };
        };
        var buildBlob = function(type2, data2) {
          var str;
          try {
            str = atob(data2);
          } catch (e2) {
            return Optional.none();
          }
          var arr2 = new Uint8Array(str.length);
          for (var i2 = 0; i2 < arr2.length; i2++) {
            arr2[i2] = str.charCodeAt(i2);
          }
          return Optional.some(new Blob([arr2], { type: type2 }));
        };
        var dataUriToBlob = function(uri) {
          return new promiseObj(function(resolve3) {
            var _a = parseDataUri(uri), type2 = _a.type, data2 = _a.data;
            buildBlob(type2, data2).fold(function() {
              return resolve3(new Blob([]));
            }, resolve3);
          });
        };
        var uriToBlob = function(url) {
          if (url.indexOf("blob:") === 0) {
            return blobUriToBlob(url);
          }
          if (url.indexOf("data:") === 0) {
            return dataUriToBlob(url);
          }
          return null;
        };
        var blobToDataUri = function(blob) {
          return new promiseObj(function(resolve3) {
            var reader = new FileReader();
            reader.onloadend = function() {
              resolve3(reader.result);
            };
            reader.readAsDataURL(blob);
          });
        };
        var count$1 = 0;
        var uniqueId = function(prefix) {
          return (prefix || "blobid") + count$1++;
        };
        var imageToBlobInfo = function(blobCache, img, resolve3, reject) {
          var base64, blobInfo;
          if (img.src.indexOf("blob:") === 0) {
            blobInfo = blobCache.getByUri(img.src);
            if (blobInfo) {
              resolve3({
                image: img,
                blobInfo
              });
            } else {
              uriToBlob(img.src).then(function(blob) {
                blobToDataUri(blob).then(function(dataUri) {
                  base64 = parseDataUri(dataUri).data;
                  blobInfo = blobCache.create(uniqueId(), blob, base64);
                  blobCache.add(blobInfo);
                  resolve3({
                    image: img,
                    blobInfo
                  });
                });
              }, function(err) {
                reject(err);
              });
            }
            return;
          }
          var _a = parseDataUri(img.src), data2 = _a.data, type2 = _a.type;
          base64 = data2;
          blobInfo = blobCache.getByData(base64, type2);
          if (blobInfo) {
            resolve3({
              image: img,
              blobInfo
            });
          } else {
            uriToBlob(img.src).then(function(blob) {
              blobInfo = blobCache.create(uniqueId(), blob, base64);
              blobCache.add(blobInfo);
              resolve3({
                image: img,
                blobInfo
              });
            }, function(err) {
              reject(err);
            });
          }
        };
        var getAllImages = function(elm) {
          return elm ? from(elm.getElementsByTagName("img")) : [];
        };
        var ImageScanner = function(uploadStatus, blobCache) {
          var cachedPromises = {};
          var findAll2 = function(elm, predicate) {
            if (!predicate) {
              predicate = always;
            }
            var images = filter$4(getAllImages(elm), function(img) {
              var src = img.src;
              if (!Env.fileApi) {
                return false;
              }
              if (img.hasAttribute("data-mce-bogus")) {
                return false;
              }
              if (img.hasAttribute("data-mce-placeholder")) {
                return false;
              }
              if (!src || src === Env.transparentSrc) {
                return false;
              }
              if (src.indexOf("blob:") === 0) {
                return !uploadStatus.isUploaded(src) && predicate(img);
              }
              if (src.indexOf("data:") === 0) {
                return predicate(img);
              }
              return false;
            });
            var promises = map$3(images, function(img) {
              if (cachedPromises[img.src] !== void 0) {
                return new promiseObj(function(resolve3) {
                  cachedPromises[img.src].then(function(imageInfo) {
                    if (typeof imageInfo === "string") {
                      return imageInfo;
                    }
                    resolve3({
                      image: img,
                      blobInfo: imageInfo.blobInfo
                    });
                  });
                });
              }
              var newPromise = new promiseObj(function(resolve3, reject) {
                imageToBlobInfo(blobCache, img, resolve3, reject);
              }).then(function(result) {
                delete cachedPromises[result.image.src];
                return result;
              }).catch(function(error4) {
                delete cachedPromises[img.src];
                return error4;
              });
              cachedPromises[img.src] = newPromise;
              return newPromise;
            });
            return promiseObj.all(promises);
          };
          return { findAll: findAll2 };
        };
        var paddEmptyNode = function(settings, args, blockElements, node) {
          var brPreferred = settings.padd_empty_with_br || args.insert;
          if (brPreferred && blockElements[node.name]) {
            node.empty().append(new AstNode("br", 1)).shortEnded = true;
          } else {
            node.empty().append(new AstNode("#text", 3)).value = nbsp;
          }
        };
        var isPaddedWithNbsp = function(node) {
          return hasOnlyChild(node, "#text") && node.firstChild.value === nbsp;
        };
        var hasOnlyChild = function(node, name2) {
          return node && node.firstChild && node.firstChild === node.lastChild && node.firstChild.name === name2;
        };
        var isPadded = function(schema, node) {
          var rule = schema.getElementRule(node.name);
          return rule && rule.paddEmpty;
        };
        var isEmpty = function(schema, nonEmptyElements, whitespaceElements, node) {
          return node.isEmpty(nonEmptyElements, whitespaceElements, function(node2) {
            return isPadded(schema, node2);
          });
        };
        var isLineBreakNode = function(node, blockElements) {
          return node && (has$2(blockElements, node.name) || node.name === "br");
        };
        var isBogusImage = function(img) {
          return isNonNullable(img.attr("data-mce-bogus"));
        };
        var isInternalImageSource = function(img) {
          return img.attr("src") === Env.transparentSrc || isNonNullable(img.attr("data-mce-placeholder"));
        };
        var isValidDataImg = function(img, settings) {
          if (settings.images_dataimg_filter) {
            var imgElem_1 = new Image();
            imgElem_1.src = img.attr("src");
            each$j(img.attributes.map, function(value2, key) {
              imgElem_1.setAttribute(key, value2);
            });
            return settings.images_dataimg_filter(imgElem_1);
          } else {
            return true;
          }
        };
        var registerBase64ImageFilter = function(parser, settings) {
          var blobCache = settings.blob_cache;
          var processImage = function(img) {
            var inputSrc = img.attr("src");
            if (isInternalImageSource(img) || isBogusImage(img)) {
              return;
            }
            parseDataUri$1(inputSrc).filter(function() {
              return isValidDataImg(img, settings);
            }).bind(function(_a) {
              var type2 = _a.type, data2 = _a.data;
              return Optional.from(blobCache.getByData(data2, type2)).orThunk(function() {
                return buildBlob(type2, data2).map(function(blob) {
                  var blobInfo = blobCache.create(uniqueId(), blob, data2);
                  blobCache.add(blobInfo);
                  return blobInfo;
                });
              });
            }).each(function(blobInfo) {
              img.attr("src", blobInfo.blobUri());
            });
          };
          if (blobCache) {
            parser.addAttributeFilter("src", function(nodes) {
              return each$k(nodes, processImage);
            });
          }
        };
        var register$1 = function(parser, settings) {
          var schema = parser.schema;
          if (settings.remove_trailing_brs) {
            parser.addNodeFilter("br", function(nodes, _2, args) {
              var i2;
              var l2 = nodes.length;
              var node;
              var blockElements = Tools.extend({}, schema.getBlockElements());
              var nonEmptyElements = schema.getNonEmptyElements();
              var parent2, lastParent, prev, prevName;
              var whiteSpaceElements = schema.getWhiteSpaceElements();
              var elementRule, textNode;
              blockElements.body = 1;
              for (i2 = 0; i2 < l2; i2++) {
                node = nodes[i2];
                parent2 = node.parent;
                if (blockElements[node.parent.name] && node === parent2.lastChild) {
                  prev = node.prev;
                  while (prev) {
                    prevName = prev.name;
                    if (prevName !== "span" || prev.attr("data-mce-type") !== "bookmark") {
                      if (prevName === "br") {
                        node = null;
                      }
                      break;
                    }
                    prev = prev.prev;
                  }
                  if (node) {
                    node.remove();
                    if (isEmpty(schema, nonEmptyElements, whiteSpaceElements, parent2)) {
                      elementRule = schema.getElementRule(parent2.name);
                      if (elementRule) {
                        if (elementRule.removeEmpty) {
                          parent2.remove();
                        } else if (elementRule.paddEmpty) {
                          paddEmptyNode(settings, args, blockElements, parent2);
                        }
                      }
                    }
                  }
                } else {
                  lastParent = node;
                  while (parent2 && parent2.firstChild === lastParent && parent2.lastChild === lastParent) {
                    lastParent = parent2;
                    if (blockElements[parent2.name]) {
                      break;
                    }
                    parent2 = parent2.parent;
                  }
                  if (lastParent === parent2 && settings.padd_empty_with_br !== true) {
                    textNode = new AstNode("#text", 3);
                    textNode.value = nbsp;
                    node.replace(textNode);
                  }
                }
              }
            });
          }
          parser.addAttributeFilter("href", function(nodes) {
            var i2 = nodes.length;
            var appendRel = function(rel) {
              var parts = rel.split(" ").filter(function(p2) {
                return p2.length > 0;
              });
              return parts.concat(["noopener"]).sort().join(" ");
            };
            var addNoOpener = function(rel) {
              var newRel = rel ? Tools.trim(rel) : "";
              if (!/\b(noopener)\b/g.test(newRel)) {
                return appendRel(newRel);
              } else {
                return newRel;
              }
            };
            if (!settings.allow_unsafe_link_target) {
              while (i2--) {
                var node = nodes[i2];
                if (node.name === "a" && node.attr("target") === "_blank") {
                  node.attr("rel", addNoOpener(node.attr("rel")));
                }
              }
            }
          });
          if (!settings.allow_html_in_named_anchor) {
            parser.addAttributeFilter("id,name", function(nodes) {
              var i2 = nodes.length, sibling2, prevSibling2, parent2, node;
              while (i2--) {
                node = nodes[i2];
                if (node.name === "a" && node.firstChild && !node.attr("href")) {
                  parent2 = node.parent;
                  sibling2 = node.lastChild;
                  do {
                    prevSibling2 = sibling2.prev;
                    parent2.insert(sibling2, node);
                    sibling2 = prevSibling2;
                  } while (sibling2);
                }
              }
            });
          }
          if (settings.fix_list_elements) {
            parser.addNodeFilter("ul,ol", function(nodes) {
              var i2 = nodes.length, node, parentNode;
              while (i2--) {
                node = nodes[i2];
                parentNode = node.parent;
                if (parentNode.name === "ul" || parentNode.name === "ol") {
                  if (node.prev && node.prev.name === "li") {
                    node.prev.append(node);
                  } else {
                    var li2 = new AstNode("li", 1);
                    li2.attr("style", "list-style-type: none");
                    node.wrap(li2);
                  }
                }
              }
            });
          }
          if (settings.validate && schema.getValidClasses()) {
            parser.addAttributeFilter("class", function(nodes) {
              var validClasses = schema.getValidClasses();
              var i2 = nodes.length;
              while (i2--) {
                var node = nodes[i2];
                var classList = node.attr("class").split(" ");
                var classValue = "";
                for (var ci2 = 0; ci2 < classList.length; ci2++) {
                  var className = classList[ci2];
                  var valid = false;
                  var validClassesMap = validClasses["*"];
                  if (validClassesMap && validClassesMap[className]) {
                    valid = true;
                  }
                  validClassesMap = validClasses[node.name];
                  if (!valid && validClassesMap && validClassesMap[className]) {
                    valid = true;
                  }
                  if (valid) {
                    if (classValue) {
                      classValue += " ";
                    }
                    classValue += className;
                  }
                }
                if (!classValue.length) {
                  classValue = null;
                }
                node.attr("class", classValue);
              }
            });
          }
          registerBase64ImageFilter(parser, settings);
        };
        var makeMap = Tools.makeMap, each$6 = Tools.each, explode$2 = Tools.explode, extend$4 = Tools.extend;
        var DomParser = function(settings, schema) {
          if (schema === void 0) {
            schema = Schema();
          }
          var nodeFilters = {};
          var attributeFilters = [];
          var matchedNodes = {};
          var matchedAttributes = {};
          settings = settings || {};
          settings.validate = "validate" in settings ? settings.validate : true;
          settings.root_name = settings.root_name || "body";
          var fixInvalidChildren = function(nodes) {
            var nonSplitableElements = makeMap("tr,td,th,tbody,thead,tfoot,table");
            var nonEmptyElements = schema.getNonEmptyElements();
            var whitespaceElements = schema.getWhiteSpaceElements();
            var textBlockElements = schema.getTextBlockElements();
            var specialElements = schema.getSpecialElements();
            var removeOrUnwrapInvalidNode = function(node2, originalNodeParent) {
              if (originalNodeParent === void 0) {
                originalNodeParent = node2.parent;
              }
              if (specialElements[node2.name]) {
                node2.empty().remove();
              } else {
                var children2 = node2.children();
                for (var _i2 = 0, children_1 = children2; _i2 < children_1.length; _i2++) {
                  var childNode2 = children_1[_i2];
                  if (!schema.isValidChild(originalNodeParent.name, childNode2.name)) {
                    removeOrUnwrapInvalidNode(childNode2, originalNodeParent);
                  }
                }
                node2.unwrap();
              }
            };
            for (var ni2 = 0; ni2 < nodes.length; ni2++) {
              var node = nodes[ni2];
              var parent_1 = void 0, newParent = void 0, tempNode = void 0;
              if (!node.parent || node.fixed) {
                continue;
              }
              if (textBlockElements[node.name] && node.parent.name === "li") {
                var sibling2 = node.next;
                while (sibling2) {
                  if (textBlockElements[sibling2.name]) {
                    sibling2.name = "li";
                    sibling2.fixed = true;
                    node.parent.insert(sibling2, node.parent);
                  } else {
                    break;
                  }
                  sibling2 = sibling2.next;
                }
                node.unwrap();
                continue;
              }
              var parents2 = [node];
              for (parent_1 = node.parent; parent_1 && !schema.isValidChild(parent_1.name, node.name) && !nonSplitableElements[parent_1.name]; parent_1 = parent_1.parent) {
                parents2.push(parent_1);
              }
              if (parent_1 && parents2.length > 1) {
                if (schema.isValidChild(parent_1.name, node.name)) {
                  parents2.reverse();
                  newParent = filterNode(parents2[0].clone());
                  var currentNode = newParent;
                  for (var i2 = 0; i2 < parents2.length - 1; i2++) {
                    if (schema.isValidChild(currentNode.name, parents2[i2].name)) {
                      tempNode = filterNode(parents2[i2].clone());
                      currentNode.append(tempNode);
                    } else {
                      tempNode = currentNode;
                    }
                    for (var childNode = parents2[i2].firstChild; childNode && childNode !== parents2[i2 + 1]; ) {
                      var nextNode = childNode.next;
                      tempNode.append(childNode);
                      childNode = nextNode;
                    }
                    currentNode = tempNode;
                  }
                  if (!isEmpty(schema, nonEmptyElements, whitespaceElements, newParent)) {
                    parent_1.insert(newParent, parents2[0], true);
                    parent_1.insert(node, newParent);
                  } else {
                    parent_1.insert(node, parents2[0], true);
                  }
                  parent_1 = parents2[0];
                  if (isEmpty(schema, nonEmptyElements, whitespaceElements, parent_1) || hasOnlyChild(parent_1, "br")) {
                    parent_1.empty().remove();
                  }
                } else {
                  removeOrUnwrapInvalidNode(node);
                }
              } else if (node.parent) {
                if (node.name === "li") {
                  var sibling2 = node.prev;
                  if (sibling2 && (sibling2.name === "ul" || sibling2.name === "ol")) {
                    sibling2.append(node);
                    continue;
                  }
                  sibling2 = node.next;
                  if (sibling2 && (sibling2.name === "ul" || sibling2.name === "ol")) {
                    sibling2.insert(node, sibling2.firstChild, true);
                    continue;
                  }
                  node.wrap(filterNode(new AstNode("ul", 1)));
                  continue;
                }
                if (schema.isValidChild(node.parent.name, "div") && schema.isValidChild("div", node.name)) {
                  node.wrap(filterNode(new AstNode("div", 1)));
                } else {
                  removeOrUnwrapInvalidNode(node);
                }
              }
            }
          };
          var filterNode = function(node) {
            var name2 = node.name;
            if (name2 in nodeFilters) {
              var list = matchedNodes[name2];
              if (list) {
                list.push(node);
              } else {
                matchedNodes[name2] = [node];
              }
            }
            var i2 = attributeFilters.length;
            while (i2--) {
              var attrName = attributeFilters[i2].name;
              if (attrName in node.attributes.map) {
                var list = matchedAttributes[attrName];
                if (list) {
                  list.push(node);
                } else {
                  matchedAttributes[attrName] = [node];
                }
              }
            }
            return node;
          };
          var addNodeFilter = function(name2, callback2) {
            each$6(explode$2(name2), function(name3) {
              var list = nodeFilters[name3];
              if (!list) {
                nodeFilters[name3] = list = [];
              }
              list.push(callback2);
            });
          };
          var getNodeFilters = function() {
            var out = [];
            for (var name_1 in nodeFilters) {
              if (has$2(nodeFilters, name_1)) {
                out.push({
                  name: name_1,
                  callbacks: nodeFilters[name_1]
                });
              }
            }
            return out;
          };
          var addAttributeFilter = function(name2, callback2) {
            each$6(explode$2(name2), function(name3) {
              var i2;
              for (i2 = 0; i2 < attributeFilters.length; i2++) {
                if (attributeFilters[i2].name === name3) {
                  attributeFilters[i2].callbacks.push(callback2);
                  return;
                }
              }
              attributeFilters.push({
                name: name3,
                callbacks: [callback2]
              });
            });
          };
          var getAttributeFilters = function() {
            return [].concat(attributeFilters);
          };
          var parse3 = function(html, args) {
            var nodes, i2, l2, fi2, fl, list, name2;
            var invalidChildren = [];
            var node;
            var getRootBlockName = function(name3) {
              if (name3 === false) {
                return "";
              } else if (name3 === true) {
                return "p";
              } else {
                return name3;
              }
            };
            args = args || {};
            matchedNodes = {};
            matchedAttributes = {};
            var blockElements = extend$4(makeMap("script,style,head,html,body,title,meta,param"), schema.getBlockElements());
            var nonEmptyElements = schema.getNonEmptyElements();
            var children2 = schema.children;
            var validate2 = settings.validate;
            var forcedRootBlockName = "forced_root_block" in args ? args.forced_root_block : settings.forced_root_block;
            var rootBlockName = getRootBlockName(forcedRootBlockName);
            var whiteSpaceElements = schema.getWhiteSpaceElements();
            var startWhiteSpaceRegExp = /^[ \t\r\n]+/;
            var endWhiteSpaceRegExp = /[ \t\r\n]+$/;
            var allWhiteSpaceRegExp = /[ \t\r\n]+/g;
            var isAllWhiteSpaceRegExp = /^[ \t\r\n]+$/;
            var isInWhiteSpacePreservedElement = has$2(whiteSpaceElements, args.context) || has$2(whiteSpaceElements, settings.root_name);
            var addRootBlocks2 = function() {
              var node2 = rootNode.firstChild, rootBlockNode = null;
              var trim2 = function(rootBlock) {
                if (rootBlock) {
                  node2 = rootBlock.firstChild;
                  if (node2 && node2.type === 3) {
                    node2.value = node2.value.replace(startWhiteSpaceRegExp, "");
                  }
                  node2 = rootBlock.lastChild;
                  if (node2 && node2.type === 3) {
                    node2.value = node2.value.replace(endWhiteSpaceRegExp, "");
                  }
                }
              };
              if (!schema.isValidChild(rootNode.name, rootBlockName.toLowerCase())) {
                return;
              }
              while (node2) {
                var next = node2.next;
                if (node2.type === 3 || node2.type === 1 && node2.name !== "p" && !blockElements[node2.name] && !node2.attr("data-mce-type")) {
                  if (!rootBlockNode) {
                    rootBlockNode = createNode(rootBlockName, 1);
                    rootBlockNode.attr(settings.forced_root_block_attrs);
                    rootNode.insert(rootBlockNode, node2);
                    rootBlockNode.append(node2);
                  } else {
                    rootBlockNode.append(node2);
                  }
                } else {
                  trim2(rootBlockNode);
                  rootBlockNode = null;
                }
                node2 = next;
              }
              trim2(rootBlockNode);
            };
            var createNode = function(name3, type2) {
              var node2 = new AstNode(name3, type2);
              var list2;
              if (name3 in nodeFilters) {
                list2 = matchedNodes[name3];
                if (list2) {
                  list2.push(node2);
                } else {
                  matchedNodes[name3] = [node2];
                }
              }
              return node2;
            };
            var removeWhitespaceBefore = function(node2) {
              var blockElements2 = schema.getBlockElements();
              for (var textNode = node2.prev; textNode && textNode.type === 3; ) {
                var textVal = textNode.value.replace(endWhiteSpaceRegExp, "");
                if (textVal.length > 0) {
                  textNode.value = textVal;
                  return;
                }
                var textNodeNext = textNode.next;
                if (textNodeNext) {
                  if (textNodeNext.type === 3 && textNodeNext.value.length) {
                    textNode = textNode.prev;
                    continue;
                  }
                  if (!blockElements2[textNodeNext.name] && textNodeNext.name !== "script" && textNodeNext.name !== "style") {
                    textNode = textNode.prev;
                    continue;
                  }
                }
                var sibling2 = textNode.prev;
                textNode.remove();
                textNode = sibling2;
              }
            };
            var cloneAndExcludeBlocks = function(input) {
              var output = {};
              for (var name_2 in input) {
                if (name_2 !== "li" && name_2 !== "p") {
                  output[name_2] = input[name_2];
                }
              }
              return output;
            };
            var parser = SaxParser({
              validate: validate2,
              document: settings.document,
              allow_html_data_urls: settings.allow_html_data_urls,
              allow_svg_data_urls: settings.allow_svg_data_urls,
              allow_script_urls: settings.allow_script_urls,
              allow_conditional_comments: settings.allow_conditional_comments,
              preserve_cdata: settings.preserve_cdata,
              self_closing_elements: cloneAndExcludeBlocks(schema.getSelfClosingElements()),
              cdata: function(text) {
                node.append(createNode("#cdata", 4)).value = text;
              },
              text: function(text, raw) {
                var textNode;
                if (!isInWhiteSpacePreservedElement) {
                  text = text.replace(allWhiteSpaceRegExp, " ");
                  if (isLineBreakNode(node.lastChild, blockElements)) {
                    text = text.replace(startWhiteSpaceRegExp, "");
                  }
                }
                if (text.length !== 0) {
                  textNode = createNode("#text", 3);
                  textNode.raw = !!raw;
                  node.append(textNode).value = text;
                }
              },
              comment: function(text) {
                node.append(createNode("#comment", 8)).value = text;
              },
              pi: function(name3, text) {
                node.append(createNode(name3, 7)).value = text;
                removeWhitespaceBefore(node);
              },
              doctype: function(text) {
                var newNode = node.append(createNode("#doctype", 10));
                newNode.value = text;
                removeWhitespaceBefore(node);
              },
              start: function(name3, attrs, empty2) {
                var elementRule = validate2 ? schema.getElementRule(name3) : {};
                if (elementRule) {
                  var newNode = createNode(elementRule.outputName || name3, 1);
                  newNode.attributes = attrs;
                  newNode.shortEnded = empty2;
                  node.append(newNode);
                  var parent_2 = children2[node.name];
                  if (parent_2 && children2[newNode.name] && !parent_2[newNode.name]) {
                    invalidChildren.push(newNode);
                  }
                  var attrFiltersLen = attributeFilters.length;
                  while (attrFiltersLen--) {
                    var attrName = attributeFilters[attrFiltersLen].name;
                    if (attrName in attrs.map) {
                      list = matchedAttributes[attrName];
                      if (list) {
                        list.push(newNode);
                      } else {
                        matchedAttributes[attrName] = [newNode];
                      }
                    }
                  }
                  if (blockElements[name3]) {
                    removeWhitespaceBefore(newNode);
                  }
                  if (!empty2) {
                    node = newNode;
                  }
                  if (!isInWhiteSpacePreservedElement && whiteSpaceElements[name3]) {
                    isInWhiteSpacePreservedElement = true;
                  }
                }
              },
              end: function(name3) {
                var textNode, text, sibling2, tempNode;
                var elementRule = validate2 ? schema.getElementRule(name3) : {};
                if (elementRule) {
                  if (blockElements[name3]) {
                    if (!isInWhiteSpacePreservedElement) {
                      textNode = node.firstChild;
                      if (textNode && textNode.type === 3) {
                        text = textNode.value.replace(startWhiteSpaceRegExp, "");
                        if (text.length > 0) {
                          textNode.value = text;
                          textNode = textNode.next;
                        } else {
                          sibling2 = textNode.next;
                          textNode.remove();
                          textNode = sibling2;
                          while (textNode && textNode.type === 3) {
                            text = textNode.value;
                            sibling2 = textNode.next;
                            if (text.length === 0 || isAllWhiteSpaceRegExp.test(text)) {
                              textNode.remove();
                              textNode = sibling2;
                            }
                            textNode = sibling2;
                          }
                        }
                      }
                      textNode = node.lastChild;
                      if (textNode && textNode.type === 3) {
                        text = textNode.value.replace(endWhiteSpaceRegExp, "");
                        if (text.length > 0) {
                          textNode.value = text;
                          textNode = textNode.prev;
                        } else {
                          sibling2 = textNode.prev;
                          textNode.remove();
                          textNode = sibling2;
                          while (textNode && textNode.type === 3) {
                            text = textNode.value;
                            sibling2 = textNode.prev;
                            if (text.length === 0 || isAllWhiteSpaceRegExp.test(text)) {
                              textNode.remove();
                              textNode = sibling2;
                            }
                            textNode = sibling2;
                          }
                        }
                      }
                    }
                  }
                  if (isInWhiteSpacePreservedElement && whiteSpaceElements[name3]) {
                    isInWhiteSpacePreservedElement = false;
                  }
                  if (elementRule.removeEmpty && isEmpty(schema, nonEmptyElements, whiteSpaceElements, node)) {
                    tempNode = node.parent;
                    if (blockElements[node.name]) {
                      node.empty().remove();
                    } else {
                      node.unwrap();
                    }
                    node = tempNode;
                    return;
                  }
                  if (elementRule.paddEmpty && (isPaddedWithNbsp(node) || isEmpty(schema, nonEmptyElements, whiteSpaceElements, node))) {
                    paddEmptyNode(settings, args, blockElements, node);
                  }
                  node = node.parent;
                }
              }
            }, schema);
            var rootNode = node = new AstNode(args.context || settings.root_name, 11);
            parser.parse(html, args.format);
            if (validate2 && invalidChildren.length) {
              if (!args.context) {
                fixInvalidChildren(invalidChildren);
              } else {
                args.invalid = true;
              }
            }
            if (rootBlockName && (rootNode.name === "body" || args.isRootContent)) {
              addRootBlocks2();
            }
            if (!args.invalid) {
              for (name2 in matchedNodes) {
                if (!has$2(matchedNodes, name2)) {
                  continue;
                }
                list = nodeFilters[name2];
                nodes = matchedNodes[name2];
                fi2 = nodes.length;
                while (fi2--) {
                  if (!nodes[fi2].parent) {
                    nodes.splice(fi2, 1);
                  }
                }
                for (i2 = 0, l2 = list.length; i2 < l2; i2++) {
                  list[i2](nodes, name2, args);
                }
              }
              for (i2 = 0, l2 = attributeFilters.length; i2 < l2; i2++) {
                list = attributeFilters[i2];
                if (list.name in matchedAttributes) {
                  nodes = matchedAttributes[list.name];
                  fi2 = nodes.length;
                  while (fi2--) {
                    if (!nodes[fi2].parent) {
                      nodes.splice(fi2, 1);
                    }
                  }
                  for (fi2 = 0, fl = list.callbacks.length; fi2 < fl; fi2++) {
                    list.callbacks[fi2](nodes, list.name, args);
                  }
                }
              }
            }
            return rootNode;
          };
          var exports2 = {
            schema,
            addAttributeFilter,
            getAttributeFilters,
            addNodeFilter,
            getNodeFilters,
            filterNode,
            parse: parse3
          };
          register$1(exports2, settings);
          register$2(exports2, settings);
          return exports2;
        };
        var register = function(htmlParser, settings, dom2) {
          htmlParser.addAttributeFilter("data-mce-tabindex", function(nodes, name2) {
            var i2 = nodes.length;
            while (i2--) {
              var node = nodes[i2];
              node.attr("tabindex", node.attr("data-mce-tabindex"));
              node.attr(name2, null);
            }
          });
          htmlParser.addAttributeFilter("src,href,style", function(nodes, name2) {
            var internalName = "data-mce-" + name2;
            var urlConverter = settings.url_converter;
            var urlConverterScope = settings.url_converter_scope;
            var i2 = nodes.length;
            while (i2--) {
              var node = nodes[i2];
              var value2 = node.attr(internalName);
              if (value2 !== void 0) {
                node.attr(name2, value2.length > 0 ? value2 : null);
                node.attr(internalName, null);
              } else {
                value2 = node.attr(name2);
                if (name2 === "style") {
                  value2 = dom2.serializeStyle(dom2.parseStyle(value2), node.name);
                } else if (urlConverter) {
                  value2 = urlConverter.call(urlConverterScope, value2, name2, node.name);
                }
                node.attr(name2, value2.length > 0 ? value2 : null);
              }
            }
          });
          htmlParser.addAttributeFilter("class", function(nodes) {
            var i2 = nodes.length;
            while (i2--) {
              var node = nodes[i2];
              var value2 = node.attr("class");
              if (value2) {
                value2 = node.attr("class").replace(/(?:^|\s)mce-item-\w+(?!\S)/g, "");
                node.attr("class", value2.length > 0 ? value2 : null);
              }
            }
          });
          htmlParser.addAttributeFilter("data-mce-type", function(nodes, name2, args) {
            var i2 = nodes.length;
            while (i2--) {
              var node = nodes[i2];
              if (node.attr("data-mce-type") === "bookmark" && !args.cleanup) {
                var hasChildren = Optional.from(node.firstChild).exists(function(firstChild2) {
                  return !isZwsp(firstChild2.value);
                });
                if (hasChildren) {
                  node.unwrap();
                } else {
                  node.remove();
                }
              }
            }
          });
          htmlParser.addNodeFilter("noscript", function(nodes) {
            var i2 = nodes.length;
            while (i2--) {
              var node = nodes[i2].firstChild;
              if (node) {
                node.value = Entities.decode(node.value);
              }
            }
          });
          htmlParser.addNodeFilter("script,style", function(nodes, name2) {
            var trim2 = function(value3) {
              return value3.replace(/(<!--\[CDATA\[|\]\]-->)/g, "\n").replace(/^[\r\n]*|[\r\n]*$/g, "").replace(/^\s*((<!--)?(\s*\/\/)?\s*<!\[CDATA\[|(<!--\s*)?\/\*\s*<!\[CDATA\[\s*\*\/|(\/\/)?\s*<!--|\/\*\s*<!--\s*\*\/)\s*[\r\n]*/gi, "").replace(/\s*(\/\*\s*\]\]>\s*\*\/(-->)?|\s*\/\/\s*\]\]>(-->)?|\/\/\s*(-->)?|\]\]>|\/\*\s*-->\s*\*\/|\s*-->\s*)\s*$/g, "");
            };
            var i2 = nodes.length;
            while (i2--) {
              var node = nodes[i2];
              var value2 = node.firstChild ? node.firstChild.value : "";
              if (name2 === "script") {
                var type2 = node.attr("type");
                if (type2) {
                  node.attr("type", type2 === "mce-no/type" ? null : type2.replace(/^mce\-/, ""));
                }
                if (settings.element_format === "xhtml" && value2.length > 0) {
                  node.firstChild.value = "// <![CDATA[\n" + trim2(value2) + "\n// ]]>";
                }
              } else {
                if (settings.element_format === "xhtml" && value2.length > 0) {
                  node.firstChild.value = "<!--\n" + trim2(value2) + "\n-->";
                }
              }
            }
          });
          htmlParser.addNodeFilter("#comment", function(nodes) {
            var i2 = nodes.length;
            while (i2--) {
              var node = nodes[i2];
              if (settings.preserve_cdata && node.value.indexOf("[CDATA[") === 0) {
                node.name = "#cdata";
                node.type = 4;
                node.value = dom2.decode(node.value.replace(/^\[CDATA\[|\]\]$/g, ""));
              } else if (node.value.indexOf("mce:protected ") === 0) {
                node.name = "#text";
                node.type = 3;
                node.raw = true;
                node.value = unescape(node.value).substr(14);
              }
            }
          });
          htmlParser.addNodeFilter("xml:namespace,input", function(nodes, name2) {
            var i2 = nodes.length;
            while (i2--) {
              var node = nodes[i2];
              if (node.type === 7) {
                node.remove();
              } else if (node.type === 1) {
                if (name2 === "input" && !node.attr("type")) {
                  node.attr("type", "text");
                }
              }
            }
          });
          htmlParser.addAttributeFilter("data-mce-type", function(nodes) {
            each$k(nodes, function(node) {
              if (node.attr("data-mce-type") === "format-caret") {
                if (node.isEmpty(htmlParser.schema.getNonEmptyElements())) {
                  node.remove();
                } else {
                  node.unwrap();
                }
              }
            });
          });
          htmlParser.addAttributeFilter("data-mce-src,data-mce-href,data-mce-style,data-mce-selected,data-mce-expando,data-mce-type,data-mce-resize,data-mce-placeholder", function(nodes, name2) {
            var i2 = nodes.length;
            while (i2--) {
              nodes[i2].attr(name2, null);
            }
          });
        };
        var trimTrailingBr = function(rootNode) {
          var isBr2 = function(node) {
            return node && node.name === "br";
          };
          var brNode1 = rootNode.lastChild;
          if (isBr2(brNode1)) {
            var brNode2 = brNode1.prev;
            if (isBr2(brNode2)) {
              brNode1.remove();
              brNode2.remove();
            }
          }
        };
        var preProcess = function(editor, node, args) {
          var oldDoc;
          var dom2 = editor.dom;
          var clonedNode = node.cloneNode(true);
          var impl = document.implementation;
          if (impl.createHTMLDocument) {
            var doc_1 = impl.createHTMLDocument("");
            Tools.each(clonedNode.nodeName === "BODY" ? clonedNode.childNodes : [clonedNode], function(node2) {
              doc_1.body.appendChild(doc_1.importNode(node2, true));
            });
            if (clonedNode.nodeName !== "BODY") {
              clonedNode = doc_1.body.firstChild;
            } else {
              clonedNode = doc_1.body;
            }
            oldDoc = dom2.doc;
            dom2.doc = doc_1;
          }
          firePreProcess(editor, __assign(__assign({}, args), { node: clonedNode }));
          if (oldDoc) {
            dom2.doc = oldDoc;
          }
          return clonedNode;
        };
        var shouldFireEvent = function(editor, args) {
          return editor && editor.hasEventListeners("PreProcess") && !args.no_events;
        };
        var process2 = function(editor, node, args) {
          return shouldFireEvent(editor, args) ? preProcess(editor, node, args) : node;
        };
        var addTempAttr = function(htmlParser, tempAttrs, name2) {
          if (Tools.inArray(tempAttrs, name2) === -1) {
            htmlParser.addAttributeFilter(name2, function(nodes, name3) {
              var i2 = nodes.length;
              while (i2--) {
                nodes[i2].attr(name3, null);
              }
            });
            tempAttrs.push(name2);
          }
        };
        var postProcess = function(editor, args, content) {
          if (!args.no_events && editor) {
            var outArgs = firePostProcess(editor, __assign(__assign({}, args), { content }));
            return outArgs.content;
          } else {
            return content;
          }
        };
        var getHtmlFromNode = function(dom2, node, args) {
          var html = trim$2(args.getInner ? node.innerHTML : dom2.getOuterHTML(node));
          return args.selection || isWsPreserveElement(SugarElement.fromDom(node)) ? html : Tools.trim(html);
        };
        var parseHtml = function(htmlParser, html, args) {
          var parserArgs = args.selection ? __assign({ forced_root_block: false }, args) : args;
          var rootNode = htmlParser.parse(html, parserArgs);
          trimTrailingBr(rootNode);
          return rootNode;
        };
        var serializeNode = function(settings, schema, node) {
          var htmlSerializer = HtmlSerializer(settings, schema);
          return htmlSerializer.serialize(node);
        };
        var toHtml = function(editor, settings, schema, rootNode, args) {
          var content = serializeNode(settings, schema, rootNode);
          return postProcess(editor, args, content);
        };
        var DomSerializerImpl = function(settings, editor) {
          var tempAttrs = ["data-mce-selected"];
          var dom2 = editor && editor.dom ? editor.dom : DOMUtils.DOM;
          var schema = editor && editor.schema ? editor.schema : Schema(settings);
          settings.entity_encoding = settings.entity_encoding || "named";
          settings.remove_trailing_brs = "remove_trailing_brs" in settings ? settings.remove_trailing_brs : true;
          var htmlParser = DomParser(settings, schema);
          register(htmlParser, settings, dom2);
          var serialize2 = function(node, parserArgs) {
            if (parserArgs === void 0) {
              parserArgs = {};
            }
            var args = __assign({ format: "html" }, parserArgs);
            var targetNode = process2(editor, node, args);
            var html = getHtmlFromNode(dom2, targetNode, args);
            var rootNode = parseHtml(htmlParser, html, args);
            return args.format === "tree" ? rootNode : toHtml(editor, settings, schema, rootNode, args);
          };
          return {
            schema,
            addNodeFilter: htmlParser.addNodeFilter,
            addAttributeFilter: htmlParser.addAttributeFilter,
            serialize: serialize2,
            addRules: schema.addValidElements,
            setRules: schema.setValidElements,
            addTempAttr: curry(addTempAttr, htmlParser, tempAttrs),
            getTempAttrs: constant(tempAttrs),
            getNodeFilters: htmlParser.getNodeFilters,
            getAttributeFilters: htmlParser.getAttributeFilters
          };
        };
        var DomSerializer = function(settings, editor) {
          var domSerializer = DomSerializerImpl(settings, editor);
          return {
            schema: domSerializer.schema,
            addNodeFilter: domSerializer.addNodeFilter,
            addAttributeFilter: domSerializer.addAttributeFilter,
            serialize: domSerializer.serialize,
            addRules: domSerializer.addRules,
            setRules: domSerializer.setRules,
            addTempAttr: domSerializer.addTempAttr,
            getTempAttrs: domSerializer.getTempAttrs,
            getNodeFilters: domSerializer.getNodeFilters,
            getAttributeFilters: domSerializer.getAttributeFilters
          };
        };
        var defaultFormat = "html";
        var getContent = function(editor, args) {
          if (args === void 0) {
            args = {};
          }
          var format3 = args.format ? args.format : defaultFormat;
          return getContent$2(editor, args, format3);
        };
        var setContent = function(editor, content, args) {
          if (args === void 0) {
            args = {};
          }
          return setContent$2(editor, content, args);
        };
        var DOM$7 = DOMUtils.DOM;
        var restoreOriginalStyles = function(editor) {
          DOM$7.setStyle(editor.id, "display", editor.orgDisplay);
        };
        var safeDestroy = function(x2) {
          return Optional.from(x2).each(function(x3) {
            return x3.destroy();
          });
        };
        var clearDomReferences = function(editor) {
          editor.contentAreaContainer = editor.formElement = editor.container = editor.editorContainer = null;
          editor.bodyElement = editor.contentDocument = editor.contentWindow = null;
          editor.iframeElement = editor.targetElm = null;
          if (editor.selection) {
            editor.selection = editor.selection.win = editor.selection.dom = editor.selection.dom.doc = null;
          }
        };
        var restoreForm = function(editor) {
          var form = editor.formElement;
          if (form) {
            if (form._mceOldSubmit) {
              form.submit = form._mceOldSubmit;
              form._mceOldSubmit = null;
            }
            DOM$7.unbind(form, "submit reset", editor.formEventDelegate);
          }
        };
        var remove = function(editor) {
          if (!editor.removed) {
            var _selectionOverrides = editor._selectionOverrides, editorUpload = editor.editorUpload;
            var body = editor.getBody();
            var element = editor.getElement();
            if (body) {
              editor.save({ is_removing: true });
            }
            editor.removed = true;
            editor.unbindAllNativeEvents();
            if (editor.hasHiddenInput && element) {
              DOM$7.remove(element.nextSibling);
            }
            fireRemove(editor);
            editor.editorManager.remove(editor);
            if (!editor.inline && body) {
              restoreOriginalStyles(editor);
            }
            fireDetach(editor);
            DOM$7.remove(editor.getContainer());
            safeDestroy(_selectionOverrides);
            safeDestroy(editorUpload);
            editor.destroy();
          }
        };
        var destroy = function(editor, automatic) {
          var selection = editor.selection, dom2 = editor.dom;
          if (editor.destroyed) {
            return;
          }
          if (!automatic && !editor.removed) {
            editor.remove();
            return;
          }
          if (!automatic) {
            editor.editorManager.off("beforeunload", editor._beforeUnload);
            if (editor.theme && editor.theme.destroy) {
              editor.theme.destroy();
            }
            safeDestroy(selection);
            safeDestroy(dom2);
          }
          restoreForm(editor);
          clearDomReferences(editor);
          editor.destroyed = true;
        };
        var deep = function(old, nu2) {
          var bothObjects = isObject2(old) && isObject2(nu2);
          return bothObjects ? deepMerge(old, nu2) : nu2;
        };
        var baseMerge = function(merger) {
          return function() {
            var objects = [];
            for (var _i2 = 0; _i2 < arguments.length; _i2++) {
              objects[_i2] = arguments[_i2];
            }
            if (objects.length === 0) {
              throw new Error("Can't merge zero objects");
            }
            var ret = {};
            for (var j2 = 0; j2 < objects.length; j2++) {
              var curObject = objects[j2];
              for (var key in curObject) {
                if (has$2(curObject, key)) {
                  ret[key] = merger(ret[key], curObject[key]);
                }
              }
            }
            return ret;
          };
        };
        var deepMerge = baseMerge(deep);
        var deprecatedSettings = "autoresize_on_init,content_editable_state,convert_fonts_to_spans,inline_styles,padd_empty_with_br,block_elements,boolean_attributes,editor_deselector,editor_selector,elements,file_browser_callback_types,filepicker_validator_handler,force_hex_style_colors,force_p_newlines,gecko_spellcheck,images_dataimg_filter,media_scripts,mode,move_caret_before_on_enter_elements,non_empty_elements,self_closing_elements,short_ended_elements,special,spellchecker_select_languages,spellchecker_whitelist,tab_focus,table_responsive_width,text_block_elements,text_inline_elements,toolbar_drawer,types,validate,whitespace_elements,paste_word_valid_elements,paste_retain_style_properties,paste_convert_word_fake_lists".split(",");
        var deprecatedPlugins = "bbcode,colorpicker,contextmenu,fullpage,legacyoutput,spellchecker,textcolor".split(",");
        var movedToPremiumPlugins = "imagetools,toc".split(",");
        var getDeprecatedSettings = function(settings) {
          var settingNames = filter$4(deprecatedSettings, function(setting) {
            return has$2(settings, setting);
          });
          var forcedRootBlock = settings.forced_root_block;
          if (forcedRootBlock === false || forcedRootBlock === "") {
            settingNames.push("forced_root_block (false only)");
          }
          return sort(settingNames);
        };
        var getDeprecatedPlugins = function(settings) {
          var plugins2 = Tools.makeMap(settings.plugins, " ");
          var hasPlugin = function(plugin) {
            return has$2(plugins2, plugin);
          };
          var pluginNames = __spreadArray(__spreadArray([], filter$4(deprecatedPlugins, hasPlugin), true), bind(movedToPremiumPlugins, function(plugin) {
            return hasPlugin(plugin) ? [plugin + " (moving to premium)"] : [];
          }), true);
          return sort(pluginNames);
        };
        var logDeprecationsWarning = function(rawSettings, finalSettings) {
          var deprecatedSettings2 = getDeprecatedSettings(rawSettings);
          var deprecatedPlugins2 = getDeprecatedPlugins(finalSettings);
          var hasDeprecatedPlugins = deprecatedPlugins2.length > 0;
          var hasDeprecatedSettings = deprecatedSettings2.length > 0;
          var isLegacyMobileTheme = finalSettings.theme === "mobile";
          if (hasDeprecatedPlugins || hasDeprecatedSettings || isLegacyMobileTheme) {
            var listJoiner = "\n- ";
            var themesMessage = isLegacyMobileTheme ? "\n\nThemes:" + listJoiner + "mobile" : "";
            var pluginsMessage = hasDeprecatedPlugins ? "\n\nPlugins:" + listJoiner + deprecatedPlugins2.join(listJoiner) : "";
            var settingsMessage = hasDeprecatedSettings ? "\n\nSettings:" + listJoiner + deprecatedSettings2.join(listJoiner) : "";
            console.warn("The following deprecated features are currently enabled, these will be removed in TinyMCE 6.0. See https://www.tiny.cloud/docs/release-notes/6.0-upcoming-changes/ for more information." + themesMessage + pluginsMessage + settingsMessage);
          }
        };
        var sectionResult = function(sections, settings) {
          return {
            sections: constant(sections),
            settings: constant(settings)
          };
        };
        var deviceDetection = detect().deviceType;
        var isTouch = deviceDetection.isTouch();
        var isPhone = deviceDetection.isPhone();
        var isTablet = deviceDetection.isTablet();
        var legacyMobilePlugins = [
          "lists",
          "autolink",
          "autosave"
        ];
        var defaultTouchSettings = {
          table_grid: false,
          object_resizing: false,
          resize: false
        };
        var normalizePlugins = function(plugins2) {
          var pluginNames = isArray$1(plugins2) ? plugins2.join(" ") : plugins2;
          var trimmedPlugins = map$3(isString$1(pluginNames) ? pluginNames.split(" ") : [], trim$4);
          return filter$4(trimmedPlugins, function(item) {
            return item.length > 0;
          });
        };
        var filterLegacyMobilePlugins = function(plugins2) {
          return filter$4(plugins2, curry(contains$3, legacyMobilePlugins));
        };
        var extractSections = function(keys2, settings) {
          var result = bifilter(settings, function(value2, key) {
            return contains$3(keys2, key);
          });
          return sectionResult(result.t, result.f);
        };
        var getSection = function(sectionResult2, name2, defaults2) {
          if (defaults2 === void 0) {
            defaults2 = {};
          }
          var sections = sectionResult2.sections();
          var sectionSettings = get$9(sections, name2).getOr({});
          return Tools.extend({}, defaults2, sectionSettings);
        };
        var hasSection = function(sectionResult2, name2) {
          return has$2(sectionResult2.sections(), name2);
        };
        var isSectionTheme = function(sectionResult2, name2, theme) {
          var section = sectionResult2.sections();
          return hasSection(sectionResult2, name2) && section[name2].theme === theme;
        };
        var getSectionConfig = function(sectionResult2, name2) {
          return hasSection(sectionResult2, name2) ? sectionResult2.sections()[name2] : {};
        };
        var getToolbarMode = function(settings, defaultVal) {
          return get$9(settings, "toolbar_mode").orThunk(function() {
            return get$9(settings, "toolbar_drawer").map(function(val) {
              return val === false ? "wrap" : val;
            });
          }).getOr(defaultVal);
        };
        var getDefaultSettings = function(settings, id2, documentBaseUrl, isTouch2, editor) {
          var baseDefaults = {
            id: id2,
            theme: "silver",
            toolbar_mode: getToolbarMode(settings, "floating"),
            plugins: "",
            document_base_url: documentBaseUrl,
            add_form_submit_trigger: true,
            submit_patch: true,
            add_unload_trigger: true,
            convert_urls: true,
            relative_urls: true,
            remove_script_host: true,
            object_resizing: true,
            doctype: "<!DOCTYPE html>",
            visual: true,
            font_size_legacy_values: "xx-small,small,medium,large,x-large,xx-large,300%",
            forced_root_block: "p",
            hidden_input: true,
            inline_styles: true,
            convert_fonts_to_spans: true,
            indent: true,
            indent_before: "p,h1,h2,h3,h4,h5,h6,blockquote,div,title,style,pre,script,td,th,ul,ol,li,dl,dt,dd,area,table,thead,tfoot,tbody,tr,section,summary,article,hgroup,aside,figure,figcaption,option,optgroup,datalist",
            indent_after: "p,h1,h2,h3,h4,h5,h6,blockquote,div,title,style,pre,script,td,th,ul,ol,li,dl,dt,dd,area,table,thead,tfoot,tbody,tr,section,summary,article,hgroup,aside,figure,figcaption,option,optgroup,datalist",
            entity_encoding: "named",
            url_converter: editor.convertURL,
            url_converter_scope: editor
          };
          return __assign(__assign({}, baseDefaults), isTouch2 ? defaultTouchSettings : {});
        };
        var getDefaultMobileSettings = function(mobileSettings, isPhone2) {
          var defaultMobileSettings = {
            resize: false,
            toolbar_mode: getToolbarMode(mobileSettings, "scrolling"),
            toolbar_sticky: false
          };
          var defaultPhoneSettings = { menubar: false };
          return __assign(__assign(__assign({}, defaultTouchSettings), defaultMobileSettings), isPhone2 ? defaultPhoneSettings : {});
        };
        var getExternalPlugins = function(overrideSettings, settings) {
          var userDefinedExternalPlugins = settings.external_plugins ? settings.external_plugins : {};
          if (overrideSettings && overrideSettings.external_plugins) {
            return Tools.extend({}, overrideSettings.external_plugins, userDefinedExternalPlugins);
          } else {
            return userDefinedExternalPlugins;
          }
        };
        var combinePlugins = function(forcedPlugins, plugins2) {
          return [].concat(normalizePlugins(forcedPlugins)).concat(normalizePlugins(plugins2));
        };
        var getPlatformPlugins = function(isMobileDevice, sectionResult2, desktopPlugins, mobilePlugins) {
          if (isMobileDevice && isSectionTheme(sectionResult2, "mobile", "mobile")) {
            return filterLegacyMobilePlugins(mobilePlugins);
          } else if (isMobileDevice && hasSection(sectionResult2, "mobile")) {
            return mobilePlugins;
          } else {
            return desktopPlugins;
          }
        };
        var processPlugins = function(isMobileDevice, sectionResult2, defaultOverrideSettings, settings) {
          var forcedPlugins = normalizePlugins(defaultOverrideSettings.forced_plugins);
          var desktopPlugins = normalizePlugins(settings.plugins);
          var mobileConfig = getSectionConfig(sectionResult2, "mobile");
          var mobilePlugins = mobileConfig.plugins ? normalizePlugins(mobileConfig.plugins) : desktopPlugins;
          var platformPlugins = getPlatformPlugins(isMobileDevice, sectionResult2, desktopPlugins, mobilePlugins);
          var combinedPlugins = combinePlugins(forcedPlugins, platformPlugins);
          if (Env.browser.isIE() && contains$3(combinedPlugins, "rtc")) {
            throw new Error("RTC plugin is not supported on IE 11.");
          }
          return Tools.extend(settings, { plugins: combinedPlugins.join(" ") });
        };
        var isOnMobile = function(isMobileDevice, sectionResult2) {
          return isMobileDevice && hasSection(sectionResult2, "mobile");
        };
        var combineSettings = function(isMobileDevice, isPhone2, defaultSettings, defaultOverrideSettings, settings) {
          var defaultDeviceSettings = isMobileDevice ? { mobile: getDefaultMobileSettings(settings.mobile || {}, isPhone2) } : {};
          var sectionResult2 = extractSections(["mobile"], deepMerge(defaultDeviceSettings, settings));
          var extendedSettings = Tools.extend(defaultSettings, defaultOverrideSettings, sectionResult2.settings(), isOnMobile(isMobileDevice, sectionResult2) ? getSection(sectionResult2, "mobile") : {}, {
            validate: true,
            external_plugins: getExternalPlugins(defaultOverrideSettings, sectionResult2.settings())
          });
          return processPlugins(isMobileDevice, sectionResult2, defaultOverrideSettings, extendedSettings);
        };
        var getEditorSettings = function(editor, id2, documentBaseUrl, defaultOverrideSettings, settings) {
          var defaultSettings = getDefaultSettings(settings, id2, documentBaseUrl, isTouch, editor);
          var finalSettings = combineSettings(isPhone || isTablet, isPhone, defaultSettings, defaultOverrideSettings, settings);
          if (finalSettings.deprecation_warnings !== false) {
            logDeprecationsWarning(settings, finalSettings);
          }
          return finalSettings;
        };
        var getFiltered = function(predicate, editor, name2) {
          return Optional.from(editor.settings[name2]).filter(predicate);
        };
        var getParamObject = function(value2) {
          var output = {};
          if (typeof value2 === "string") {
            each$k(value2.indexOf("=") > 0 ? value2.split(/[;,](?![^=;,]*(?:[;,]|$))/) : value2.split(","), function(val) {
              var arr2 = val.split("=");
              if (arr2.length > 1) {
                output[Tools.trim(arr2[0])] = Tools.trim(arr2[1]);
              } else {
                output[Tools.trim(arr2[0])] = Tools.trim(arr2[0]);
              }
            });
          } else {
            output = value2;
          }
          return output;
        };
        var isArrayOf = function(p2) {
          return function(a2) {
            return isArray$1(a2) && forall(a2, p2);
          };
        };
        var getParam = function(editor, name2, defaultVal, type2) {
          var value2 = name2 in editor.settings ? editor.settings[name2] : defaultVal;
          if (type2 === "hash") {
            return getParamObject(value2);
          } else if (type2 === "string") {
            return getFiltered(isString$1, editor, name2).getOr(defaultVal);
          } else if (type2 === "number") {
            return getFiltered(isNumber2, editor, name2).getOr(defaultVal);
          } else if (type2 === "boolean") {
            return getFiltered(isBoolean, editor, name2).getOr(defaultVal);
          } else if (type2 === "object") {
            return getFiltered(isObject2, editor, name2).getOr(defaultVal);
          } else if (type2 === "array") {
            return getFiltered(isArray$1, editor, name2).getOr(defaultVal);
          } else if (type2 === "string[]") {
            return getFiltered(isArrayOf(isString$1), editor, name2).getOr(defaultVal);
          } else if (type2 === "function") {
            return getFiltered(isFunction2, editor, name2).getOr(defaultVal);
          } else {
            return value2;
          }
        };
        var CreateIconManager = function() {
          var lookup = {};
          var add4 = function(id2, iconPack) {
            lookup[id2] = iconPack;
          };
          var get2 = function(id2) {
            if (lookup[id2]) {
              return lookup[id2];
            }
            return { icons: {} };
          };
          var has2 = function(id2) {
            return has$2(lookup, id2);
          };
          return {
            add: add4,
            get: get2,
            has: has2
          };
        };
        var IconManager = CreateIconManager();
        var getProp = function(propName, elm) {
          var rawElm = elm.dom;
          return rawElm[propName];
        };
        var getComputedSizeProp = function(propName, elm) {
          return parseInt(get$5(elm, propName), 10);
        };
        var getClientWidth = curry(getProp, "clientWidth");
        var getClientHeight = curry(getProp, "clientHeight");
        var getMarginTop = curry(getComputedSizeProp, "margin-top");
        var getMarginLeft = curry(getComputedSizeProp, "margin-left");
        var getBoundingClientRect2 = function(elm) {
          return elm.dom.getBoundingClientRect();
        };
        var isInsideElementContentArea = function(bodyElm, clientX, clientY) {
          var clientWidth = getClientWidth(bodyElm);
          var clientHeight = getClientHeight(bodyElm);
          return clientX >= 0 && clientY >= 0 && clientX <= clientWidth && clientY <= clientHeight;
        };
        var transpose = function(inline, elm, clientX, clientY) {
          var clientRect = getBoundingClientRect2(elm);
          var deltaX = inline ? clientRect.left + elm.dom.clientLeft + getMarginLeft(elm) : 0;
          var deltaY = inline ? clientRect.top + elm.dom.clientTop + getMarginTop(elm) : 0;
          var x2 = clientX - deltaX;
          var y2 = clientY - deltaY;
          return {
            x: x2,
            y: y2
          };
        };
        var isXYInContentArea = function(editor, clientX, clientY) {
          var bodyElm = SugarElement.fromDom(editor.getBody());
          var targetElm = editor.inline ? bodyElm : documentElement(bodyElm);
          var transposedPoint = transpose(editor.inline, targetElm, clientX, clientY);
          return isInsideElementContentArea(targetElm, transposedPoint.x, transposedPoint.y);
        };
        var fromDomSafe = function(node) {
          return Optional.from(node).map(SugarElement.fromDom);
        };
        var isEditorAttachedToDom = function(editor) {
          var rawContainer = editor.inline ? editor.getBody() : editor.getContentAreaContainer();
          return fromDomSafe(rawContainer).map(inBody).getOr(false);
        };
        var NotificationManagerImpl = function() {
          var unimplemented = function() {
            throw new Error("Theme did not provide a NotificationManager implementation.");
          };
          return {
            open: unimplemented,
            close: unimplemented,
            reposition: unimplemented,
            getArgs: unimplemented
          };
        };
        var NotificationManager = function(editor) {
          var notifications = [];
          var getImplementation = function() {
            var theme = editor.theme;
            return theme && theme.getNotificationManagerImpl ? theme.getNotificationManagerImpl() : NotificationManagerImpl();
          };
          var getTopNotification = function() {
            return Optional.from(notifications[0]);
          };
          var isEqual2 = function(a2, b2) {
            return a2.type === b2.type && a2.text === b2.text && !a2.progressBar && !a2.timeout && !b2.progressBar && !b2.timeout;
          };
          var reposition2 = function() {
            if (notifications.length > 0) {
              getImplementation().reposition(notifications);
            }
          };
          var addNotification = function(notification) {
            notifications.push(notification);
          };
          var closeNotification = function(notification) {
            findIndex$2(notifications, function(otherNotification) {
              return otherNotification === notification;
            }).each(function(index) {
              notifications.splice(index, 1);
            });
          };
          var open = function(spec, fireEvent2) {
            if (fireEvent2 === void 0) {
              fireEvent2 = true;
            }
            if (editor.removed || !isEditorAttachedToDom(editor)) {
              return;
            }
            if (fireEvent2) {
              editor.fire("BeforeOpenNotification", { notification: spec });
            }
            return find$3(notifications, function(notification) {
              return isEqual2(getImplementation().getArgs(notification), spec);
            }).getOrThunk(function() {
              editor.editorManager.setActive(editor);
              var notification = getImplementation().open(spec, function() {
                closeNotification(notification);
                reposition2();
                getTopNotification().fold(function() {
                  return editor.focus();
                }, function(top2) {
                  return focus$1(SugarElement.fromDom(top2.getEl()));
                });
              });
              addNotification(notification);
              reposition2();
              editor.fire("OpenNotification", { notification: __assign({}, notification) });
              return notification;
            });
          };
          var close = function() {
            getTopNotification().each(function(notification) {
              getImplementation().close(notification);
              closeNotification(notification);
              reposition2();
            });
          };
          var getNotifications = constant(notifications);
          var registerEvents2 = function(editor2) {
            editor2.on("SkinLoaded", function() {
              var serviceMessage = getServiceMessage(editor2);
              if (serviceMessage) {
                open({
                  text: serviceMessage,
                  type: "warning",
                  timeout: 0
                }, false);
              }
              reposition2();
            });
            editor2.on("show ResizeEditor ResizeWindow NodeChange", function() {
              Delay.requestAnimationFrame(reposition2);
            });
            editor2.on("remove", function() {
              each$k(notifications.slice(), function(notification) {
                getImplementation().close(notification);
              });
            });
          };
          registerEvents2(editor);
          return {
            open,
            close,
            getNotifications
          };
        };
        var PluginManager = AddOnManager.PluginManager;
        var ThemeManager = AddOnManager.ThemeManager;
        function WindowManagerImpl() {
          var unimplemented = function() {
            throw new Error("Theme did not provide a WindowManager implementation.");
          };
          return {
            open: unimplemented,
            openUrl: unimplemented,
            alert: unimplemented,
            confirm: unimplemented,
            close: unimplemented,
            getParams: unimplemented,
            setParams: unimplemented
          };
        }
        var WindowManager = function(editor) {
          var dialogs = [];
          var getImplementation = function() {
            var theme = editor.theme;
            return theme && theme.getWindowManagerImpl ? theme.getWindowManagerImpl() : WindowManagerImpl();
          };
          var funcBind = function(scope, f2) {
            return function() {
              var args = [];
              for (var _i2 = 0; _i2 < arguments.length; _i2++) {
                args[_i2] = arguments[_i2];
              }
              return f2 ? f2.apply(scope, args) : void 0;
            };
          };
          var fireOpenEvent = function(dialog) {
            editor.fire("OpenWindow", { dialog });
          };
          var fireCloseEvent = function(dialog) {
            editor.fire("CloseWindow", { dialog });
          };
          var addDialog = function(dialog) {
            dialogs.push(dialog);
            fireOpenEvent(dialog);
          };
          var closeDialog = function(dialog) {
            fireCloseEvent(dialog);
            dialogs = filter$4(dialogs, function(otherDialog) {
              return otherDialog !== dialog;
            });
            if (dialogs.length === 0) {
              editor.focus();
            }
          };
          var getTopDialog = function() {
            return Optional.from(dialogs[dialogs.length - 1]);
          };
          var storeSelectionAndOpenDialog = function(openDialog) {
            editor.editorManager.setActive(editor);
            store(editor);
            var dialog = openDialog();
            addDialog(dialog);
            return dialog;
          };
          var open = function(args, params) {
            return storeSelectionAndOpenDialog(function() {
              return getImplementation().open(args, params, closeDialog);
            });
          };
          var openUrl = function(args) {
            return storeSelectionAndOpenDialog(function() {
              return getImplementation().openUrl(args, closeDialog);
            });
          };
          var alert2 = function(message, callback2, scope) {
            var windowManagerImpl = getImplementation();
            windowManagerImpl.alert(message, funcBind(scope ? scope : windowManagerImpl, callback2));
          };
          var confirm2 = function(message, callback2, scope) {
            var windowManagerImpl = getImplementation();
            windowManagerImpl.confirm(message, funcBind(scope ? scope : windowManagerImpl, callback2));
          };
          var close = function() {
            getTopDialog().each(function(dialog) {
              getImplementation().close(dialog);
              closeDialog(dialog);
            });
          };
          editor.on("remove", function() {
            each$k(dialogs, function(dialog) {
              getImplementation().close(dialog);
            });
          });
          return {
            open,
            openUrl,
            alert: alert2,
            confirm: confirm2,
            close
          };
        };
        var displayNotification = function(editor, message) {
          editor.notificationManager.open({
            type: "error",
            text: message
          });
        };
        var displayError = function(editor, message) {
          if (editor._skinLoaded) {
            displayNotification(editor, message);
          } else {
            editor.on("SkinLoaded", function() {
              displayNotification(editor, message);
            });
          }
        };
        var uploadError = function(editor, message) {
          displayError(editor, I18n.translate([
            "Failed to upload image: {0}",
            message
          ]));
        };
        var logError = function(editor, errorType, msg) {
          fireError(editor, errorType, { message: msg });
          console.error(msg);
        };
        var createLoadError = function(type2, url, name2) {
          return name2 ? "Failed to load " + type2 + ": " + name2 + " from url " + url : "Failed to load " + type2 + " url: " + url;
        };
        var pluginLoadError = function(editor, url, name2) {
          logError(editor, "PluginLoadError", createLoadError("plugin", url, name2));
        };
        var iconsLoadError = function(editor, url, name2) {
          logError(editor, "IconsLoadError", createLoadError("icons", url, name2));
        };
        var languageLoadError = function(editor, url, name2) {
          logError(editor, "LanguageLoadError", createLoadError("language", url, name2));
        };
        var pluginInitError = function(editor, name2, err) {
          var message = I18n.translate([
            "Failed to initialize plugin: {0}",
            name2
          ]);
          fireError(editor, "PluginLoadError", { message });
          initError(message, err);
          displayError(editor, message);
        };
        var initError = function(message) {
          var x2 = [];
          for (var _i2 = 1; _i2 < arguments.length; _i2++) {
            x2[_i2 - 1] = arguments[_i2];
          }
          var console2 = window.console;
          if (console2) {
            if (console2.error) {
              console2.error.apply(console2, __spreadArray([message], x2, false));
            } else {
              console2.log.apply(console2, __spreadArray([message], x2, false));
            }
          }
        };
        var isContentCssSkinName = function(url) {
          return /^[a-z0-9\-]+$/i.test(url);
        };
        var getContentCssUrls = function(editor) {
          return transformToUrls(editor, getContentCss(editor));
        };
        var getFontCssUrls = function(editor) {
          return transformToUrls(editor, getFontCss(editor));
        };
        var transformToUrls = function(editor, cssLinks) {
          var skinUrl = editor.editorManager.baseURL + "/skins/content";
          var suffix = editor.editorManager.suffix;
          var contentCssFile = "content" + suffix + ".css";
          var inline = editor.inline === true;
          return map$3(cssLinks, function(url) {
            if (isContentCssSkinName(url) && !inline) {
              return skinUrl + "/" + url + "/" + contentCssFile;
            } else {
              return editor.documentBaseURI.toAbsolute(url);
            }
          });
        };
        var appendContentCssFromSettings = function(editor) {
          editor.contentCSS = editor.contentCSS.concat(getContentCssUrls(editor), getFontCssUrls(editor));
        };
        var UploadStatus = function() {
          var PENDING = 1, UPLOADED = 2;
          var blobUriStatuses = {};
          var createStatus = function(status, resultUri) {
            return {
              status,
              resultUri
            };
          };
          var hasBlobUri = function(blobUri) {
            return blobUri in blobUriStatuses;
          };
          var getResultUri = function(blobUri) {
            var result = blobUriStatuses[blobUri];
            return result ? result.resultUri : null;
          };
          var isPending = function(blobUri) {
            return hasBlobUri(blobUri) ? blobUriStatuses[blobUri].status === PENDING : false;
          };
          var isUploaded = function(blobUri) {
            return hasBlobUri(blobUri) ? blobUriStatuses[blobUri].status === UPLOADED : false;
          };
          var markPending = function(blobUri) {
            blobUriStatuses[blobUri] = createStatus(PENDING, null);
          };
          var markUploaded = function(blobUri, resultUri) {
            blobUriStatuses[blobUri] = createStatus(UPLOADED, resultUri);
          };
          var removeFailed = function(blobUri) {
            delete blobUriStatuses[blobUri];
          };
          var destroy2 = function() {
            blobUriStatuses = {};
          };
          return {
            hasBlobUri,
            getResultUri,
            isPending,
            isUploaded,
            markPending,
            markUploaded,
            removeFailed,
            destroy: destroy2
          };
        };
        var count = 0;
        var seed = function() {
          var rnd = function() {
            return Math.round(Math.random() * 4294967295).toString(36);
          };
          var now2 = new Date().getTime();
          return "s" + now2.toString(36) + rnd() + rnd() + rnd();
        };
        var uuid2 = function(prefix) {
          return prefix + count++ + seed();
        };
        var BlobCache = function() {
          var cache2 = [];
          var mimeToExt = function(mime) {
            var mimes = {
              "image/jpeg": "jpg",
              "image/jpg": "jpg",
              "image/gif": "gif",
              "image/png": "png",
              "image/apng": "apng",
              "image/avif": "avif",
              "image/svg+xml": "svg",
              "image/webp": "webp",
              "image/bmp": "bmp",
              "image/tiff": "tiff"
            };
            return mimes[mime.toLowerCase()] || "dat";
          };
          var create2 = function(o2, blob, base64, name2, filename) {
            if (isString$1(o2)) {
              var id2 = o2;
              return toBlobInfo({
                id: id2,
                name: name2,
                filename,
                blob,
                base64
              });
            } else if (isObject2(o2)) {
              return toBlobInfo(o2);
            } else {
              throw new Error("Unknown input type");
            }
          };
          var toBlobInfo = function(o2) {
            if (!o2.blob || !o2.base64) {
              throw new Error("blob and base64 representations of the image are required for BlobInfo to be created");
            }
            var id2 = o2.id || uuid2("blobid");
            var name2 = o2.name || id2;
            var blob = o2.blob;
            return {
              id: constant(id2),
              name: constant(name2),
              filename: constant(o2.filename || name2 + "." + mimeToExt(blob.type)),
              blob: constant(blob),
              base64: constant(o2.base64),
              blobUri: constant(o2.blobUri || URL.createObjectURL(blob)),
              uri: constant(o2.uri)
            };
          };
          var add4 = function(blobInfo) {
            if (!get2(blobInfo.id())) {
              cache2.push(blobInfo);
            }
          };
          var findFirst = function(predicate) {
            return find$3(cache2, predicate).getOrUndefined();
          };
          var get2 = function(id2) {
            return findFirst(function(cachedBlobInfo) {
              return cachedBlobInfo.id() === id2;
            });
          };
          var getByUri = function(blobUri) {
            return findFirst(function(blobInfo) {
              return blobInfo.blobUri() === blobUri;
            });
          };
          var getByData = function(base64, type2) {
            return findFirst(function(blobInfo) {
              return blobInfo.base64() === base64 && blobInfo.blob().type === type2;
            });
          };
          var removeByUri = function(blobUri) {
            cache2 = filter$4(cache2, function(blobInfo) {
              if (blobInfo.blobUri() === blobUri) {
                URL.revokeObjectURL(blobInfo.blobUri());
                return false;
              }
              return true;
            });
          };
          var destroy2 = function() {
            each$k(cache2, function(cachedBlobInfo) {
              URL.revokeObjectURL(cachedBlobInfo.blobUri());
            });
            cache2 = [];
          };
          return {
            create: create2,
            add: add4,
            get: get2,
            getByUri,
            getByData,
            findFirst,
            removeByUri,
            destroy: destroy2
          };
        };
        var Uploader = function(uploadStatus, settings) {
          var pendingPromises = {};
          var pathJoin = function(path1, path2) {
            if (path1) {
              return path1.replace(/\/$/, "") + "/" + path2.replace(/^\//, "");
            }
            return path2;
          };
          var defaultHandler = function(blobInfo, success, failure, progress) {
            var xhr = new XMLHttpRequest();
            xhr.open("POST", settings.url);
            xhr.withCredentials = settings.credentials;
            xhr.upload.onprogress = function(e2) {
              progress(e2.loaded / e2.total * 100);
            };
            xhr.onerror = function() {
              failure("Image upload failed due to a XHR Transport error. Code: " + xhr.status);
            };
            xhr.onload = function() {
              if (xhr.status < 200 || xhr.status >= 300) {
                failure("HTTP Error: " + xhr.status);
                return;
              }
              var json = JSON.parse(xhr.responseText);
              if (!json || typeof json.location !== "string") {
                failure("Invalid JSON: " + xhr.responseText);
                return;
              }
              success(pathJoin(settings.basePath, json.location));
            };
            var formData = new FormData();
            formData.append("file", blobInfo.blob(), blobInfo.filename());
            xhr.send(formData);
          };
          var noUpload = function() {
            return new promiseObj(function(resolve3) {
              resolve3([]);
            });
          };
          var handlerSuccess = function(blobInfo, url) {
            return {
              url,
              blobInfo,
              status: true
            };
          };
          var handlerFailure = function(blobInfo, message, options) {
            return {
              url: "",
              blobInfo,
              status: false,
              error: {
                message,
                options
              }
            };
          };
          var resolvePending = function(blobUri, result) {
            Tools.each(pendingPromises[blobUri], function(resolve3) {
              resolve3(result);
            });
            delete pendingPromises[blobUri];
          };
          var uploadBlobInfo = function(blobInfo, handler, openNotification2) {
            uploadStatus.markPending(blobInfo.blobUri());
            return new promiseObj(function(resolve3) {
              var notification, progress;
              try {
                var closeNotification_1 = function() {
                  if (notification) {
                    notification.close();
                    progress = noop3;
                  }
                };
                var success = function(url) {
                  closeNotification_1();
                  uploadStatus.markUploaded(blobInfo.blobUri(), url);
                  resolvePending(blobInfo.blobUri(), handlerSuccess(blobInfo, url));
                  resolve3(handlerSuccess(blobInfo, url));
                };
                var failure = function(error4, options) {
                  var failureOptions = options ? options : {};
                  closeNotification_1();
                  uploadStatus.removeFailed(blobInfo.blobUri());
                  resolvePending(blobInfo.blobUri(), handlerFailure(blobInfo, error4, failureOptions));
                  resolve3(handlerFailure(blobInfo, error4, failureOptions));
                };
                progress = function(percent) {
                  if (percent < 0 || percent > 100) {
                    return;
                  }
                  Optional.from(notification).orThunk(function() {
                    return Optional.from(openNotification2).map(apply);
                  }).each(function(n2) {
                    notification = n2;
                    n2.progressBar.value(percent);
                  });
                };
                handler(blobInfo, success, failure, progress);
              } catch (ex) {
                resolve3(handlerFailure(blobInfo, ex.message, {}));
              }
            });
          };
          var isDefaultHandler = function(handler) {
            return handler === defaultHandler;
          };
          var pendingUploadBlobInfo = function(blobInfo) {
            var blobUri = blobInfo.blobUri();
            return new promiseObj(function(resolve3) {
              pendingPromises[blobUri] = pendingPromises[blobUri] || [];
              pendingPromises[blobUri].push(resolve3);
            });
          };
          var uploadBlobs = function(blobInfos, openNotification2) {
            blobInfos = Tools.grep(blobInfos, function(blobInfo) {
              return !uploadStatus.isUploaded(blobInfo.blobUri());
            });
            return promiseObj.all(Tools.map(blobInfos, function(blobInfo) {
              return uploadStatus.isPending(blobInfo.blobUri()) ? pendingUploadBlobInfo(blobInfo) : uploadBlobInfo(blobInfo, settings.handler, openNotification2);
            }));
          };
          var upload = function(blobInfos, openNotification2) {
            return !settings.url && isDefaultHandler(settings.handler) ? noUpload() : uploadBlobs(blobInfos, openNotification2);
          };
          if (isFunction2(settings.handler) === false) {
            settings.handler = defaultHandler;
          }
          return { upload };
        };
        var openNotification = function(editor) {
          return function() {
            return editor.notificationManager.open({
              text: editor.translate("Image uploading..."),
              type: "info",
              timeout: -1,
              progressBar: true
            });
          };
        };
        var createUploader = function(editor, uploadStatus) {
          return Uploader(uploadStatus, {
            url: getImageUploadUrl(editor),
            basePath: getImageUploadBasePath(editor),
            credentials: getImagesUploadCredentials(editor),
            handler: getImagesUploadHandler(editor)
          });
        };
        var ImageUploader = function(editor) {
          var uploadStatus = UploadStatus();
          var uploader = createUploader(editor, uploadStatus);
          return {
            upload: function(blobInfos, showNotification) {
              if (showNotification === void 0) {
                showNotification = true;
              }
              return uploader.upload(blobInfos, showNotification ? openNotification(editor) : void 0);
            }
          };
        };
        var UploadChangeHandler = function(editor) {
          var lastChangedLevel = Cell(null);
          editor.on("change AddUndo", function(e2) {
            lastChangedLevel.set(__assign({}, e2.level));
          });
          var fireIfChanged = function() {
            var data2 = editor.undoManager.data;
            last$2(data2).filter(function(level) {
              return !isEq$1(lastChangedLevel.get(), level);
            }).each(function(level) {
              editor.setDirty(true);
              editor.fire("change", {
                level,
                lastLevel: get$a(data2, data2.length - 2).getOrNull()
              });
            });
          };
          return { fireIfChanged };
        };
        var EditorUpload = function(editor) {
          var blobCache = BlobCache();
          var uploader, imageScanner;
          var uploadStatus = UploadStatus();
          var urlFilters = [];
          var changeHandler = UploadChangeHandler(editor);
          var aliveGuard = function(callback2) {
            return function(result) {
              if (editor.selection) {
                return callback2(result);
              }
              return [];
            };
          };
          var cacheInvalidator = function(url) {
            return url + (url.indexOf("?") === -1 ? "?" : "&") + new Date().getTime();
          };
          var replaceString = function(content, search2, replace) {
            var index = 0;
            do {
              index = content.indexOf(search2, index);
              if (index !== -1) {
                content = content.substring(0, index) + replace + content.substr(index + search2.length);
                index += replace.length - search2.length + 1;
              }
            } while (index !== -1);
            return content;
          };
          var replaceImageUrl = function(content, targetUrl, replacementUrl) {
            var replacementString = 'src="' + replacementUrl + '"' + (replacementUrl === Env.transparentSrc ? ' data-mce-placeholder="1"' : "");
            content = replaceString(content, 'src="' + targetUrl + '"', replacementString);
            content = replaceString(content, 'data-mce-src="' + targetUrl + '"', 'data-mce-src="' + replacementUrl + '"');
            return content;
          };
          var replaceUrlInUndoStack = function(targetUrl, replacementUrl) {
            each$k(editor.undoManager.data, function(level) {
              if (level.type === "fragmented") {
                level.fragments = map$3(level.fragments, function(fragment) {
                  return replaceImageUrl(fragment, targetUrl, replacementUrl);
                });
              } else {
                level.content = replaceImageUrl(level.content, targetUrl, replacementUrl);
              }
            });
          };
          var replaceImageUriInView = function(image, resultUri) {
            var src = editor.convertURL(resultUri, "src");
            replaceUrlInUndoStack(image.src, resultUri);
            editor.$(image).attr({
              "src": shouldReuseFileName(editor) ? cacheInvalidator(resultUri) : resultUri,
              "data-mce-src": src
            });
          };
          var uploadImages = function(callback2) {
            if (!uploader) {
              uploader = createUploader(editor, uploadStatus);
            }
            return scanForImages().then(aliveGuard(function(imageInfos) {
              var blobInfos = map$3(imageInfos, function(imageInfo) {
                return imageInfo.blobInfo;
              });
              return uploader.upload(blobInfos, openNotification(editor)).then(aliveGuard(function(result) {
                var imagesToRemove = [];
                var filteredResult = map$3(result, function(uploadInfo, index) {
                  var blobInfo = imageInfos[index].blobInfo;
                  var image = imageInfos[index].image;
                  if (uploadInfo.status && shouldReplaceBlobUris(editor)) {
                    blobCache.removeByUri(image.src);
                    if (isRtc(editor))
                      ;
                    else {
                      replaceImageUriInView(image, uploadInfo.url);
                    }
                  } else if (uploadInfo.error) {
                    if (uploadInfo.error.options.remove) {
                      replaceUrlInUndoStack(image.getAttribute("src"), Env.transparentSrc);
                      imagesToRemove.push(image);
                    }
                    uploadError(editor, uploadInfo.error.message);
                  }
                  return {
                    element: image,
                    status: uploadInfo.status,
                    uploadUri: uploadInfo.url,
                    blobInfo
                  };
                });
                if (filteredResult.length > 0) {
                  changeHandler.fireIfChanged();
                }
                if (imagesToRemove.length > 0) {
                  if (isRtc(editor)) {
                    console.error("Removing images on failed uploads is currently unsupported for RTC");
                  } else {
                    editor.undoManager.transact(function() {
                      each$k(imagesToRemove, function(element) {
                        editor.dom.remove(element);
                        blobCache.removeByUri(element.src);
                      });
                    });
                  }
                }
                if (callback2) {
                  callback2(filteredResult);
                }
                return filteredResult;
              }));
            }));
          };
          var uploadImagesAuto = function(callback2) {
            if (isAutomaticUploadsEnabled(editor)) {
              return uploadImages(callback2);
            }
          };
          var isValidDataUriImage = function(imgElm) {
            if (forall(urlFilters, function(filter2) {
              return filter2(imgElm);
            }) === false) {
              return false;
            }
            if (imgElm.getAttribute("src").indexOf("data:") === 0) {
              var dataImgFilter = getImagesDataImgFilter(editor);
              return dataImgFilter(imgElm);
            }
            return true;
          };
          var addFilter = function(filter2) {
            urlFilters.push(filter2);
          };
          var scanForImages = function() {
            if (!imageScanner) {
              imageScanner = ImageScanner(uploadStatus, blobCache);
            }
            return imageScanner.findAll(editor.getBody(), isValidDataUriImage).then(aliveGuard(function(result) {
              result = filter$4(result, function(resultItem) {
                if (typeof resultItem === "string") {
                  displayError(editor, resultItem);
                  return false;
                }
                return true;
              });
              if (isRtc(editor))
                ;
              else {
                each$k(result, function(resultItem) {
                  replaceUrlInUndoStack(resultItem.image.src, resultItem.blobInfo.blobUri());
                  resultItem.image.src = resultItem.blobInfo.blobUri();
                  resultItem.image.removeAttribute("data-mce-src");
                });
              }
              return result;
            }));
          };
          var destroy2 = function() {
            blobCache.destroy();
            uploadStatus.destroy();
            imageScanner = uploader = null;
          };
          var replaceBlobUris = function(content) {
            return content.replace(/src="(blob:[^"]+)"/g, function(match3, blobUri) {
              var resultUri = uploadStatus.getResultUri(blobUri);
              if (resultUri) {
                return 'src="' + resultUri + '"';
              }
              var blobInfo = blobCache.getByUri(blobUri);
              if (!blobInfo) {
                blobInfo = foldl(editor.editorManager.get(), function(result, editor2) {
                  return result || editor2.editorUpload && editor2.editorUpload.blobCache.getByUri(blobUri);
                }, null);
              }
              if (blobInfo) {
                var blob = blobInfo.blob();
                return 'src="data:' + blob.type + ";base64," + blobInfo.base64() + '"';
              }
              return match3;
            });
          };
          editor.on("SetContent", function() {
            if (isAutomaticUploadsEnabled(editor)) {
              uploadImagesAuto();
            } else {
              scanForImages();
            }
          });
          editor.on("RawSaveContent", function(e2) {
            e2.content = replaceBlobUris(e2.content);
          });
          editor.on("GetContent", function(e2) {
            if (e2.source_view || e2.format === "raw" || e2.format === "tree") {
              return;
            }
            e2.content = replaceBlobUris(e2.content);
          });
          editor.on("PostRender", function() {
            editor.parser.addNodeFilter("img", function(images) {
              each$k(images, function(img) {
                var src = img.attr("src");
                if (blobCache.getByUri(src)) {
                  return;
                }
                var resultUri = uploadStatus.getResultUri(src);
                if (resultUri) {
                  img.attr("src", resultUri);
                }
              });
            });
          });
          return {
            blobCache,
            addFilter,
            uploadImages,
            uploadImagesAuto,
            scanForImages,
            destroy: destroy2
          };
        };
        var get = function(dom2) {
          var formats = {
            valigntop: [{
              selector: "td,th",
              styles: { verticalAlign: "top" }
            }],
            valignmiddle: [{
              selector: "td,th",
              styles: { verticalAlign: "middle" }
            }],
            valignbottom: [{
              selector: "td,th",
              styles: { verticalAlign: "bottom" }
            }],
            alignleft: [
              {
                selector: "figure.image",
                collapsed: false,
                classes: "align-left",
                ceFalseOverride: true,
                preview: "font-family font-size"
              },
              {
                selector: "figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li",
                styles: { textAlign: "left" },
                inherit: false,
                preview: false,
                defaultBlock: "div"
              },
              {
                selector: "img,table,audio,video",
                collapsed: false,
                styles: { float: "left" },
                preview: "font-family font-size"
              }
            ],
            aligncenter: [
              {
                selector: "figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li",
                styles: { textAlign: "center" },
                inherit: false,
                preview: "font-family font-size",
                defaultBlock: "div"
              },
              {
                selector: "figure.image",
                collapsed: false,
                classes: "align-center",
                ceFalseOverride: true,
                preview: "font-family font-size"
              },
              {
                selector: "img,audio,video",
                collapsed: false,
                styles: {
                  display: "block",
                  marginLeft: "auto",
                  marginRight: "auto"
                },
                preview: false
              },
              {
                selector: "table",
                collapsed: false,
                styles: {
                  marginLeft: "auto",
                  marginRight: "auto"
                },
                preview: "font-family font-size"
              }
            ],
            alignright: [
              {
                selector: "figure.image",
                collapsed: false,
                classes: "align-right",
                ceFalseOverride: true,
                preview: "font-family font-size"
              },
              {
                selector: "figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li",
                styles: { textAlign: "right" },
                inherit: false,
                preview: "font-family font-size",
                defaultBlock: "div"
              },
              {
                selector: "img,table,audio,video",
                collapsed: false,
                styles: { float: "right" },
                preview: "font-family font-size"
              }
            ],
            alignjustify: [{
              selector: "figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li",
              styles: { textAlign: "justify" },
              inherit: false,
              defaultBlock: "div",
              preview: "font-family font-size"
            }],
            bold: [
              {
                inline: "strong",
                remove: "all",
                preserve_attributes: [
                  "class",
                  "style"
                ]
              },
              {
                inline: "span",
                styles: { fontWeight: "bold" }
              },
              {
                inline: "b",
                remove: "all",
                preserve_attributes: [
                  "class",
                  "style"
                ]
              }
            ],
            italic: [
              {
                inline: "em",
                remove: "all",
                preserve_attributes: [
                  "class",
                  "style"
                ]
              },
              {
                inline: "span",
                styles: { fontStyle: "italic" }
              },
              {
                inline: "i",
                remove: "all",
                preserve_attributes: [
                  "class",
                  "style"
                ]
              }
            ],
            underline: [
              {
                inline: "span",
                styles: { textDecoration: "underline" },
                exact: true
              },
              {
                inline: "u",
                remove: "all",
                preserve_attributes: [
                  "class",
                  "style"
                ]
              }
            ],
            strikethrough: [
              {
                inline: "span",
                styles: { textDecoration: "line-through" },
                exact: true
              },
              {
                inline: "strike",
                remove: "all",
                preserve_attributes: [
                  "class",
                  "style"
                ]
              },
              {
                inline: "s",
                remove: "all",
                preserve_attributes: [
                  "class",
                  "style"
                ]
              }
            ],
            forecolor: {
              inline: "span",
              styles: { color: "%value" },
              links: true,
              remove_similar: true,
              clear_child_styles: true
            },
            hilitecolor: {
              inline: "span",
              styles: { backgroundColor: "%value" },
              links: true,
              remove_similar: true,
              clear_child_styles: true
            },
            fontname: {
              inline: "span",
              toggle: false,
              styles: { fontFamily: "%value" },
              clear_child_styles: true
            },
            fontsize: {
              inline: "span",
              toggle: false,
              styles: { fontSize: "%value" },
              clear_child_styles: true
            },
            lineheight: {
              selector: "h1,h2,h3,h4,h5,h6,p,li,td,th,div",
              defaultBlock: "p",
              styles: { lineHeight: "%value" }
            },
            fontsize_class: {
              inline: "span",
              attributes: { class: "%value" }
            },
            blockquote: {
              block: "blockquote",
              wrapper: true,
              remove: "all"
            },
            subscript: { inline: "sub" },
            superscript: { inline: "sup" },
            code: { inline: "code" },
            link: {
              inline: "a",
              selector: "a",
              remove: "all",
              split: true,
              deep: true,
              onmatch: function(node, _fmt, _itemName) {
                return isElement$5(node) && node.hasAttribute("href");
              },
              onformat: function(elm, _fmt, vars) {
                Tools.each(vars, function(value2, key) {
                  dom2.setAttrib(elm, key, value2);
                });
              }
            },
            lang: {
              inline: "span",
              clear_child_styles: true,
              remove_similar: true,
              attributes: {
                "lang": "%value",
                "data-mce-lang": function(vars) {
                  var _a;
                  return (_a = vars === null || vars === void 0 ? void 0 : vars.customValue) !== null && _a !== void 0 ? _a : null;
                }
              }
            },
            removeformat: [
              {
                selector: "b,strong,em,i,font,u,strike,s,sub,sup,dfn,code,samp,kbd,var,cite,mark,q,del,ins,small",
                remove: "all",
                split: true,
                expand: false,
                block_expand: true,
                deep: true
              },
              {
                selector: "span",
                attributes: [
                  "style",
                  "class"
                ],
                remove: "empty",
                split: true,
                expand: false,
                deep: true
              },
              {
                selector: "*",
                attributes: [
                  "style",
                  "class"
                ],
                split: false,
                expand: false,
                deep: true
              }
            ]
          };
          Tools.each("p h1 h2 h3 h4 h5 h6 div address pre dt dd samp".split(/\s/), function(name2) {
            formats[name2] = {
              block: name2,
              remove: "all"
            };
          });
          return formats;
        };
        var FormatRegistry = function(editor) {
          var formats = {};
          var get$12 = function(name2) {
            return isNonNullable(name2) ? formats[name2] : formats;
          };
          var has2 = function(name2) {
            return has$2(formats, name2);
          };
          var register2 = function(name2, format3) {
            if (name2) {
              if (!isString$1(name2)) {
                each$j(name2, function(format4, name3) {
                  register2(name3, format4);
                });
              } else {
                if (!isArray$1(format3)) {
                  format3 = [format3];
                }
                each$k(format3, function(format4) {
                  if (isUndefined(format4.deep)) {
                    format4.deep = !isSelectorFormat(format4);
                  }
                  if (isUndefined(format4.split)) {
                    format4.split = !isSelectorFormat(format4) || isInlineFormat(format4);
                  }
                  if (isUndefined(format4.remove) && isSelectorFormat(format4) && !isInlineFormat(format4)) {
                    format4.remove = "none";
                  }
                  if (isSelectorFormat(format4) && isInlineFormat(format4)) {
                    format4.mixed = true;
                    format4.block_expand = true;
                  }
                  if (isString$1(format4.classes)) {
                    format4.classes = format4.classes.split(/\s+/);
                  }
                });
                formats[name2] = format3;
              }
            }
          };
          var unregister = function(name2) {
            if (name2 && formats[name2]) {
              delete formats[name2];
            }
            return formats;
          };
          register2(get(editor.dom));
          register2(getFormats(editor));
          return {
            get: get$12,
            has: has2,
            register: register2,
            unregister
          };
        };
        var each$5 = Tools.each;
        var dom = DOMUtils.DOM;
        var parsedSelectorToHtml = function(ancestry, editor) {
          var elm, item, fragment;
          var schema = editor && editor.schema || Schema({});
          var decorate = function(elm2, item2) {
            if (item2.classes.length) {
              dom.addClass(elm2, item2.classes.join(" "));
            }
            dom.setAttribs(elm2, item2.attrs);
          };
          var createElement = function(sItem) {
            item = typeof sItem === "string" ? {
              name: sItem,
              classes: [],
              attrs: {}
            } : sItem;
            var elm2 = dom.create(item.name);
            decorate(elm2, item);
            return elm2;
          };
          var getRequiredParent = function(elm2, candidate) {
            var name2 = typeof elm2 !== "string" ? elm2.nodeName.toLowerCase() : elm2;
            var elmRule = schema.getElementRule(name2);
            var parentsRequired = elmRule && elmRule.parentsRequired;
            if (parentsRequired && parentsRequired.length) {
              return candidate && Tools.inArray(parentsRequired, candidate) !== -1 ? candidate : parentsRequired[0];
            } else {
              return false;
            }
          };
          var wrapInHtml = function(elm2, ancestry2, siblings2) {
            var parent2, parentCandidate;
            var ancestor2 = ancestry2.length > 0 && ancestry2[0];
            var ancestorName = ancestor2 && ancestor2.name;
            var parentRequired = getRequiredParent(elm2, ancestorName);
            if (parentRequired) {
              if (ancestorName === parentRequired) {
                parentCandidate = ancestry2[0];
                ancestry2 = ancestry2.slice(1);
              } else {
                parentCandidate = parentRequired;
              }
            } else if (ancestor2) {
              parentCandidate = ancestry2[0];
              ancestry2 = ancestry2.slice(1);
            } else if (!siblings2) {
              return elm2;
            }
            if (parentCandidate) {
              parent2 = createElement(parentCandidate);
              parent2.appendChild(elm2);
            }
            if (siblings2) {
              if (!parent2) {
                parent2 = dom.create("div");
                parent2.appendChild(elm2);
              }
              Tools.each(siblings2, function(sibling2) {
                var siblingElm = createElement(sibling2);
                parent2.insertBefore(siblingElm, elm2);
              });
            }
            return wrapInHtml(parent2, ancestry2, parentCandidate && parentCandidate.siblings);
          };
          if (ancestry && ancestry.length) {
            item = ancestry[0];
            elm = createElement(item);
            fragment = dom.create("div");
            fragment.appendChild(wrapInHtml(elm, ancestry.slice(1), item.siblings));
            return fragment;
          } else {
            return "";
          }
        };
        var parseSelectorItem = function(item) {
          var tagName;
          var obj = {
            classes: [],
            attrs: {}
          };
          item = obj.selector = Tools.trim(item);
          if (item !== "*") {
            tagName = item.replace(/(?:([#\.]|::?)([\w\-]+)|(\[)([^\]]+)\]?)/g, function($0, $1, $2, $3, $4) {
              switch ($1) {
                case "#":
                  obj.attrs.id = $2;
                  break;
                case ".":
                  obj.classes.push($2);
                  break;
                case ":":
                  if (Tools.inArray("checked disabled enabled read-only required".split(" "), $2) !== -1) {
                    obj.attrs[$2] = $2;
                  }
                  break;
              }
              if ($3 === "[") {
                var m2 = $4.match(/([\w\-]+)(?:\=\"([^\"]+))?/);
                if (m2) {
                  obj.attrs[m2[1]] = m2[2];
                }
              }
              return "";
            });
          }
          obj.name = tagName || "div";
          return obj;
        };
        var parseSelector = function(selector) {
          if (!selector || typeof selector !== "string") {
            return [];
          }
          selector = selector.split(/\s*,\s*/)[0];
          selector = selector.replace(/\s*(~\+|~|\+|>)\s*/g, "$1");
          return Tools.map(selector.split(/(?:>|\s+(?![^\[\]]+\]))/), function(item) {
            var siblings2 = Tools.map(item.split(/(?:~\+|~|\+)/), parseSelectorItem);
            var obj = siblings2.pop();
            if (siblings2.length) {
              obj.siblings = siblings2;
            }
            return obj;
          }).reverse();
        };
        var getCssText = function(editor, format3) {
          var name2, previewFrag;
          var previewCss = "", parentFontSize;
          var previewStyles = getPreviewStyles(editor);
          if (previewStyles === "") {
            return "";
          }
          var removeVars = function(val) {
            return val.replace(/%(\w+)/g, "");
          };
          if (typeof format3 === "string") {
            format3 = editor.formatter.get(format3);
            if (!format3) {
              return;
            }
            format3 = format3[0];
          }
          if ("preview" in format3) {
            var previewOpt = get$9(format3, "preview");
            if (is$1(previewOpt, false)) {
              return "";
            } else {
              previewStyles = previewOpt.getOr(previewStyles);
            }
          }
          name2 = format3.block || format3.inline || "span";
          var items = parseSelector(format3.selector);
          if (items.length) {
            if (!items[0].name) {
              items[0].name = name2;
            }
            name2 = format3.selector;
            previewFrag = parsedSelectorToHtml(items, editor);
          } else {
            previewFrag = parsedSelectorToHtml([name2], editor);
          }
          var previewElm = dom.select(name2, previewFrag)[0] || previewFrag.firstChild;
          each$5(format3.styles, function(value2, name3) {
            var newValue = removeVars(value2);
            if (newValue) {
              dom.setStyle(previewElm, name3, newValue);
            }
          });
          each$5(format3.attributes, function(value2, name3) {
            var newValue = removeVars(value2);
            if (newValue) {
              dom.setAttrib(previewElm, name3, newValue);
            }
          });
          each$5(format3.classes, function(value2) {
            var newValue = removeVars(value2);
            if (!dom.hasClass(previewElm, newValue)) {
              dom.addClass(previewElm, newValue);
            }
          });
          editor.fire("PreviewFormats");
          dom.setStyles(previewFrag, {
            position: "absolute",
            left: -65535
          });
          editor.getBody().appendChild(previewFrag);
          parentFontSize = dom.getStyle(editor.getBody(), "fontSize", true);
          parentFontSize = /px$/.test(parentFontSize) ? parseInt(parentFontSize, 10) : 0;
          each$5(previewStyles.split(" "), function(name3) {
            var value2 = dom.getStyle(previewElm, name3, true);
            if (name3 === "background-color" && /transparent|rgba\s*\([^)]+,\s*0\)/.test(value2)) {
              value2 = dom.getStyle(editor.getBody(), name3, true);
              if (dom.toHex(value2).toLowerCase() === "#ffffff") {
                return;
              }
            }
            if (name3 === "color") {
              if (dom.toHex(value2).toLowerCase() === "#000000") {
                return;
              }
            }
            if (name3 === "font-size") {
              if (/em|%$/.test(value2)) {
                if (parentFontSize === 0) {
                  return;
                }
                var numValue = parseFloat(value2) / (/%$/.test(value2) ? 100 : 1);
                value2 = numValue * parentFontSize + "px";
              }
            }
            if (name3 === "border" && value2) {
              previewCss += "padding:0 2px;";
            }
            previewCss += name3 + ":" + value2 + ";";
          });
          editor.fire("AfterPreviewFormats");
          dom.remove(previewFrag);
          return previewCss;
        };
        var setup$h = function(editor) {
          editor.addShortcut("meta+b", "", "Bold");
          editor.addShortcut("meta+i", "", "Italic");
          editor.addShortcut("meta+u", "", "Underline");
          for (var i2 = 1; i2 <= 6; i2++) {
            editor.addShortcut("access+" + i2, "", [
              "FormatBlock",
              false,
              "h" + i2
            ]);
          }
          editor.addShortcut("access+7", "", [
            "FormatBlock",
            false,
            "p"
          ]);
          editor.addShortcut("access+8", "", [
            "FormatBlock",
            false,
            "div"
          ]);
          editor.addShortcut("access+9", "", [
            "FormatBlock",
            false,
            "address"
          ]);
        };
        var Formatter = function(editor) {
          var formats = FormatRegistry(editor);
          var formatChangeState = Cell(null);
          setup$h(editor);
          setup$k(editor);
          return {
            get: formats.get,
            has: formats.has,
            register: formats.register,
            unregister: formats.unregister,
            apply: function(name2, vars, node) {
              applyFormat(editor, name2, vars, node);
            },
            remove: function(name2, vars, node, similar) {
              removeFormat(editor, name2, vars, node, similar);
            },
            toggle: function(name2, vars, node) {
              toggleFormat(editor, name2, vars, node);
            },
            match: function(name2, vars, node, similar) {
              return matchFormat(editor, name2, vars, node, similar);
            },
            closest: function(names2) {
              return closestFormat(editor, names2);
            },
            matchAll: function(names2, vars) {
              return matchAllFormats(editor, names2, vars);
            },
            matchNode: function(node, name2, vars, similar) {
              return matchNodeFormat(editor, node, name2, vars, similar);
            },
            canApply: function(name2) {
              return canApplyFormat(editor, name2);
            },
            formatChanged: function(formats2, callback2, similar, vars) {
              return formatChanged(editor, formatChangeState, formats2, callback2, similar, vars);
            },
            getCssText: curry(getCssText, editor)
          };
        };
        var shouldIgnoreCommand = function(cmd) {
          switch (cmd.toLowerCase()) {
            case "undo":
            case "redo":
            case "mcerepaint":
            case "mcefocus":
              return true;
            default:
              return false;
          }
        };
        var registerEvents = function(editor, undoManager, locks) {
          var isFirstTypedCharacter = Cell(false);
          var addNonTypingUndoLevel = function(e2) {
            setTyping(undoManager, false, locks);
            undoManager.add({}, e2);
          };
          editor.on("init", function() {
            undoManager.add();
          });
          editor.on("BeforeExecCommand", function(e2) {
            var cmd = e2.command;
            if (!shouldIgnoreCommand(cmd)) {
              endTyping(undoManager, locks);
              undoManager.beforeChange();
            }
          });
          editor.on("ExecCommand", function(e2) {
            var cmd = e2.command;
            if (!shouldIgnoreCommand(cmd)) {
              addNonTypingUndoLevel(e2);
            }
          });
          editor.on("ObjectResizeStart cut", function() {
            undoManager.beforeChange();
          });
          editor.on("SaveContent ObjectResized blur", addNonTypingUndoLevel);
          editor.on("dragend", addNonTypingUndoLevel);
          editor.on("keyup", function(e2) {
            var keyCode = e2.keyCode;
            if (e2.isDefaultPrevented()) {
              return;
            }
            if (keyCode >= 33 && keyCode <= 36 || keyCode >= 37 && keyCode <= 40 || keyCode === 45 || e2.ctrlKey) {
              addNonTypingUndoLevel();
              editor.nodeChanged();
            }
            if (keyCode === 46 || keyCode === 8) {
              editor.nodeChanged();
            }
            if (isFirstTypedCharacter.get() && undoManager.typing && isEq$1(createFromEditor(editor), undoManager.data[0]) === false) {
              if (editor.isDirty() === false) {
                editor.setDirty(true);
                editor.fire("change", {
                  level: undoManager.data[0],
                  lastLevel: null
                });
              }
              editor.fire("TypingUndo");
              isFirstTypedCharacter.set(false);
              editor.nodeChanged();
            }
          });
          editor.on("keydown", function(e2) {
            var keyCode = e2.keyCode;
            if (e2.isDefaultPrevented()) {
              return;
            }
            if (keyCode >= 33 && keyCode <= 36 || keyCode >= 37 && keyCode <= 40 || keyCode === 45) {
              if (undoManager.typing) {
                addNonTypingUndoLevel(e2);
              }
              return;
            }
            var modKey = e2.ctrlKey && !e2.altKey || e2.metaKey;
            if ((keyCode < 16 || keyCode > 20) && keyCode !== 224 && keyCode !== 91 && !undoManager.typing && !modKey) {
              undoManager.beforeChange();
              setTyping(undoManager, true, locks);
              undoManager.add({}, e2);
              isFirstTypedCharacter.set(true);
            }
          });
          editor.on("mousedown", function(e2) {
            if (undoManager.typing) {
              addNonTypingUndoLevel(e2);
            }
          });
          var isInsertReplacementText = function(event) {
            return event.inputType === "insertReplacementText";
          };
          var isInsertTextDataNull = function(event) {
            return event.inputType === "insertText" && event.data === null;
          };
          var isInsertFromPasteOrDrop = function(event) {
            return event.inputType === "insertFromPaste" || event.inputType === "insertFromDrop";
          };
          editor.on("input", function(e2) {
            if (e2.inputType && (isInsertReplacementText(e2) || isInsertTextDataNull(e2) || isInsertFromPasteOrDrop(e2))) {
              addNonTypingUndoLevel(e2);
            }
          });
          editor.on("AddUndo Undo Redo ClearUndos", function(e2) {
            if (!e2.isDefaultPrevented()) {
              editor.nodeChanged();
            }
          });
        };
        var addKeyboardShortcuts = function(editor) {
          editor.addShortcut("meta+z", "", "Undo");
          editor.addShortcut("meta+y,meta+shift+z", "", "Redo");
        };
        var UndoManager = function(editor) {
          var beforeBookmark = value();
          var locks = Cell(0);
          var index = Cell(0);
          var undoManager = {
            data: [],
            typing: false,
            beforeChange: function() {
              beforeChange(editor, locks, beforeBookmark);
            },
            add: function(level, event) {
              return addUndoLevel(editor, undoManager, index, locks, beforeBookmark, level, event);
            },
            undo: function() {
              return undo(editor, undoManager, locks, index);
            },
            redo: function() {
              return redo(editor, index, undoManager.data);
            },
            clear: function() {
              clear(editor, undoManager, index);
            },
            reset: function() {
              reset(editor, undoManager);
            },
            hasUndo: function() {
              return hasUndo(editor, undoManager, index);
            },
            hasRedo: function() {
              return hasRedo(editor, undoManager, index);
            },
            transact: function(callback2) {
              return transact(editor, undoManager, locks, callback2);
            },
            ignore: function(callback2) {
              ignore(editor, locks, callback2);
            },
            extra: function(callback1, callback2) {
              extra(editor, undoManager, index, callback1, callback2);
            }
          };
          if (!isRtc(editor)) {
            registerEvents(editor, undoManager, locks);
          }
          addKeyboardShortcuts(editor);
          return undoManager;
        };
        var nonTypingKeycodes = [
          9,
          27,
          VK.HOME,
          VK.END,
          19,
          20,
          44,
          144,
          145,
          33,
          34,
          45,
          16,
          17,
          18,
          91,
          92,
          93,
          VK.DOWN,
          VK.UP,
          VK.LEFT,
          VK.RIGHT
        ].concat(Env.browser.isFirefox() ? [224] : []);
        var placeholderAttr = "data-mce-placeholder";
        var isKeyboardEvent = function(e2) {
          return e2.type === "keydown" || e2.type === "keyup";
        };
        var isDeleteEvent = function(e2) {
          var keyCode = e2.keyCode;
          return keyCode === VK.BACKSPACE || keyCode === VK.DELETE;
        };
        var isNonTypingKeyboardEvent = function(e2) {
          if (isKeyboardEvent(e2)) {
            var keyCode = e2.keyCode;
            return !isDeleteEvent(e2) && (VK.metaKeyPressed(e2) || e2.altKey || keyCode >= 112 && keyCode <= 123 || contains$3(nonTypingKeycodes, keyCode));
          } else {
            return false;
          }
        };
        var isTypingKeyboardEvent = function(e2) {
          return isKeyboardEvent(e2) && !(isDeleteEvent(e2) || e2.type === "keyup" && e2.keyCode === 229);
        };
        var isVisuallyEmpty = function(dom2, rootElm, forcedRootBlock) {
          if (isEmpty$2(SugarElement.fromDom(rootElm), false)) {
            var isForcedRootBlockFalse = forcedRootBlock === "";
            var firstElement2 = rootElm.firstElementChild;
            if (!firstElement2) {
              return true;
            } else if (dom2.getStyle(rootElm.firstElementChild, "padding-left") || dom2.getStyle(rootElm.firstElementChild, "padding-right")) {
              return false;
            } else {
              return isForcedRootBlockFalse ? !dom2.isBlock(firstElement2) : forcedRootBlock === firstElement2.nodeName.toLowerCase();
            }
          } else {
            return false;
          }
        };
        var setup$g = function(editor) {
          var dom2 = editor.dom;
          var rootBlock = getForcedRootBlock(editor);
          var placeholder = getPlaceholder(editor);
          var updatePlaceholder = function(e2, initial) {
            if (isNonTypingKeyboardEvent(e2)) {
              return;
            }
            var body = editor.getBody();
            var showPlaceholder = isTypingKeyboardEvent(e2) ? false : isVisuallyEmpty(dom2, body, rootBlock);
            var isPlaceholderShown = dom2.getAttrib(body, placeholderAttr) !== "";
            if (isPlaceholderShown !== showPlaceholder || initial) {
              dom2.setAttrib(body, placeholderAttr, showPlaceholder ? placeholder : null);
              dom2.setAttrib(body, "aria-placeholder", showPlaceholder ? placeholder : null);
              firePlaceholderToggle(editor, showPlaceholder);
              editor.on(showPlaceholder ? "keydown" : "keyup", updatePlaceholder);
              editor.off(showPlaceholder ? "keyup" : "keydown", updatePlaceholder);
            }
          };
          if (placeholder) {
            editor.on("init", function(e2) {
              updatePlaceholder(e2, true);
              editor.on("change SetContent ExecCommand", updatePlaceholder);
              editor.on("paste", function(e3) {
                return Delay.setEditorTimeout(editor, function() {
                  return updatePlaceholder(e3);
                });
              });
            });
          }
        };
        var strongRtl = /[\u0591-\u07FF\uFB1D-\uFDFF\uFE70-\uFEFC]/;
        var hasStrongRtl = function(text) {
          return strongRtl.test(text);
        };
        var isInlineTarget = function(editor, elm) {
          return is$2(SugarElement.fromDom(elm), getInlineBoundarySelector(editor));
        };
        var isRtl = function(element) {
          return DOMUtils.DOM.getStyle(element, "direction", true) === "rtl" || hasStrongRtl(element.textContent);
        };
        var findInlineParents = function(isInlineTarget2, rootNode, pos) {
          return filter$4(DOMUtils.DOM.getParents(pos.container(), "*", rootNode), isInlineTarget2);
        };
        var findRootInline = function(isInlineTarget2, rootNode, pos) {
          var parents2 = findInlineParents(isInlineTarget2, rootNode, pos);
          return Optional.from(parents2[parents2.length - 1]);
        };
        var hasSameParentBlock = function(rootNode, node1, node2) {
          var block1 = getParentBlock$2(node1, rootNode);
          var block2 = getParentBlock$2(node2, rootNode);
          return block1 && block1 === block2;
        };
        var isAtZwsp = function(pos) {
          return isBeforeInline(pos) || isAfterInline(pos);
        };
        var normalizePosition = function(forward, pos) {
          if (!pos) {
            return pos;
          }
          var container = pos.container(), offset2 = pos.offset();
          if (forward) {
            if (isCaretContainerInline(container)) {
              if (isText$7(container.nextSibling)) {
                return CaretPosition(container.nextSibling, 0);
              } else {
                return CaretPosition.after(container);
              }
            } else {
              return isBeforeInline(pos) ? CaretPosition(container, offset2 + 1) : pos;
            }
          } else {
            if (isCaretContainerInline(container)) {
              if (isText$7(container.previousSibling)) {
                return CaretPosition(container.previousSibling, container.previousSibling.data.length);
              } else {
                return CaretPosition.before(container);
              }
            } else {
              return isAfterInline(pos) ? CaretPosition(container, offset2 - 1) : pos;
            }
          }
        };
        var normalizeForwards = curry(normalizePosition, true);
        var normalizeBackwards = curry(normalizePosition, false);
        var isBeforeRoot = function(rootNode) {
          return function(elm) {
            return eq2(rootNode, SugarElement.fromDom(elm.dom.parentNode));
          };
        };
        var isTextBlockOrListItem = function(element) {
          return isTextBlock$2(element) || isListItem(element);
        };
        var getParentBlock$1 = function(rootNode, elm) {
          if (contains$1(rootNode, elm)) {
            return closest$3(elm, isTextBlockOrListItem, isBeforeRoot(rootNode));
          } else {
            return Optional.none();
          }
        };
        var placeCaretInEmptyBody = function(editor) {
          var body = editor.getBody();
          var node = body.firstChild && editor.dom.isBlock(body.firstChild) ? body.firstChild : body;
          editor.selection.setCursorLocation(node, 0);
        };
        var paddEmptyBody = function(editor) {
          if (editor.dom.isEmpty(editor.getBody())) {
            editor.setContent("");
            placeCaretInEmptyBody(editor);
          }
        };
        var willDeleteLastPositionInElement = function(forward, fromPos, elm) {
          return lift2(firstPositionIn(elm), lastPositionIn(elm), function(firstPos, lastPos) {
            var normalizedFirstPos = normalizePosition(true, firstPos);
            var normalizedLastPos = normalizePosition(false, lastPos);
            var normalizedFromPos = normalizePosition(false, fromPos);
            if (forward) {
              return nextPosition(elm, normalizedFromPos).exists(function(nextPos) {
                return nextPos.isEqual(normalizedLastPos) && fromPos.isEqual(normalizedFirstPos);
              });
            } else {
              return prevPosition(elm, normalizedFromPos).exists(function(prevPos) {
                return prevPos.isEqual(normalizedFirstPos) && fromPos.isEqual(normalizedLastPos);
              });
            }
          }).getOr(true);
        };
        var blockPosition = function(block, position) {
          return {
            block,
            position
          };
        };
        var blockBoundary = function(from2, to2) {
          return {
            from: from2,
            to: to2
          };
        };
        var getBlockPosition = function(rootNode, pos) {
          var rootElm = SugarElement.fromDom(rootNode);
          var containerElm = SugarElement.fromDom(pos.container());
          return getParentBlock$1(rootElm, containerElm).map(function(block) {
            return blockPosition(block, pos);
          });
        };
        var isDifferentBlocks = function(blockBoundary2) {
          return eq2(blockBoundary2.from.block, blockBoundary2.to.block) === false;
        };
        var hasSameParent = function(blockBoundary2) {
          return parent(blockBoundary2.from.block).bind(function(parent1) {
            return parent(blockBoundary2.to.block).filter(function(parent2) {
              return eq2(parent1, parent2);
            });
          }).isSome();
        };
        var isEditable$1 = function(blockBoundary2) {
          return isContentEditableFalse$b(blockBoundary2.from.block.dom) === false && isContentEditableFalse$b(blockBoundary2.to.block.dom) === false;
        };
        var skipLastBr = function(rootNode, forward, blockPosition2) {
          if (isBr$5(blockPosition2.position.getNode()) && isEmpty$2(blockPosition2.block) === false) {
            return positionIn(false, blockPosition2.block.dom).bind(function(lastPositionInBlock) {
              if (lastPositionInBlock.isEqual(blockPosition2.position)) {
                return fromPosition(forward, rootNode, lastPositionInBlock).bind(function(to2) {
                  return getBlockPosition(rootNode, to2);
                });
              } else {
                return Optional.some(blockPosition2);
              }
            }).getOr(blockPosition2);
          } else {
            return blockPosition2;
          }
        };
        var readFromRange = function(rootNode, forward, rng) {
          var fromBlockPos = getBlockPosition(rootNode, CaretPosition.fromRangeStart(rng));
          var toBlockPos = fromBlockPos.bind(function(blockPos) {
            return fromPosition(forward, rootNode, blockPos.position).bind(function(to2) {
              return getBlockPosition(rootNode, to2).map(function(blockPos2) {
                return skipLastBr(rootNode, forward, blockPos2);
              });
            });
          });
          return lift2(fromBlockPos, toBlockPos, blockBoundary).filter(function(blockBoundary2) {
            return isDifferentBlocks(blockBoundary2) && hasSameParent(blockBoundary2) && isEditable$1(blockBoundary2);
          });
        };
        var read$1 = function(rootNode, forward, rng) {
          return rng.collapsed ? readFromRange(rootNode, forward, rng) : Optional.none();
        };
        var getChildrenUntilBlockBoundary = function(block) {
          var children$1 = children(block);
          return findIndex$2(children$1, isBlock$2).fold(constant(children$1), function(index) {
            return children$1.slice(0, index);
          });
        };
        var extractChildren = function(block) {
          var children2 = getChildrenUntilBlockBoundary(block);
          each$k(children2, remove$7);
          return children2;
        };
        var removeEmptyRoot = function(rootNode, block) {
          var parents2 = parentsAndSelf(block, rootNode);
          return find$3(parents2.reverse(), function(element) {
            return isEmpty$2(element);
          }).each(remove$7);
        };
        var isEmptyBefore = function(el) {
          return filter$4(prevSiblings(el), function(el2) {
            return !isEmpty$2(el2);
          }).length === 0;
        };
        var nestedBlockMerge = function(rootNode, fromBlock, toBlock, insertionPoint) {
          if (isEmpty$2(toBlock)) {
            fillWithPaddingBr(toBlock);
            return firstPositionIn(toBlock.dom);
          }
          if (isEmptyBefore(insertionPoint) && isEmpty$2(fromBlock)) {
            before$4(insertionPoint, SugarElement.fromTag("br"));
          }
          var position = prevPosition(toBlock.dom, CaretPosition.before(insertionPoint.dom));
          each$k(extractChildren(fromBlock), function(child2) {
            before$4(insertionPoint, child2);
          });
          removeEmptyRoot(rootNode, fromBlock);
          return position;
        };
        var sidelongBlockMerge = function(rootNode, fromBlock, toBlock) {
          if (isEmpty$2(toBlock)) {
            remove$7(toBlock);
            if (isEmpty$2(fromBlock)) {
              fillWithPaddingBr(fromBlock);
            }
            return firstPositionIn(fromBlock.dom);
          }
          var position = lastPositionIn(toBlock.dom);
          each$k(extractChildren(fromBlock), function(child2) {
            append$1(toBlock, child2);
          });
          removeEmptyRoot(rootNode, fromBlock);
          return position;
        };
        var findInsertionPoint = function(toBlock, block) {
          var parentsAndSelf$1 = parentsAndSelf(block, toBlock);
          return Optional.from(parentsAndSelf$1[parentsAndSelf$1.length - 1]);
        };
        var getInsertionPoint = function(fromBlock, toBlock) {
          return contains$1(toBlock, fromBlock) ? findInsertionPoint(toBlock, fromBlock) : Optional.none();
        };
        var trimBr = function(first2, block) {
          positionIn(first2, block.dom).map(function(position) {
            return position.getNode();
          }).map(SugarElement.fromDom).filter(isBr$4).each(remove$7);
        };
        var mergeBlockInto = function(rootNode, fromBlock, toBlock) {
          trimBr(true, fromBlock);
          trimBr(false, toBlock);
          return getInsertionPoint(fromBlock, toBlock).fold(curry(sidelongBlockMerge, rootNode, fromBlock, toBlock), curry(nestedBlockMerge, rootNode, fromBlock, toBlock));
        };
        var mergeBlocks = function(rootNode, forward, block1, block2) {
          return forward ? mergeBlockInto(rootNode, block2, block1) : mergeBlockInto(rootNode, block1, block2);
        };
        var backspaceDelete$8 = function(editor, forward) {
          var rootNode = SugarElement.fromDom(editor.getBody());
          var position = read$1(rootNode.dom, forward, editor.selection.getRng()).bind(function(blockBoundary2) {
            return mergeBlocks(rootNode, forward, blockBoundary2.from.block, blockBoundary2.to.block);
          });
          position.each(function(pos) {
            editor.selection.setRng(pos.toRange());
          });
          return position.isSome();
        };
        var deleteRangeMergeBlocks = function(rootNode, selection) {
          var rng = selection.getRng();
          return lift2(getParentBlock$1(rootNode, SugarElement.fromDom(rng.startContainer)), getParentBlock$1(rootNode, SugarElement.fromDom(rng.endContainer)), function(block1, block2) {
            if (eq2(block1, block2) === false) {
              rng.deleteContents();
              mergeBlocks(rootNode, true, block1, block2).each(function(pos) {
                selection.setRng(pos.toRange());
              });
              return true;
            } else {
              return false;
            }
          }).getOr(false);
        };
        var isRawNodeInTable = function(root, rawNode) {
          var node = SugarElement.fromDom(rawNode);
          var isRoot = curry(eq2, root);
          return ancestor$3(node, isTableCell$4, isRoot).isSome();
        };
        var isSelectionInTable = function(root, rng) {
          return isRawNodeInTable(root, rng.startContainer) || isRawNodeInTable(root, rng.endContainer);
        };
        var isEverythingSelected = function(root, rng) {
          var noPrevious = prevPosition(root.dom, CaretPosition.fromRangeStart(rng)).isNone();
          var noNext = nextPosition(root.dom, CaretPosition.fromRangeEnd(rng)).isNone();
          return !isSelectionInTable(root, rng) && noPrevious && noNext;
        };
        var emptyEditor = function(editor) {
          editor.setContent("");
          editor.selection.setCursorLocation();
          return true;
        };
        var deleteRange$1 = function(editor) {
          var rootNode = SugarElement.fromDom(editor.getBody());
          var rng = editor.selection.getRng();
          return isEverythingSelected(rootNode, rng) ? emptyEditor(editor) : deleteRangeMergeBlocks(rootNode, editor.selection);
        };
        var backspaceDelete$7 = function(editor, _forward) {
          return editor.selection.isCollapsed() ? false : deleteRange$1(editor);
        };
        var isContentEditableTrue$2 = isContentEditableTrue$4;
        var isContentEditableFalse$4 = isContentEditableFalse$b;
        var showCaret = function(direction, editor, node, before2, scrollIntoView) {
          return Optional.from(editor._selectionOverrides.showCaret(direction, node, before2, scrollIntoView));
        };
        var getNodeRange = function(node) {
          var rng = node.ownerDocument.createRange();
          rng.selectNode(node);
          return rng;
        };
        var selectNode = function(editor, node) {
          var e2 = editor.fire("BeforeObjectSelected", { target: node });
          if (e2.isDefaultPrevented()) {
            return Optional.none();
          }
          return Optional.some(getNodeRange(node));
        };
        var renderCaretAtRange = function(editor, range2, scrollIntoView) {
          var normalizedRange = normalizeRange(1, editor.getBody(), range2);
          var caretPosition = CaretPosition.fromRangeStart(normalizedRange);
          var caretPositionNode = caretPosition.getNode();
          if (isInlineFakeCaretTarget(caretPositionNode)) {
            return showCaret(1, editor, caretPositionNode, !caretPosition.isAtEnd(), false);
          }
          var caretPositionBeforeNode = caretPosition.getNode(true);
          if (isInlineFakeCaretTarget(caretPositionBeforeNode)) {
            return showCaret(1, editor, caretPositionBeforeNode, false, false);
          }
          var ceRoot = editor.dom.getParent(caretPosition.getNode(), function(node) {
            return isContentEditableFalse$4(node) || isContentEditableTrue$2(node);
          });
          if (isInlineFakeCaretTarget(ceRoot)) {
            return showCaret(1, editor, ceRoot, false, scrollIntoView);
          }
          return Optional.none();
        };
        var renderRangeCaret = function(editor, range2, scrollIntoView) {
          return range2.collapsed ? renderCaretAtRange(editor, range2, scrollIntoView).getOr(range2) : range2;
        };
        var isBeforeBoundary = function(pos) {
          return isBeforeContentEditableFalse(pos) || isBeforeMedia(pos);
        };
        var isAfterBoundary = function(pos) {
          return isAfterContentEditableFalse(pos) || isAfterMedia(pos);
        };
        var trimEmptyTextNode = function(dom2, node) {
          if (isText$7(node) && node.data.length === 0) {
            dom2.remove(node);
          }
        };
        var deleteContentAndShowCaret = function(editor, range2, node, direction, forward, peekCaretPosition) {
          showCaret(direction, editor, peekCaretPosition.getNode(!forward), forward, true).each(function(caretRange) {
            if (range2.collapsed) {
              var deleteRange2 = range2.cloneRange();
              if (forward) {
                deleteRange2.setEnd(caretRange.startContainer, caretRange.startOffset);
              } else {
                deleteRange2.setStart(caretRange.endContainer, caretRange.endOffset);
              }
              deleteRange2.deleteContents();
            } else {
              range2.deleteContents();
            }
            editor.selection.setRng(caretRange);
          });
          trimEmptyTextNode(editor.dom, node);
          return true;
        };
        var deleteBoundaryText = function(editor, forward) {
          var range2 = editor.selection.getRng();
          if (!isText$7(range2.commonAncestorContainer)) {
            return false;
          }
          var direction = forward ? HDirection.Forwards : HDirection.Backwards;
          var caretWalker = CaretWalker(editor.getBody());
          var getNextPosFn = curry(getVisualCaretPosition, forward ? caretWalker.next : caretWalker.prev);
          var isBeforeFn = forward ? isBeforeBoundary : isAfterBoundary;
          var caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range2);
          var nextCaretPosition = normalizePosition(forward, getNextPosFn(caretPosition));
          if (!nextCaretPosition || !isMoveInsideSameBlock(caretPosition, nextCaretPosition)) {
            return false;
          } else if (isBeforeFn(nextCaretPosition)) {
            return deleteContentAndShowCaret(editor, range2, caretPosition.getNode(), direction, forward, nextCaretPosition);
          }
          var peekCaretPosition = getNextPosFn(nextCaretPosition);
          if (peekCaretPosition && isBeforeFn(peekCaretPosition)) {
            if (isMoveInsideSameBlock(nextCaretPosition, peekCaretPosition)) {
              return deleteContentAndShowCaret(editor, range2, caretPosition.getNode(), direction, forward, peekCaretPosition);
            }
          }
          return false;
        };
        var backspaceDelete$6 = function(editor, forward) {
          return deleteBoundaryText(editor, forward);
        };
        var isCompoundElement = function(node) {
          return isTableCell$4(SugarElement.fromDom(node)) || isListItem(SugarElement.fromDom(node));
        };
        var DeleteAction = Adt.generate([
          { remove: ["element"] },
          { moveToElement: ["element"] },
          { moveToPosition: ["position"] }
        ]);
        var isAtContentEditableBlockCaret = function(forward, from2) {
          var elm = from2.getNode(forward === false);
          var caretLocation = forward ? "after" : "before";
          return isElement$5(elm) && elm.getAttribute("data-mce-caret") === caretLocation;
        };
        var isDeleteFromCefDifferentBlocks = function(root, forward, from2, to2) {
          var inSameBlock = function(elm) {
            return isInline$1(SugarElement.fromDom(elm)) && !isInSameBlock(from2, to2, root);
          };
          return getRelativeCefElm(!forward, from2).fold(function() {
            return getRelativeCefElm(forward, to2).fold(never, inSameBlock);
          }, inSameBlock);
        };
        var deleteEmptyBlockOrMoveToCef = function(root, forward, from2, to2) {
          var toCefElm = to2.getNode(forward === false);
          return getParentBlock$1(SugarElement.fromDom(root), SugarElement.fromDom(from2.getNode())).map(function(blockElm) {
            return isEmpty$2(blockElm) ? DeleteAction.remove(blockElm.dom) : DeleteAction.moveToElement(toCefElm);
          }).orThunk(function() {
            return Optional.some(DeleteAction.moveToElement(toCefElm));
          });
        };
        var findCefPosition = function(root, forward, from2) {
          return fromPosition(forward, root, from2).bind(function(to2) {
            if (isCompoundElement(to2.getNode())) {
              return Optional.none();
            } else if (isDeleteFromCefDifferentBlocks(root, forward, from2, to2)) {
              return Optional.none();
            } else if (forward && isContentEditableFalse$b(to2.getNode())) {
              return deleteEmptyBlockOrMoveToCef(root, forward, from2, to2);
            } else if (forward === false && isContentEditableFalse$b(to2.getNode(true))) {
              return deleteEmptyBlockOrMoveToCef(root, forward, from2, to2);
            } else if (forward && isAfterContentEditableFalse(from2)) {
              return Optional.some(DeleteAction.moveToPosition(to2));
            } else if (forward === false && isBeforeContentEditableFalse(from2)) {
              return Optional.some(DeleteAction.moveToPosition(to2));
            } else {
              return Optional.none();
            }
          });
        };
        var getContentEditableBlockAction = function(forward, elm) {
          if (forward && isContentEditableFalse$b(elm.nextSibling)) {
            return Optional.some(DeleteAction.moveToElement(elm.nextSibling));
          } else if (forward === false && isContentEditableFalse$b(elm.previousSibling)) {
            return Optional.some(DeleteAction.moveToElement(elm.previousSibling));
          } else {
            return Optional.none();
          }
        };
        var skipMoveToActionFromInlineCefToContent = function(root, from2, deleteAction2) {
          return deleteAction2.fold(function(elm) {
            return Optional.some(DeleteAction.remove(elm));
          }, function(elm) {
            return Optional.some(DeleteAction.moveToElement(elm));
          }, function(to2) {
            if (isInSameBlock(from2, to2, root)) {
              return Optional.none();
            } else {
              return Optional.some(DeleteAction.moveToPosition(to2));
            }
          });
        };
        var getContentEditableAction = function(root, forward, from2) {
          if (isAtContentEditableBlockCaret(forward, from2)) {
            return getContentEditableBlockAction(forward, from2.getNode(forward === false)).fold(function() {
              return findCefPosition(root, forward, from2);
            }, Optional.some);
          } else {
            return findCefPosition(root, forward, from2).bind(function(deleteAction2) {
              return skipMoveToActionFromInlineCefToContent(root, from2, deleteAction2);
            });
          }
        };
        var read2 = function(root, forward, rng) {
          var normalizedRange = normalizeRange(forward ? 1 : -1, root, rng);
          var from2 = CaretPosition.fromRangeStart(normalizedRange);
          var rootElement = SugarElement.fromDom(root);
          if (forward === false && isAfterContentEditableFalse(from2)) {
            return Optional.some(DeleteAction.remove(from2.getNode(true)));
          } else if (forward && isBeforeContentEditableFalse(from2)) {
            return Optional.some(DeleteAction.remove(from2.getNode()));
          } else if (forward === false && isBeforeContentEditableFalse(from2) && isAfterBr(rootElement, from2)) {
            return findPreviousBr(rootElement, from2).map(function(br) {
              return DeleteAction.remove(br.getNode());
            });
          } else if (forward && isAfterContentEditableFalse(from2) && isBeforeBr$1(rootElement, from2)) {
            return findNextBr(rootElement, from2).map(function(br) {
              return DeleteAction.remove(br.getNode());
            });
          } else {
            return getContentEditableAction(root, forward, from2);
          }
        };
        var deleteElement$1 = function(editor, forward) {
          return function(element) {
            editor._selectionOverrides.hideFakeCaret();
            deleteElement$2(editor, forward, SugarElement.fromDom(element));
            return true;
          };
        };
        var moveToElement = function(editor, forward) {
          return function(element) {
            var pos = forward ? CaretPosition.before(element) : CaretPosition.after(element);
            editor.selection.setRng(pos.toRange());
            return true;
          };
        };
        var moveToPosition = function(editor) {
          return function(pos) {
            editor.selection.setRng(pos.toRange());
            return true;
          };
        };
        var getAncestorCe = function(editor, node) {
          return Optional.from(getContentEditableRoot$1(editor.getBody(), node));
        };
        var backspaceDeleteCaret = function(editor, forward) {
          var selectedNode = editor.selection.getNode();
          return getAncestorCe(editor, selectedNode).filter(isContentEditableFalse$b).fold(function() {
            return read2(editor.getBody(), forward, editor.selection.getRng()).exists(function(deleteAction2) {
              return deleteAction2.fold(deleteElement$1(editor, forward), moveToElement(editor, forward), moveToPosition(editor));
            });
          }, always);
        };
        var deleteOffscreenSelection = function(rootElement) {
          each$k(descendants(rootElement, ".mce-offscreen-selection"), remove$7);
        };
        var backspaceDeleteRange = function(editor, forward) {
          var selectedNode = editor.selection.getNode();
          if (isContentEditableFalse$b(selectedNode) && !isTableCell$5(selectedNode)) {
            var hasCefAncestor = getAncestorCe(editor, selectedNode.parentNode).filter(isContentEditableFalse$b);
            return hasCefAncestor.fold(function() {
              deleteOffscreenSelection(SugarElement.fromDom(editor.getBody()));
              deleteElement$2(editor, forward, SugarElement.fromDom(editor.selection.getNode()));
              paddEmptyBody(editor);
              return true;
            }, always);
          }
          return false;
        };
        var paddEmptyElement = function(editor) {
          var dom2 = editor.dom, selection = editor.selection;
          var ceRoot = getContentEditableRoot$1(editor.getBody(), selection.getNode());
          if (isContentEditableTrue$4(ceRoot) && dom2.isBlock(ceRoot) && dom2.isEmpty(ceRoot)) {
            var br = dom2.create("br", { "data-mce-bogus": "1" });
            dom2.setHTML(ceRoot, "");
            ceRoot.appendChild(br);
            selection.setRng(CaretPosition.before(br).toRange());
          }
          return true;
        };
        var backspaceDelete$5 = function(editor, forward) {
          if (editor.selection.isCollapsed()) {
            return backspaceDeleteCaret(editor, forward);
          } else {
            return backspaceDeleteRange(editor, forward);
          }
        };
        var deleteCaret$2 = function(editor, forward) {
          var fromPos = CaretPosition.fromRangeStart(editor.selection.getRng());
          return fromPosition(forward, editor.getBody(), fromPos).filter(function(pos) {
            return forward ? isBeforeImageBlock(pos) : isAfterImageBlock(pos);
          }).bind(function(pos) {
            return Optional.from(getChildNodeAtRelativeOffset(forward ? 0 : -1, pos));
          }).exists(function(elm) {
            editor.selection.select(elm);
            return true;
          });
        };
        var backspaceDelete$4 = function(editor, forward) {
          return editor.selection.isCollapsed() ? deleteCaret$2(editor, forward) : false;
        };
        var isText = isText$7;
        var startsWithCaretContainer = function(node) {
          return isText(node) && node.data[0] === ZWSP$1;
        };
        var endsWithCaretContainer = function(node) {
          return isText(node) && node.data[node.data.length - 1] === ZWSP$1;
        };
        var createZwsp = function(node) {
          return node.ownerDocument.createTextNode(ZWSP$1);
        };
        var insertBefore = function(node) {
          if (isText(node.previousSibling)) {
            if (endsWithCaretContainer(node.previousSibling)) {
              return node.previousSibling;
            } else {
              node.previousSibling.appendData(ZWSP$1);
              return node.previousSibling;
            }
          } else if (isText(node)) {
            if (startsWithCaretContainer(node)) {
              return node;
            } else {
              node.insertData(0, ZWSP$1);
              return node;
            }
          } else {
            var newNode = createZwsp(node);
            node.parentNode.insertBefore(newNode, node);
            return newNode;
          }
        };
        var insertAfter = function(node) {
          if (isText(node.nextSibling)) {
            if (startsWithCaretContainer(node.nextSibling)) {
              return node.nextSibling;
            } else {
              node.nextSibling.insertData(0, ZWSP$1);
              return node.nextSibling;
            }
          } else if (isText(node)) {
            if (endsWithCaretContainer(node)) {
              return node;
            } else {
              node.appendData(ZWSP$1);
              return node;
            }
          } else {
            var newNode = createZwsp(node);
            if (node.nextSibling) {
              node.parentNode.insertBefore(newNode, node.nextSibling);
            } else {
              node.parentNode.appendChild(newNode);
            }
            return newNode;
          }
        };
        var insertInline = function(before2, node) {
          return before2 ? insertBefore(node) : insertAfter(node);
        };
        var insertInlineBefore = curry(insertInline, true);
        var insertInlineAfter = curry(insertInline, false);
        var insertInlinePos = function(pos, before2) {
          if (isText$7(pos.container())) {
            return insertInline(before2, pos.container());
          } else {
            return insertInline(before2, pos.getNode());
          }
        };
        var isPosCaretContainer = function(pos, caret) {
          var caretNode = caret.get();
          return caretNode && pos.container() === caretNode && isCaretContainerInline(caretNode);
        };
        var renderCaret = function(caret, location2) {
          return location2.fold(function(element) {
            remove$2(caret.get());
            var text = insertInlineBefore(element);
            caret.set(text);
            return Optional.some(CaretPosition(text, text.length - 1));
          }, function(element) {
            return firstPositionIn(element).map(function(pos) {
              if (!isPosCaretContainer(pos, caret)) {
                remove$2(caret.get());
                var text = insertInlinePos(pos, true);
                caret.set(text);
                return CaretPosition(text, 1);
              } else {
                return CaretPosition(caret.get(), 1);
              }
            });
          }, function(element) {
            return lastPositionIn(element).map(function(pos) {
              if (!isPosCaretContainer(pos, caret)) {
                remove$2(caret.get());
                var text = insertInlinePos(pos, false);
                caret.set(text);
                return CaretPosition(text, text.length - 1);
              } else {
                return CaretPosition(caret.get(), caret.get().length - 1);
              }
            });
          }, function(element) {
            remove$2(caret.get());
            var text = insertInlineAfter(element);
            caret.set(text);
            return Optional.some(CaretPosition(text, 1));
          });
        };
        var evaluateUntil = function(fns, args) {
          for (var i2 = 0; i2 < fns.length; i2++) {
            var result = fns[i2].apply(null, args);
            if (result.isSome()) {
              return result;
            }
          }
          return Optional.none();
        };
        var Location = Adt.generate([
          { before: ["element"] },
          { start: ["element"] },
          { end: ["element"] },
          { after: ["element"] }
        ]);
        var rescope$1 = function(rootNode, node) {
          var parentBlock = getParentBlock$2(node, rootNode);
          return parentBlock ? parentBlock : rootNode;
        };
        var before = function(isInlineTarget2, rootNode, pos) {
          var nPos = normalizeForwards(pos);
          var scope = rescope$1(rootNode, nPos.container());
          return findRootInline(isInlineTarget2, scope, nPos).fold(function() {
            return nextPosition(scope, nPos).bind(curry(findRootInline, isInlineTarget2, scope)).map(function(inline) {
              return Location.before(inline);
            });
          }, Optional.none);
        };
        var isNotInsideFormatCaretContainer = function(rootNode, elm) {
          return getParentCaretContainer(rootNode, elm) === null;
        };
        var findInsideRootInline = function(isInlineTarget2, rootNode, pos) {
          return findRootInline(isInlineTarget2, rootNode, pos).filter(curry(isNotInsideFormatCaretContainer, rootNode));
        };
        var start$1 = function(isInlineTarget2, rootNode, pos) {
          var nPos = normalizeBackwards(pos);
          return findInsideRootInline(isInlineTarget2, rootNode, nPos).bind(function(inline) {
            var prevPos = prevPosition(inline, nPos);
            return prevPos.isNone() ? Optional.some(Location.start(inline)) : Optional.none();
          });
        };
        var end2 = function(isInlineTarget2, rootNode, pos) {
          var nPos = normalizeForwards(pos);
          return findInsideRootInline(isInlineTarget2, rootNode, nPos).bind(function(inline) {
            var nextPos = nextPosition(inline, nPos);
            return nextPos.isNone() ? Optional.some(Location.end(inline)) : Optional.none();
          });
        };
        var after = function(isInlineTarget2, rootNode, pos) {
          var nPos = normalizeBackwards(pos);
          var scope = rescope$1(rootNode, nPos.container());
          return findRootInline(isInlineTarget2, scope, nPos).fold(function() {
            return prevPosition(scope, nPos).bind(curry(findRootInline, isInlineTarget2, scope)).map(function(inline) {
              return Location.after(inline);
            });
          }, Optional.none);
        };
        var isValidLocation = function(location2) {
          return isRtl(getElement2(location2)) === false;
        };
        var readLocation = function(isInlineTarget2, rootNode, pos) {
          var location2 = evaluateUntil([
            before,
            start$1,
            end2,
            after
          ], [
            isInlineTarget2,
            rootNode,
            pos
          ]);
          return location2.filter(isValidLocation);
        };
        var getElement2 = function(location2) {
          return location2.fold(identity, identity, identity, identity);
        };
        var getName = function(location2) {
          return location2.fold(constant("before"), constant("start"), constant("end"), constant("after"));
        };
        var outside = function(location2) {
          return location2.fold(Location.before, Location.before, Location.after, Location.after);
        };
        var inside = function(location2) {
          return location2.fold(Location.start, Location.start, Location.end, Location.end);
        };
        var isEq = function(location1, location2) {
          return getName(location1) === getName(location2) && getElement2(location1) === getElement2(location2);
        };
        var betweenInlines = function(forward, isInlineTarget2, rootNode, from2, to2, location2) {
          return lift2(findRootInline(isInlineTarget2, rootNode, from2), findRootInline(isInlineTarget2, rootNode, to2), function(fromInline, toInline) {
            if (fromInline !== toInline && hasSameParentBlock(rootNode, fromInline, toInline)) {
              return Location.after(forward ? fromInline : toInline);
            } else {
              return location2;
            }
          }).getOr(location2);
        };
        var skipNoMovement = function(fromLocation, toLocation) {
          return fromLocation.fold(always, function(fromLocation2) {
            return !isEq(fromLocation2, toLocation);
          });
        };
        var findLocationTraverse = function(forward, isInlineTarget2, rootNode, fromLocation, pos) {
          var from2 = normalizePosition(forward, pos);
          var to2 = fromPosition(forward, rootNode, from2).map(curry(normalizePosition, forward));
          var location2 = to2.fold(function() {
            return fromLocation.map(outside);
          }, function(to3) {
            return readLocation(isInlineTarget2, rootNode, to3).map(curry(betweenInlines, forward, isInlineTarget2, rootNode, from2, to3)).filter(curry(skipNoMovement, fromLocation));
          });
          return location2.filter(isValidLocation);
        };
        var findLocationSimple = function(forward, location2) {
          if (forward) {
            return location2.fold(compose(Optional.some, Location.start), Optional.none, compose(Optional.some, Location.after), Optional.none);
          } else {
            return location2.fold(Optional.none, compose(Optional.some, Location.before), Optional.none, compose(Optional.some, Location.end));
          }
        };
        var findLocation$1 = function(forward, isInlineTarget2, rootNode, pos) {
          var from2 = normalizePosition(forward, pos);
          var fromLocation = readLocation(isInlineTarget2, rootNode, from2);
          return readLocation(isInlineTarget2, rootNode, from2).bind(curry(findLocationSimple, forward)).orThunk(function() {
            return findLocationTraverse(forward, isInlineTarget2, rootNode, fromLocation, pos);
          });
        };
        curry(findLocation$1, false);
        curry(findLocation$1, true);
        var hasSelectionModifyApi = function(editor) {
          return isFunction2(editor.selection.getSel().modify);
        };
        var moveRel = function(forward, selection, pos) {
          var delta = forward ? 1 : -1;
          selection.setRng(CaretPosition(pos.container(), pos.offset() + delta).toRange());
          selection.getSel().modify("move", forward ? "forward" : "backward", "word");
          return true;
        };
        var moveByWord = function(forward, editor) {
          var rng = editor.selection.getRng();
          var pos = forward ? CaretPosition.fromRangeEnd(rng) : CaretPosition.fromRangeStart(rng);
          if (!hasSelectionModifyApi(editor)) {
            return false;
          } else if (forward && isBeforeInline(pos)) {
            return moveRel(true, editor.selection, pos);
          } else if (!forward && isAfterInline(pos)) {
            return moveRel(false, editor.selection, pos);
          } else {
            return false;
          }
        };
        var BreakType;
        (function(BreakType2) {
          BreakType2[BreakType2["Br"] = 0] = "Br";
          BreakType2[BreakType2["Block"] = 1] = "Block";
          BreakType2[BreakType2["Wrap"] = 2] = "Wrap";
          BreakType2[BreakType2["Eol"] = 3] = "Eol";
        })(BreakType || (BreakType = {}));
        var flip2 = function(direction, positions2) {
          return direction === HDirection.Backwards ? reverse(positions2) : positions2;
        };
        var walk2 = function(direction, caretWalker, pos) {
          return direction === HDirection.Forwards ? caretWalker.next(pos) : caretWalker.prev(pos);
        };
        var getBreakType = function(scope, direction, currentPos, nextPos) {
          if (isBr$5(nextPos.getNode(direction === HDirection.Forwards))) {
            return BreakType.Br;
          } else if (isInSameBlock(currentPos, nextPos) === false) {
            return BreakType.Block;
          } else {
            return BreakType.Wrap;
          }
        };
        var getPositionsUntil = function(predicate, direction, scope, start5) {
          var caretWalker = CaretWalker(scope);
          var currentPos = start5;
          var positions2 = [];
          while (currentPos) {
            var nextPos = walk2(direction, caretWalker, currentPos);
            if (!nextPos) {
              break;
            }
            if (isBr$5(nextPos.getNode(false))) {
              if (direction === HDirection.Forwards) {
                return {
                  positions: flip2(direction, positions2).concat([nextPos]),
                  breakType: BreakType.Br,
                  breakAt: Optional.some(nextPos)
                };
              } else {
                return {
                  positions: flip2(direction, positions2),
                  breakType: BreakType.Br,
                  breakAt: Optional.some(nextPos)
                };
              }
            }
            if (!nextPos.isVisible()) {
              currentPos = nextPos;
              continue;
            }
            if (predicate(currentPos, nextPos)) {
              var breakType = getBreakType(scope, direction, currentPos, nextPos);
              return {
                positions: flip2(direction, positions2),
                breakType,
                breakAt: Optional.some(nextPos)
              };
            }
            positions2.push(nextPos);
            currentPos = nextPos;
          }
          return {
            positions: flip2(direction, positions2),
            breakType: BreakType.Eol,
            breakAt: Optional.none()
          };
        };
        var getAdjacentLinePositions = function(direction, getPositionsUntilBreak, scope, start5) {
          return getPositionsUntilBreak(scope, start5).breakAt.map(function(pos) {
            var positions2 = getPositionsUntilBreak(scope, pos).positions;
            return direction === HDirection.Backwards ? positions2.concat(pos) : [pos].concat(positions2);
          }).getOr([]);
        };
        var findClosestHorizontalPositionFromPoint = function(positions2, x2) {
          return foldl(positions2, function(acc, newPos) {
            return acc.fold(function() {
              return Optional.some(newPos);
            }, function(lastPos) {
              return lift2(head(lastPos.getClientRects()), head(newPos.getClientRects()), function(lastRect, newRect) {
                var lastDist = Math.abs(x2 - lastRect.left);
                var newDist = Math.abs(x2 - newRect.left);
                return newDist <= lastDist ? newPos : lastPos;
              }).or(acc);
            });
          }, Optional.none());
        };
        var findClosestHorizontalPosition = function(positions2, pos) {
          return head(pos.getClientRects()).bind(function(targetRect) {
            return findClosestHorizontalPositionFromPoint(positions2, targetRect.left);
          });
        };
        var getPositionsUntilPreviousLine = curry(getPositionsUntil, CaretPosition.isAbove, -1);
        var getPositionsUntilNextLine = curry(getPositionsUntil, CaretPosition.isBelow, 1);
        var getPositionsAbove = curry(getAdjacentLinePositions, -1, getPositionsUntilPreviousLine);
        var getPositionsBelow = curry(getAdjacentLinePositions, 1, getPositionsUntilNextLine);
        var isAtFirstLine = function(scope, pos) {
          return getPositionsUntilPreviousLine(scope, pos).breakAt.isNone();
        };
        var isAtLastLine = function(scope, pos) {
          return getPositionsUntilNextLine(scope, pos).breakAt.isNone();
        };
        var getFirstLinePositions = function(scope) {
          return firstPositionIn(scope).map(function(pos) {
            return [pos].concat(getPositionsUntilNextLine(scope, pos).positions);
          }).getOr([]);
        };
        var getLastLinePositions = function(scope) {
          return lastPositionIn(scope).map(function(pos) {
            return getPositionsUntilPreviousLine(scope, pos).positions.concat(pos);
          }).getOr([]);
        };
        var getNodeClientRects = function(node) {
          var toArrayWithNode = function(clientRects) {
            return map$3(clientRects, function(rect) {
              var clientRect = clone2(rect);
              clientRect.node = node;
              return clientRect;
            });
          };
          if (isElement$5(node)) {
            return toArrayWithNode(node.getClientRects());
          }
          if (isText$7(node)) {
            var rng = node.ownerDocument.createRange();
            rng.setStart(node, 0);
            rng.setEnd(node, node.data.length);
            return toArrayWithNode(rng.getClientRects());
          }
        };
        var getClientRects = function(nodes) {
          return bind(nodes, getNodeClientRects);
        };
        var VDirection;
        (function(VDirection2) {
          VDirection2[VDirection2["Up"] = -1] = "Up";
          VDirection2[VDirection2["Down"] = 1] = "Down";
        })(VDirection || (VDirection = {}));
        var findUntil = function(direction, root, predicateFn, node) {
          while (node = findNode$1(node, direction, isEditableCaretCandidate$1, root)) {
            if (predicateFn(node)) {
              return;
            }
          }
        };
        var walkUntil$1 = function(direction, isAboveFn, isBeflowFn, root, predicateFn, caretPosition) {
          var line = 0;
          var result = [];
          var add4 = function(node2) {
            var clientRects = getClientRects([node2]);
            if (direction === -1) {
              clientRects = clientRects.reverse();
            }
            for (var i2 = 0; i2 < clientRects.length; i2++) {
              var clientRect = clientRects[i2];
              if (isBeflowFn(clientRect, targetClientRect)) {
                continue;
              }
              if (result.length > 0 && isAboveFn(clientRect, last$1(result))) {
                line++;
              }
              clientRect.line = line;
              if (predicateFn(clientRect)) {
                return true;
              }
              result.push(clientRect);
            }
          };
          var targetClientRect = last$1(caretPosition.getClientRects());
          if (!targetClientRect) {
            return result;
          }
          var node = caretPosition.getNode();
          add4(node);
          findUntil(direction, root, add4, node);
          return result;
        };
        var aboveLineNumber = function(lineNumber, clientRect) {
          return clientRect.line > lineNumber;
        };
        var isLineNumber = function(lineNumber, clientRect) {
          return clientRect.line === lineNumber;
        };
        var upUntil = curry(walkUntil$1, VDirection.Up, isAbove$1, isBelow$1);
        var downUntil = curry(walkUntil$1, VDirection.Down, isBelow$1, isAbove$1);
        var positionsUntil = function(direction, root, predicateFn, node) {
          var caretWalker = CaretWalker(root);
          var walkFn;
          var isBelowFn;
          var isAboveFn;
          var caretPosition;
          var result = [];
          var line = 0;
          var getClientRect = function(caretPosition2) {
            if (direction === 1) {
              return last$1(caretPosition2.getClientRects());
            }
            return last$1(caretPosition2.getClientRects());
          };
          if (direction === 1) {
            walkFn = caretWalker.next;
            isBelowFn = isBelow$1;
            isAboveFn = isAbove$1;
            caretPosition = CaretPosition.after(node);
          } else {
            walkFn = caretWalker.prev;
            isBelowFn = isAbove$1;
            isAboveFn = isBelow$1;
            caretPosition = CaretPosition.before(node);
          }
          var targetClientRect = getClientRect(caretPosition);
          do {
            if (!caretPosition.isVisible()) {
              continue;
            }
            var rect = getClientRect(caretPosition);
            if (isAboveFn(rect, targetClientRect)) {
              continue;
            }
            if (result.length > 0 && isBelowFn(rect, last$1(result))) {
              line++;
            }
            var clientRect = clone2(rect);
            clientRect.position = caretPosition;
            clientRect.line = line;
            if (predicateFn(clientRect)) {
              return result;
            }
            result.push(clientRect);
          } while (caretPosition = walkFn(caretPosition));
          return result;
        };
        var isAboveLine = function(lineNumber) {
          return function(clientRect) {
            return aboveLineNumber(lineNumber, clientRect);
          };
        };
        var isLine = function(lineNumber) {
          return function(clientRect) {
            return isLineNumber(lineNumber, clientRect);
          };
        };
        var isContentEditableFalse$3 = isContentEditableFalse$b;
        var findNode = findNode$1;
        var distanceToRectLeft = function(clientRect, clientX) {
          return Math.abs(clientRect.left - clientX);
        };
        var distanceToRectRight = function(clientRect, clientX) {
          return Math.abs(clientRect.right - clientX);
        };
        var isInsideX = function(clientX, clientRect) {
          return clientX >= clientRect.left && clientX <= clientRect.right;
        };
        var isInsideY = function(clientY, clientRect) {
          return clientY >= clientRect.top && clientY <= clientRect.bottom;
        };
        var isNodeClientRect = function(rect) {
          return hasNonNullableKey(rect, "node");
        };
        var findClosestClientRect = function(clientRects, clientX, allowInside) {
          if (allowInside === void 0) {
            allowInside = always;
          }
          return reduce(clientRects, function(oldClientRect, clientRect) {
            if (isInsideX(clientX, clientRect)) {
              return allowInside(clientRect) ? clientRect : oldClientRect;
            }
            if (isInsideX(clientX, oldClientRect)) {
              return allowInside(oldClientRect) ? oldClientRect : clientRect;
            }
            var oldDistance = Math.min(distanceToRectLeft(oldClientRect, clientX), distanceToRectRight(oldClientRect, clientX));
            var newDistance = Math.min(distanceToRectLeft(clientRect, clientX), distanceToRectRight(clientRect, clientX));
            if (newDistance === oldDistance && isNodeClientRect(clientRect) && isContentEditableFalse$3(clientRect.node)) {
              return clientRect;
            }
            if (newDistance < oldDistance) {
              return clientRect;
            }
            return oldClientRect;
          });
        };
        var walkUntil = function(direction, root, predicateFn, startNode, includeChildren) {
          var node = findNode(startNode, direction, isEditableCaretCandidate$1, root, !includeChildren);
          do {
            if (!node || predicateFn(node)) {
              return;
            }
          } while (node = findNode(node, direction, isEditableCaretCandidate$1, root));
        };
        var findLineNodeRects = function(root, targetNodeRect, includeChildren) {
          if (includeChildren === void 0) {
            includeChildren = true;
          }
          var clientRects = [];
          var collect = function(checkPosFn, node) {
            var lineRects = filter$4(getClientRects([node]), function(clientRect) {
              return !checkPosFn(clientRect, targetNodeRect);
            });
            clientRects = clientRects.concat(lineRects);
            return lineRects.length === 0;
          };
          clientRects.push(targetNodeRect);
          walkUntil(VDirection.Up, root, curry(collect, isAbove$1), targetNodeRect.node, includeChildren);
          walkUntil(VDirection.Down, root, curry(collect, isBelow$1), targetNodeRect.node, includeChildren);
          return clientRects;
        };
        var getFakeCaretTargets = function(root) {
          return filter$4(from(root.getElementsByTagName("*")), isFakeCaretTarget);
        };
        var caretInfo = function(clientRect, clientX) {
          return {
            node: clientRect.node,
            before: distanceToRectLeft(clientRect, clientX) < distanceToRectRight(clientRect, clientX)
          };
        };
        var closestFakeCaret = function(root, clientX, clientY) {
          var fakeTargetNodeRects = getClientRects(getFakeCaretTargets(root));
          var targetNodeRects = filter$4(fakeTargetNodeRects, curry(isInsideY, clientY));
          var checkInside = function(clientRect) {
            return !isTable$3(clientRect.node) && !isMedia$2(clientRect.node);
          };
          var closestNodeRect = findClosestClientRect(targetNodeRects, clientX, checkInside);
          if (closestNodeRect) {
            var includeChildren = checkInside(closestNodeRect);
            closestNodeRect = findClosestClientRect(findLineNodeRects(root, closestNodeRect, includeChildren), clientX, checkInside);
            if (closestNodeRect && isFakeCaretTarget(closestNodeRect.node)) {
              return caretInfo(closestNodeRect, clientX);
            }
          }
          return null;
        };
        var moveToRange = function(editor, rng) {
          editor.selection.setRng(rng);
          scrollRangeIntoView(editor, editor.selection.getRng());
        };
        var renderRangeCaretOpt = function(editor, range2, scrollIntoView) {
          return Optional.some(renderRangeCaret(editor, range2, scrollIntoView));
        };
        var moveHorizontally = function(editor, direction, range2, isBefore, isAfter, isElement4) {
          var forwards = direction === HDirection.Forwards;
          var caretWalker = CaretWalker(editor.getBody());
          var getNextPosFn = curry(getVisualCaretPosition, forwards ? caretWalker.next : caretWalker.prev);
          var isBeforeFn = forwards ? isBefore : isAfter;
          if (!range2.collapsed) {
            var node = getSelectedNode(range2);
            if (isElement4(node)) {
              return showCaret(direction, editor, node, direction === HDirection.Backwards, false);
            }
          }
          var caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range2);
          if (isBeforeFn(caretPosition)) {
            return selectNode(editor, caretPosition.getNode(!forwards));
          }
          var nextCaretPosition = normalizePosition(forwards, getNextPosFn(caretPosition));
          var rangeIsInContainerBlock = isRangeInCaretContainerBlock(range2);
          if (!nextCaretPosition) {
            return rangeIsInContainerBlock ? Optional.some(range2) : Optional.none();
          }
          if (isBeforeFn(nextCaretPosition)) {
            return showCaret(direction, editor, nextCaretPosition.getNode(!forwards), forwards, false);
          }
          var peekCaretPosition = getNextPosFn(nextCaretPosition);
          if (peekCaretPosition && isBeforeFn(peekCaretPosition)) {
            if (isMoveInsideSameBlock(nextCaretPosition, peekCaretPosition)) {
              return showCaret(direction, editor, peekCaretPosition.getNode(!forwards), forwards, false);
            }
          }
          if (rangeIsInContainerBlock) {
            return renderRangeCaretOpt(editor, nextCaretPosition.toRange(), false);
          }
          return Optional.none();
        };
        var moveVertically = function(editor, direction, range2, isBefore, isAfter, isElement4) {
          var caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range2);
          var caretClientRect = last$1(caretPosition.getClientRects());
          var forwards = direction === VDirection.Down;
          if (!caretClientRect) {
            return Optional.none();
          }
          var walkerFn = forwards ? downUntil : upUntil;
          var linePositions = walkerFn(editor.getBody(), isAboveLine(1), caretPosition);
          var nextLinePositions = filter$4(linePositions, isLine(1));
          var clientX = caretClientRect.left;
          var nextLineRect = findClosestClientRect(nextLinePositions, clientX);
          if (nextLineRect && isElement4(nextLineRect.node)) {
            var dist1 = Math.abs(clientX - nextLineRect.left);
            var dist2 = Math.abs(clientX - nextLineRect.right);
            return showCaret(direction, editor, nextLineRect.node, dist1 < dist2, false);
          }
          var currentNode;
          if (isBefore(caretPosition)) {
            currentNode = caretPosition.getNode();
          } else if (isAfter(caretPosition)) {
            currentNode = caretPosition.getNode(true);
          } else {
            currentNode = getSelectedNode(range2);
          }
          if (currentNode) {
            var caretPositions = positionsUntil(direction, editor.getBody(), isAboveLine(1), currentNode);
            var closestNextLineRect = findClosestClientRect(filter$4(caretPositions, isLine(1)), clientX);
            if (closestNextLineRect) {
              return renderRangeCaretOpt(editor, closestNextLineRect.position.toRange(), false);
            }
            closestNextLineRect = last$1(filter$4(caretPositions, isLine(0)));
            if (closestNextLineRect) {
              return renderRangeCaretOpt(editor, closestNextLineRect.position.toRange(), false);
            }
          }
          if (nextLinePositions.length === 0) {
            return getLineEndPoint(editor, forwards).filter(forwards ? isAfter : isBefore).map(function(pos) {
              return renderRangeCaret(editor, pos.toRange(), false);
            });
          }
          return Optional.none();
        };
        var getLineEndPoint = function(editor, forward) {
          var rng = editor.selection.getRng();
          var body = editor.getBody();
          if (forward) {
            var from2 = CaretPosition.fromRangeEnd(rng);
            var result = getPositionsUntilNextLine(body, from2);
            return last$2(result.positions);
          } else {
            var from2 = CaretPosition.fromRangeStart(rng);
            var result = getPositionsUntilPreviousLine(body, from2);
            return head(result.positions);
          }
        };
        var moveToLineEndPoint$3 = function(editor, forward, isElementPosition) {
          return getLineEndPoint(editor, forward).filter(isElementPosition).exists(function(pos) {
            editor.selection.setRng(pos.toRange());
            return true;
          });
        };
        var setCaretPosition = function(editor, pos) {
          var rng = editor.dom.createRng();
          rng.setStart(pos.container(), pos.offset());
          rng.setEnd(pos.container(), pos.offset());
          editor.selection.setRng(rng);
        };
        var setSelected = function(state, elm) {
          if (state) {
            elm.setAttribute("data-mce-selected", "inline-boundary");
          } else {
            elm.removeAttribute("data-mce-selected");
          }
        };
        var renderCaretLocation = function(editor, caret, location2) {
          return renderCaret(caret, location2).map(function(pos) {
            setCaretPosition(editor, pos);
            return location2;
          });
        };
        var findLocation = function(editor, caret, forward) {
          var rootNode = editor.getBody();
          var from2 = CaretPosition.fromRangeStart(editor.selection.getRng());
          var isInlineTarget$1 = curry(isInlineTarget, editor);
          var location2 = findLocation$1(forward, isInlineTarget$1, rootNode, from2);
          return location2.bind(function(location3) {
            return renderCaretLocation(editor, caret, location3);
          });
        };
        var toggleInlines = function(isInlineTarget2, dom2, elms) {
          var inlineBoundaries = map$3(descendants(SugarElement.fromDom(dom2.getRoot()), '*[data-mce-selected="inline-boundary"]'), function(e2) {
            return e2.dom;
          });
          var selectedInlines = filter$4(inlineBoundaries, isInlineTarget2);
          var targetInlines = filter$4(elms, isInlineTarget2);
          each$k(difference(selectedInlines, targetInlines), curry(setSelected, false));
          each$k(difference(targetInlines, selectedInlines), curry(setSelected, true));
        };
        var safeRemoveCaretContainer = function(editor, caret) {
          if (editor.selection.isCollapsed() && editor.composing !== true && caret.get()) {
            var pos = CaretPosition.fromRangeStart(editor.selection.getRng());
            if (CaretPosition.isTextPosition(pos) && isAtZwsp(pos) === false) {
              setCaretPosition(editor, removeAndReposition(caret.get(), pos));
              caret.set(null);
            }
          }
        };
        var renderInsideInlineCaret = function(isInlineTarget2, editor, caret, elms) {
          if (editor.selection.isCollapsed()) {
            var inlines = filter$4(elms, isInlineTarget2);
            each$k(inlines, function(_inline) {
              var pos = CaretPosition.fromRangeStart(editor.selection.getRng());
              readLocation(isInlineTarget2, editor.getBody(), pos).bind(function(location2) {
                return renderCaretLocation(editor, caret, location2);
              });
            });
          }
        };
        var move$2 = function(editor, caret, forward) {
          return isInlineBoundariesEnabled(editor) ? findLocation(editor, caret, forward).isSome() : false;
        };
        var moveWord = function(forward, editor, _caret) {
          return isInlineBoundariesEnabled(editor) ? moveByWord(forward, editor) : false;
        };
        var setupSelectedState = function(editor) {
          var caret = Cell(null);
          var isInlineTarget$1 = curry(isInlineTarget, editor);
          editor.on("NodeChange", function(e2) {
            if (isInlineBoundariesEnabled(editor) && !(Env.browser.isIE() && e2.initial)) {
              toggleInlines(isInlineTarget$1, editor.dom, e2.parents);
              safeRemoveCaretContainer(editor, caret);
              renderInsideInlineCaret(isInlineTarget$1, editor, caret, e2.parents);
            }
          });
          return caret;
        };
        var moveNextWord = curry(moveWord, true);
        var movePrevWord = curry(moveWord, false);
        var moveToLineEndPoint$2 = function(editor, forward, caret) {
          if (isInlineBoundariesEnabled(editor)) {
            var linePoint = getLineEndPoint(editor, forward).getOrThunk(function() {
              var rng = editor.selection.getRng();
              return forward ? CaretPosition.fromRangeEnd(rng) : CaretPosition.fromRangeStart(rng);
            });
            return readLocation(curry(isInlineTarget, editor), editor.getBody(), linePoint).exists(function(loc) {
              var outsideLoc = outside(loc);
              return renderCaret(caret, outsideLoc).exists(function(pos) {
                setCaretPosition(editor, pos);
                return true;
              });
            });
          } else {
            return false;
          }
        };
        var rangeFromPositions = function(from2, to2) {
          var range2 = document.createRange();
          range2.setStart(from2.container(), from2.offset());
          range2.setEnd(to2.container(), to2.offset());
          return range2;
        };
        var hasOnlyTwoOrLessPositionsLeft = function(elm) {
          return lift2(firstPositionIn(elm), lastPositionIn(elm), function(firstPos, lastPos) {
            var normalizedFirstPos = normalizePosition(true, firstPos);
            var normalizedLastPos = normalizePosition(false, lastPos);
            return nextPosition(elm, normalizedFirstPos).forall(function(pos) {
              return pos.isEqual(normalizedLastPos);
            });
          }).getOr(true);
        };
        var setCaretLocation = function(editor, caret) {
          return function(location2) {
            return renderCaret(caret, location2).exists(function(pos) {
              setCaretPosition(editor, pos);
              return true;
            });
          };
        };
        var deleteFromTo = function(editor, caret, from2, to2) {
          var rootNode = editor.getBody();
          var isInlineTarget$1 = curry(isInlineTarget, editor);
          editor.undoManager.ignore(function() {
            editor.selection.setRng(rangeFromPositions(from2, to2));
            editor.execCommand("Delete");
            readLocation(isInlineTarget$1, rootNode, CaretPosition.fromRangeStart(editor.selection.getRng())).map(inside).map(setCaretLocation(editor, caret));
          });
          editor.nodeChanged();
        };
        var rescope = function(rootNode, node) {
          var parentBlock = getParentBlock$2(node, rootNode);
          return parentBlock ? parentBlock : rootNode;
        };
        var backspaceDeleteCollapsed = function(editor, caret, forward, from2) {
          var rootNode = rescope(editor.getBody(), from2.container());
          var isInlineTarget$1 = curry(isInlineTarget, editor);
          var fromLocation = readLocation(isInlineTarget$1, rootNode, from2);
          return fromLocation.bind(function(location2) {
            if (forward) {
              return location2.fold(constant(Optional.some(inside(location2))), Optional.none, constant(Optional.some(outside(location2))), Optional.none);
            } else {
              return location2.fold(Optional.none, constant(Optional.some(outside(location2))), Optional.none, constant(Optional.some(inside(location2))));
            }
          }).map(setCaretLocation(editor, caret)).getOrThunk(function() {
            var toPosition = navigate(forward, rootNode, from2);
            var toLocation = toPosition.bind(function(pos) {
              return readLocation(isInlineTarget$1, rootNode, pos);
            });
            return lift2(fromLocation, toLocation, function() {
              return findRootInline(isInlineTarget$1, rootNode, from2).exists(function(elm) {
                if (hasOnlyTwoOrLessPositionsLeft(elm)) {
                  deleteElement$2(editor, forward, SugarElement.fromDom(elm));
                  return true;
                } else {
                  return false;
                }
              });
            }).orThunk(function() {
              return toLocation.bind(function(_2) {
                return toPosition.map(function(to2) {
                  if (forward) {
                    deleteFromTo(editor, caret, from2, to2);
                  } else {
                    deleteFromTo(editor, caret, to2, from2);
                  }
                  return true;
                });
              });
            }).getOr(false);
          });
        };
        var backspaceDelete$3 = function(editor, caret, forward) {
          if (editor.selection.isCollapsed() && isInlineBoundariesEnabled(editor)) {
            var from2 = CaretPosition.fromRangeStart(editor.selection.getRng());
            return backspaceDeleteCollapsed(editor, caret, forward, from2);
          }
          return false;
        };
        var getParentInlines = function(rootElm, startElm) {
          var parents2 = parentsAndSelf(startElm, rootElm);
          return findIndex$2(parents2, isBlock$2).fold(constant(parents2), function(index) {
            return parents2.slice(0, index);
          });
        };
        var hasOnlyOneChild = function(elm) {
          return childNodesCount(elm) === 1;
        };
        var deleteLastPosition = function(forward, editor, target, parentInlines) {
          var isFormatElement$1 = curry(isFormatElement, editor);
          var formatNodes = map$3(filter$4(parentInlines, isFormatElement$1), function(elm) {
            return elm.dom;
          });
          if (formatNodes.length === 0) {
            deleteElement$2(editor, forward, target);
          } else {
            var pos = replaceWithCaretFormat(target.dom, formatNodes);
            editor.selection.setRng(pos.toRange());
          }
        };
        var deleteCaret$1 = function(editor, forward) {
          var rootElm = SugarElement.fromDom(editor.getBody());
          var startElm = SugarElement.fromDom(editor.selection.getStart());
          var parentInlines = filter$4(getParentInlines(rootElm, startElm), hasOnlyOneChild);
          return last$2(parentInlines).exists(function(target) {
            var fromPos = CaretPosition.fromRangeStart(editor.selection.getRng());
            if (willDeleteLastPositionInElement(forward, fromPos, target.dom) && !isEmptyCaretFormatElement(target)) {
              deleteLastPosition(forward, editor, target, parentInlines);
              return true;
            } else {
              return false;
            }
          });
        };
        var backspaceDelete$2 = function(editor, forward) {
          return editor.selection.isCollapsed() ? deleteCaret$1(editor, forward) : false;
        };
        var deleteElement = function(editor, forward, element) {
          editor._selectionOverrides.hideFakeCaret();
          deleteElement$2(editor, forward, SugarElement.fromDom(element));
          return true;
        };
        var deleteCaret = function(editor, forward) {
          var isNearMedia = forward ? isBeforeMedia : isAfterMedia;
          var direction = forward ? HDirection.Forwards : HDirection.Backwards;
          var fromPos = getNormalizedRangeEndPoint(direction, editor.getBody(), editor.selection.getRng());
          if (isNearMedia(fromPos)) {
            return deleteElement(editor, forward, fromPos.getNode(!forward));
          } else {
            return Optional.from(normalizePosition(forward, fromPos)).filter(function(pos) {
              return isNearMedia(pos) && isMoveInsideSameBlock(fromPos, pos);
            }).exists(function(pos) {
              return deleteElement(editor, forward, pos.getNode(!forward));
            });
          }
        };
        var deleteRange = function(editor, forward) {
          var selectedNode = editor.selection.getNode();
          return isMedia$2(selectedNode) ? deleteElement(editor, forward, selectedNode) : false;
        };
        var backspaceDelete$1 = function(editor, forward) {
          return editor.selection.isCollapsed() ? deleteCaret(editor, forward) : deleteRange(editor, forward);
        };
        var isEditable = function(target) {
          return closest$3(target, function(elm) {
            return isContentEditableTrue$4(elm.dom) || isContentEditableFalse$b(elm.dom);
          }).exists(function(elm) {
            return isContentEditableTrue$4(elm.dom);
          });
        };
        var parseIndentValue = function(value2) {
          var number = parseInt(value2, 10);
          return isNaN(number) ? 0 : number;
        };
        var getIndentStyleName = function(useMargin, element) {
          var indentStyleName = useMargin || isTable$2(element) ? "margin" : "padding";
          var suffix = get$5(element, "direction") === "rtl" ? "-right" : "-left";
          return indentStyleName + suffix;
        };
        var indentElement = function(dom2, command, useMargin, value2, unit, element) {
          var indentStyleName = getIndentStyleName(useMargin, SugarElement.fromDom(element));
          if (command === "outdent") {
            var styleValue = Math.max(0, parseIndentValue(element.style[indentStyleName]) - value2);
            dom2.setStyle(element, indentStyleName, styleValue ? styleValue + unit : "");
          } else {
            var styleValue = parseIndentValue(element.style[indentStyleName]) + value2 + unit;
            dom2.setStyle(element, indentStyleName, styleValue);
          }
        };
        var validateBlocks = function(editor, blocks2) {
          return forall(blocks2, function(block) {
            var indentStyleName = getIndentStyleName(shouldIndentUseMargin(editor), block);
            var intentValue = getRaw(block, indentStyleName).map(parseIndentValue).getOr(0);
            var contentEditable = editor.dom.getContentEditable(block.dom);
            return contentEditable !== "false" && intentValue > 0;
          });
        };
        var canOutdent = function(editor) {
          var blocks2 = getBlocksToIndent(editor);
          return !editor.mode.isReadOnly() && (blocks2.length > 1 || validateBlocks(editor, blocks2));
        };
        var isListComponent = function(el) {
          return isList(el) || isListItem(el);
        };
        var parentIsListComponent = function(el) {
          return parent(el).exists(isListComponent);
        };
        var getBlocksToIndent = function(editor) {
          return filter$4(fromDom$1(editor.selection.getSelectedBlocks()), function(el) {
            return !isListComponent(el) && !parentIsListComponent(el) && isEditable(el);
          });
        };
        var handle = function(editor, command) {
          var dom2 = editor.dom, selection = editor.selection, formatter = editor.formatter;
          var indentation = getIndentation(editor);
          var indentUnit = /[a-z%]+$/i.exec(indentation)[0];
          var indentValue = parseInt(indentation, 10);
          var useMargin = shouldIndentUseMargin(editor);
          var forcedRootBlock = getForcedRootBlock(editor);
          if (!editor.queryCommandState("InsertUnorderedList") && !editor.queryCommandState("InsertOrderedList")) {
            if (forcedRootBlock === "" && !dom2.getParent(selection.getNode(), dom2.isBlock)) {
              formatter.apply("div");
            }
          }
          each$k(getBlocksToIndent(editor), function(block) {
            indentElement(dom2, command, useMargin, indentValue, indentUnit, block.dom);
          });
        };
        var backspaceDelete = function(editor, _forward) {
          if (editor.selection.isCollapsed() && canOutdent(editor)) {
            var dom2 = editor.dom;
            var rng = editor.selection.getRng();
            var pos = CaretPosition.fromRangeStart(rng);
            var block = dom2.getParent(rng.startContainer, dom2.isBlock);
            if (block !== null && isAtStartOfBlock(SugarElement.fromDom(block), pos)) {
              handle(editor, "outdent");
              return true;
            }
          }
          return false;
        };
        var nativeCommand = function(editor, command) {
          editor.getDoc().execCommand(command, false, null);
        };
        var deleteCommand = function(editor, caret) {
          if (backspaceDelete(editor)) {
            return;
          } else if (backspaceDelete$5(editor, false)) {
            return;
          } else if (backspaceDelete$6(editor, false)) {
            return;
          } else if (backspaceDelete$3(editor, caret, false)) {
            return;
          } else if (backspaceDelete$8(editor, false)) {
            return;
          } else if (backspaceDelete$9(editor)) {
            return;
          } else if (backspaceDelete$4(editor, false)) {
            return;
          } else if (backspaceDelete$1(editor, false)) {
            return;
          } else if (backspaceDelete$7(editor)) {
            return;
          } else if (backspaceDelete$2(editor, false)) {
            return;
          } else {
            nativeCommand(editor, "Delete");
            paddEmptyBody(editor);
          }
        };
        var forwardDeleteCommand = function(editor, caret) {
          if (backspaceDelete$5(editor, true)) {
            return;
          } else if (backspaceDelete$6(editor, true)) {
            return;
          } else if (backspaceDelete$3(editor, caret, true)) {
            return;
          } else if (backspaceDelete$8(editor, true)) {
            return;
          } else if (backspaceDelete$9(editor)) {
            return;
          } else if (backspaceDelete$4(editor, true)) {
            return;
          } else if (backspaceDelete$1(editor, true)) {
            return;
          } else if (backspaceDelete$7(editor)) {
            return;
          } else if (backspaceDelete$2(editor, true)) {
            return;
          } else {
            nativeCommand(editor, "ForwardDelete");
          }
        };
        var setup$f = function(editor, caret) {
          editor.addCommand("delete", function() {
            deleteCommand(editor, caret);
          });
          editor.addCommand("forwardDelete", function() {
            forwardDeleteCommand(editor, caret);
          });
        };
        var SIGNIFICANT_MOVE = 5;
        var LONGPRESS_DELAY = 400;
        var getTouch = function(event) {
          if (event.touches === void 0 || event.touches.length !== 1) {
            return Optional.none();
          }
          return Optional.some(event.touches[0]);
        };
        var isFarEnough = function(touch, data2) {
          var distX = Math.abs(touch.clientX - data2.x);
          var distY = Math.abs(touch.clientY - data2.y);
          return distX > SIGNIFICANT_MOVE || distY > SIGNIFICANT_MOVE;
        };
        var setup$e = function(editor) {
          var startData = value();
          var longpressFired = Cell(false);
          var debounceLongpress = last(function(e2) {
            editor.fire("longpress", __assign(__assign({}, e2), { type: "longpress" }));
            longpressFired.set(true);
          }, LONGPRESS_DELAY);
          editor.on("touchstart", function(e2) {
            getTouch(e2).each(function(touch) {
              debounceLongpress.cancel();
              var data2 = {
                x: touch.clientX,
                y: touch.clientY,
                target: e2.target
              };
              debounceLongpress.throttle(e2);
              longpressFired.set(false);
              startData.set(data2);
            });
          }, true);
          editor.on("touchmove", function(e2) {
            debounceLongpress.cancel();
            getTouch(e2).each(function(touch) {
              startData.on(function(data2) {
                if (isFarEnough(touch, data2)) {
                  startData.clear();
                  longpressFired.set(false);
                  editor.fire("longpresscancel");
                }
              });
            });
          }, true);
          editor.on("touchend touchcancel", function(e2) {
            debounceLongpress.cancel();
            if (e2.type === "touchcancel") {
              return;
            }
            startData.get().filter(function(data2) {
              return data2.target.isEqualNode(e2.target);
            }).each(function() {
              if (longpressFired.get()) {
                e2.preventDefault();
              } else {
                editor.fire("tap", __assign(__assign({}, e2), { type: "tap" }));
              }
            });
          }, true);
        };
        var isBlockElement = function(blockElements, node) {
          return has$2(blockElements, node.nodeName);
        };
        var isValidTarget = function(blockElements, node) {
          if (isText$7(node)) {
            return true;
          } else if (isElement$5(node)) {
            return !isBlockElement(blockElements, node) && !isBookmarkNode$1(node);
          } else {
            return false;
          }
        };
        var hasBlockParent = function(blockElements, root, node) {
          return exists(parents(SugarElement.fromDom(node), SugarElement.fromDom(root)), function(elm) {
            return isBlockElement(blockElements, elm.dom);
          });
        };
        var shouldRemoveTextNode = function(blockElements, node) {
          if (isText$7(node)) {
            if (node.nodeValue.length === 0) {
              return true;
            } else if (/^\s+$/.test(node.nodeValue) && (!node.nextSibling || isBlockElement(blockElements, node.nextSibling))) {
              return true;
            }
          }
          return false;
        };
        var addRootBlocks = function(editor) {
          var dom2 = editor.dom, selection = editor.selection;
          var schema = editor.schema, blockElements = schema.getBlockElements();
          var node = selection.getStart();
          var rootNode = editor.getBody();
          var rootBlockNode, tempNode, wrapped;
          var forcedRootBlock = getForcedRootBlock(editor);
          if (!node || !isElement$5(node) || !forcedRootBlock) {
            return;
          }
          var rootNodeName = rootNode.nodeName.toLowerCase();
          if (!schema.isValidChild(rootNodeName, forcedRootBlock.toLowerCase()) || hasBlockParent(blockElements, rootNode, node)) {
            return;
          }
          var rng = selection.getRng();
          var startContainer = rng.startContainer;
          var startOffset = rng.startOffset;
          var endContainer = rng.endContainer;
          var endOffset = rng.endOffset;
          var restoreSelection = hasFocus(editor);
          node = rootNode.firstChild;
          while (node) {
            if (isValidTarget(blockElements, node)) {
              if (shouldRemoveTextNode(blockElements, node)) {
                tempNode = node;
                node = node.nextSibling;
                dom2.remove(tempNode);
                continue;
              }
              if (!rootBlockNode) {
                rootBlockNode = dom2.create(forcedRootBlock, getForcedRootBlockAttrs(editor));
                node.parentNode.insertBefore(rootBlockNode, node);
                wrapped = true;
              }
              tempNode = node;
              node = node.nextSibling;
              rootBlockNode.appendChild(tempNode);
            } else {
              rootBlockNode = null;
              node = node.nextSibling;
            }
          }
          if (wrapped && restoreSelection) {
            rng.setStart(startContainer, startOffset);
            rng.setEnd(endContainer, endOffset);
            selection.setRng(rng);
            editor.nodeChanged();
          }
        };
        var setup$d = function(editor) {
          if (getForcedRootBlock(editor)) {
            editor.on("NodeChange", curry(addRootBlocks, editor));
          }
        };
        var findBlockCaretContainer = function(editor) {
          return descendant(SugarElement.fromDom(editor.getBody()), "*[data-mce-caret]").map(function(elm) {
            return elm.dom;
          }).getOrNull();
        };
        var removeIeControlRect = function(editor) {
          editor.selection.setRng(editor.selection.getRng());
        };
        var showBlockCaretContainer = function(editor, blockCaretContainer) {
          if (blockCaretContainer.hasAttribute("data-mce-caret")) {
            showCaretContainerBlock(blockCaretContainer);
            removeIeControlRect(editor);
            editor.selection.scrollIntoView(blockCaretContainer);
          }
        };
        var handleBlockContainer = function(editor, e2) {
          var blockCaretContainer = findBlockCaretContainer(editor);
          if (!blockCaretContainer) {
            return;
          }
          if (e2.type === "compositionstart") {
            e2.preventDefault();
            e2.stopPropagation();
            showBlockCaretContainer(editor, blockCaretContainer);
            return;
          }
          if (hasContent(blockCaretContainer)) {
            showBlockCaretContainer(editor, blockCaretContainer);
            editor.undoManager.add();
          }
        };
        var setup$c = function(editor) {
          editor.on("keyup compositionstart", curry(handleBlockContainer, editor));
        };
        var isContentEditableFalse$2 = isContentEditableFalse$b;
        var moveToCeFalseHorizontally = function(direction, editor, range2) {
          return moveHorizontally(editor, direction, range2, isBeforeContentEditableFalse, isAfterContentEditableFalse, isContentEditableFalse$2);
        };
        var moveToCeFalseVertically = function(direction, editor, range2) {
          var isBefore = function(caretPosition) {
            return isBeforeContentEditableFalse(caretPosition) || isBeforeTable(caretPosition);
          };
          var isAfter = function(caretPosition) {
            return isAfterContentEditableFalse(caretPosition) || isAfterTable(caretPosition);
          };
          return moveVertically(editor, direction, range2, isBefore, isAfter, isContentEditableFalse$2);
        };
        var createTextBlock = function(editor) {
          var textBlock = editor.dom.create(getForcedRootBlock(editor));
          if (!Env.ie || Env.ie >= 11) {
            textBlock.innerHTML = '<br data-mce-bogus="1">';
          }
          return textBlock;
        };
        var exitPreBlock = function(editor, direction, range2) {
          var caretWalker = CaretWalker(editor.getBody());
          var getVisualCaretPosition$1 = curry(getVisualCaretPosition, direction === 1 ? caretWalker.next : caretWalker.prev);
          if (range2.collapsed && hasForcedRootBlock(editor)) {
            var pre = editor.dom.getParent(range2.startContainer, "PRE");
            if (!pre) {
              return;
            }
            var caretPos = getVisualCaretPosition$1(CaretPosition.fromRangeStart(range2));
            if (!caretPos) {
              var newBlock = createTextBlock(editor);
              if (direction === 1) {
                editor.$(pre).after(newBlock);
              } else {
                editor.$(pre).before(newBlock);
              }
              editor.selection.select(newBlock, true);
              editor.selection.collapse();
            }
          }
        };
        var getHorizontalRange = function(editor, forward) {
          var direction = forward ? HDirection.Forwards : HDirection.Backwards;
          var range2 = editor.selection.getRng();
          return moveToCeFalseHorizontally(direction, editor, range2).orThunk(function() {
            exitPreBlock(editor, direction, range2);
            return Optional.none();
          });
        };
        var getVerticalRange = function(editor, down) {
          var direction = down ? 1 : -1;
          var range2 = editor.selection.getRng();
          return moveToCeFalseVertically(direction, editor, range2).orThunk(function() {
            exitPreBlock(editor, direction, range2);
            return Optional.none();
          });
        };
        var moveH$2 = function(editor, forward) {
          return getHorizontalRange(editor, forward).exists(function(newRange) {
            moveToRange(editor, newRange);
            return true;
          });
        };
        var moveV$3 = function(editor, down) {
          return getVerticalRange(editor, down).exists(function(newRange) {
            moveToRange(editor, newRange);
            return true;
          });
        };
        var moveToLineEndPoint$1 = function(editor, forward) {
          var isCefPosition = forward ? isAfterContentEditableFalse : isBeforeContentEditableFalse;
          return moveToLineEndPoint$3(editor, forward, isCefPosition);
        };
        var isTarget = function(node) {
          return contains$3(["figcaption"], name(node));
        };
        var rangeBefore = function(target) {
          var rng = document.createRange();
          rng.setStartBefore(target.dom);
          rng.setEndBefore(target.dom);
          return rng;
        };
        var insertElement = function(root, elm, forward) {
          if (forward) {
            append$1(root, elm);
          } else {
            prepend(root, elm);
          }
        };
        var insertBr = function(root, forward) {
          var br = SugarElement.fromTag("br");
          insertElement(root, br, forward);
          return rangeBefore(br);
        };
        var insertBlock = function(root, forward, blockName, attrs) {
          var block = SugarElement.fromTag(blockName);
          var br = SugarElement.fromTag("br");
          setAll$1(block, attrs);
          append$1(block, br);
          insertElement(root, block, forward);
          return rangeBefore(br);
        };
        var insertEmptyLine = function(root, rootBlockName, attrs, forward) {
          if (rootBlockName === "") {
            return insertBr(root, forward);
          } else {
            return insertBlock(root, forward, rootBlockName, attrs);
          }
        };
        var getClosestTargetBlock = function(pos, root) {
          var isRoot = curry(eq2, root);
          return closest$3(SugarElement.fromDom(pos.container()), isBlock$2, isRoot).filter(isTarget);
        };
        var isAtFirstOrLastLine = function(root, forward, pos) {
          return forward ? isAtLastLine(root.dom, pos) : isAtFirstLine(root.dom, pos);
        };
        var moveCaretToNewEmptyLine = function(editor, forward) {
          var root = SugarElement.fromDom(editor.getBody());
          var pos = CaretPosition.fromRangeStart(editor.selection.getRng());
          var rootBlock = getForcedRootBlock(editor);
          var rootBlockAttrs = getForcedRootBlockAttrs(editor);
          return getClosestTargetBlock(pos, root).exists(function() {
            if (isAtFirstOrLastLine(root, forward, pos)) {
              var rng = insertEmptyLine(root, rootBlock, rootBlockAttrs, forward);
              editor.selection.setRng(rng);
              return true;
            } else {
              return false;
            }
          });
        };
        var moveV$2 = function(editor, forward) {
          if (editor.selection.isCollapsed()) {
            return moveCaretToNewEmptyLine(editor, forward);
          } else {
            return false;
          }
        };
        var defaultPatterns = function(patterns2) {
          return map$3(patterns2, function(pattern) {
            return __assign({
              shiftKey: false,
              altKey: false,
              ctrlKey: false,
              metaKey: false,
              keyCode: 0,
              action: noop3
            }, pattern);
          });
        };
        var matchesEvent = function(pattern, evt) {
          return evt.keyCode === pattern.keyCode && evt.shiftKey === pattern.shiftKey && evt.altKey === pattern.altKey && evt.ctrlKey === pattern.ctrlKey && evt.metaKey === pattern.metaKey;
        };
        var match$1 = function(patterns2, evt) {
          return bind(defaultPatterns(patterns2), function(pattern) {
            return matchesEvent(pattern, evt) ? [pattern] : [];
          });
        };
        var action = function(f2) {
          var x2 = [];
          for (var _i2 = 1; _i2 < arguments.length; _i2++) {
            x2[_i2 - 1] = arguments[_i2];
          }
          return function() {
            return f2.apply(null, x2);
          };
        };
        var execute2 = function(patterns2, evt) {
          return find$3(match$1(patterns2, evt), function(pattern) {
            return pattern.action();
          });
        };
        var moveH$1 = function(editor, forward) {
          var direction = forward ? HDirection.Forwards : HDirection.Backwards;
          var range2 = editor.selection.getRng();
          return moveHorizontally(editor, direction, range2, isBeforeMedia, isAfterMedia, isMedia$2).exists(function(newRange) {
            moveToRange(editor, newRange);
            return true;
          });
        };
        var moveV$1 = function(editor, down) {
          var direction = down ? 1 : -1;
          var range2 = editor.selection.getRng();
          return moveVertically(editor, direction, range2, isBeforeMedia, isAfterMedia, isMedia$2).exists(function(newRange) {
            moveToRange(editor, newRange);
            return true;
          });
        };
        var moveToLineEndPoint = function(editor, forward) {
          var isNearMedia = forward ? isAfterMedia : isBeforeMedia;
          return moveToLineEndPoint$3(editor, forward, isNearMedia);
        };
        var deflate = function(rect, delta) {
          return {
            left: rect.left - delta,
            top: rect.top - delta,
            right: rect.right + delta * 2,
            bottom: rect.bottom + delta * 2,
            width: rect.width + delta,
            height: rect.height + delta
          };
        };
        var getCorners = function(getYAxisValue, tds) {
          return bind(tds, function(td) {
            var rect = deflate(clone2(td.getBoundingClientRect()), -1);
            return [
              {
                x: rect.left,
                y: getYAxisValue(rect),
                cell: td
              },
              {
                x: rect.right,
                y: getYAxisValue(rect),
                cell: td
              }
            ];
          });
        };
        var findClosestCorner = function(corners, x2, y2) {
          return foldl(corners, function(acc, newCorner) {
            return acc.fold(function() {
              return Optional.some(newCorner);
            }, function(oldCorner) {
              var oldDist = Math.sqrt(Math.abs(oldCorner.x - x2) + Math.abs(oldCorner.y - y2));
              var newDist = Math.sqrt(Math.abs(newCorner.x - x2) + Math.abs(newCorner.y - y2));
              return Optional.some(newDist < oldDist ? newCorner : oldCorner);
            });
          }, Optional.none());
        };
        var getClosestCell = function(getYAxisValue, isTargetCorner, table, x2, y2) {
          var cells = descendants(SugarElement.fromDom(table), "td,th,caption").map(function(e2) {
            return e2.dom;
          });
          var corners = filter$4(getCorners(getYAxisValue, cells), function(corner) {
            return isTargetCorner(corner, y2);
          });
          return findClosestCorner(corners, x2, y2).map(function(corner) {
            return corner.cell;
          });
        };
        var getBottomValue = function(rect) {
          return rect.bottom;
        };
        var getTopValue = function(rect) {
          return rect.top;
        };
        var isAbove = function(corner, y2) {
          return corner.y < y2;
        };
        var isBelow = function(corner, y2) {
          return corner.y > y2;
        };
        var getClosestCellAbove = curry(getClosestCell, getBottomValue, isAbove);
        var getClosestCellBelow = curry(getClosestCell, getTopValue, isBelow);
        var findClosestPositionInAboveCell = function(table, pos) {
          return head(pos.getClientRects()).bind(function(rect) {
            return getClosestCellAbove(table, rect.left, rect.top);
          }).bind(function(cell) {
            return findClosestHorizontalPosition(getLastLinePositions(cell), pos);
          });
        };
        var findClosestPositionInBelowCell = function(table, pos) {
          return last$2(pos.getClientRects()).bind(function(rect) {
            return getClosestCellBelow(table, rect.left, rect.top);
          }).bind(function(cell) {
            return findClosestHorizontalPosition(getFirstLinePositions(cell), pos);
          });
        };
        var hasNextBreak = function(getPositionsUntil2, scope, lineInfo) {
          return lineInfo.breakAt.exists(function(breakPos) {
            return getPositionsUntil2(scope, breakPos).breakAt.isSome();
          });
        };
        var startsWithWrapBreak = function(lineInfo) {
          return lineInfo.breakType === BreakType.Wrap && lineInfo.positions.length === 0;
        };
        var startsWithBrBreak = function(lineInfo) {
          return lineInfo.breakType === BreakType.Br && lineInfo.positions.length === 1;
        };
        var isAtTableCellLine = function(getPositionsUntil2, scope, pos) {
          var lineInfo = getPositionsUntil2(scope, pos);
          if (startsWithWrapBreak(lineInfo) || !isBr$5(pos.getNode()) && startsWithBrBreak(lineInfo)) {
            return !hasNextBreak(getPositionsUntil2, scope, lineInfo);
          } else {
            return lineInfo.breakAt.isNone();
          }
        };
        var isAtFirstTableCellLine = curry(isAtTableCellLine, getPositionsUntilPreviousLine);
        var isAtLastTableCellLine = curry(isAtTableCellLine, getPositionsUntilNextLine);
        var isCaretAtStartOrEndOfTable = function(forward, rng, table) {
          var caretPos = CaretPosition.fromRangeStart(rng);
          return positionIn(!forward, table).exists(function(pos) {
            return pos.isEqual(caretPos);
          });
        };
        var navigateHorizontally = function(editor, forward, table, _td) {
          var rng = editor.selection.getRng();
          var direction = forward ? 1 : -1;
          if (isFakeCaretTableBrowser() && isCaretAtStartOrEndOfTable(forward, rng, table)) {
            showCaret(direction, editor, table, !forward, false).each(function(newRng) {
              moveToRange(editor, newRng);
            });
            return true;
          }
          return false;
        };
        var getClosestAbovePosition = function(root, table, start5) {
          return findClosestPositionInAboveCell(table, start5).orThunk(function() {
            return head(start5.getClientRects()).bind(function(rect) {
              return findClosestHorizontalPositionFromPoint(getPositionsAbove(root, CaretPosition.before(table)), rect.left);
            });
          }).getOr(CaretPosition.before(table));
        };
        var getClosestBelowPosition = function(root, table, start5) {
          return findClosestPositionInBelowCell(table, start5).orThunk(function() {
            return head(start5.getClientRects()).bind(function(rect) {
              return findClosestHorizontalPositionFromPoint(getPositionsBelow(root, CaretPosition.after(table)), rect.left);
            });
          }).getOr(CaretPosition.after(table));
        };
        var getTable = function(previous, pos) {
          var node = pos.getNode(previous);
          return isElement$5(node) && node.nodeName === "TABLE" ? Optional.some(node) : Optional.none();
        };
        var renderBlock = function(down, editor, table, pos) {
          var forcedRootBlock = getForcedRootBlock(editor);
          if (forcedRootBlock) {
            editor.undoManager.transact(function() {
              var element = SugarElement.fromTag(forcedRootBlock);
              setAll$1(element, getForcedRootBlockAttrs(editor));
              append$1(element, SugarElement.fromTag("br"));
              if (down) {
                after$3(SugarElement.fromDom(table), element);
              } else {
                before$4(SugarElement.fromDom(table), element);
              }
              var rng = editor.dom.createRng();
              rng.setStart(element.dom, 0);
              rng.setEnd(element.dom, 0);
              moveToRange(editor, rng);
            });
          } else {
            moveToRange(editor, pos.toRange());
          }
        };
        var moveCaret = function(editor, down, pos) {
          var table = down ? getTable(true, pos) : getTable(false, pos);
          var last2 = down === false;
          table.fold(function() {
            return moveToRange(editor, pos.toRange());
          }, function(table2) {
            return positionIn(last2, editor.getBody()).filter(function(lastPos) {
              return lastPos.isEqual(pos);
            }).fold(function() {
              return moveToRange(editor, pos.toRange());
            }, function(_2) {
              return renderBlock(down, editor, table2, pos);
            });
          });
        };
        var navigateVertically = function(editor, down, table, td) {
          var rng = editor.selection.getRng();
          var pos = CaretPosition.fromRangeStart(rng);
          var root = editor.getBody();
          if (!down && isAtFirstTableCellLine(td, pos)) {
            var newPos = getClosestAbovePosition(root, table, pos);
            moveCaret(editor, down, newPos);
            return true;
          } else if (down && isAtLastTableCellLine(td, pos)) {
            var newPos = getClosestBelowPosition(root, table, pos);
            moveCaret(editor, down, newPos);
            return true;
          } else {
            return false;
          }
        };
        var move$1 = function(editor, forward, mover) {
          return Optional.from(editor.dom.getParent(editor.selection.getNode(), "td,th")).bind(function(td) {
            return Optional.from(editor.dom.getParent(td, "table")).map(function(table) {
              return mover(editor, forward, table, td);
            });
          }).getOr(false);
        };
        var moveH = function(editor, forward) {
          return move$1(editor, forward, navigateHorizontally);
        };
        var moveV = function(editor, forward) {
          return move$1(editor, forward, navigateVertically);
        };
        var executeKeydownOverride$3 = function(editor, caret, evt) {
          var os2 = detect().os;
          execute2([
            {
              keyCode: VK.RIGHT,
              action: action(moveH$2, editor, true)
            },
            {
              keyCode: VK.LEFT,
              action: action(moveH$2, editor, false)
            },
            {
              keyCode: VK.UP,
              action: action(moveV$3, editor, false)
            },
            {
              keyCode: VK.DOWN,
              action: action(moveV$3, editor, true)
            },
            {
              keyCode: VK.RIGHT,
              action: action(moveH, editor, true)
            },
            {
              keyCode: VK.LEFT,
              action: action(moveH, editor, false)
            },
            {
              keyCode: VK.UP,
              action: action(moveV, editor, false)
            },
            {
              keyCode: VK.DOWN,
              action: action(moveV, editor, true)
            },
            {
              keyCode: VK.RIGHT,
              action: action(moveH$1, editor, true)
            },
            {
              keyCode: VK.LEFT,
              action: action(moveH$1, editor, false)
            },
            {
              keyCode: VK.UP,
              action: action(moveV$1, editor, false)
            },
            {
              keyCode: VK.DOWN,
              action: action(moveV$1, editor, true)
            },
            {
              keyCode: VK.RIGHT,
              action: action(move$2, editor, caret, true)
            },
            {
              keyCode: VK.LEFT,
              action: action(move$2, editor, caret, false)
            },
            {
              keyCode: VK.RIGHT,
              ctrlKey: !os2.isOSX(),
              altKey: os2.isOSX(),
              action: action(moveNextWord, editor, caret)
            },
            {
              keyCode: VK.LEFT,
              ctrlKey: !os2.isOSX(),
              altKey: os2.isOSX(),
              action: action(movePrevWord, editor, caret)
            },
            {
              keyCode: VK.UP,
              action: action(moveV$2, editor, false)
            },
            {
              keyCode: VK.DOWN,
              action: action(moveV$2, editor, true)
            }
          ], evt).each(function(_2) {
            evt.preventDefault();
          });
        };
        var setup$b = function(editor, caret) {
          editor.on("keydown", function(evt) {
            if (evt.isDefaultPrevented() === false) {
              executeKeydownOverride$3(editor, caret, evt);
            }
          });
        };
        var executeKeydownOverride$2 = function(editor, caret, evt) {
          execute2([
            {
              keyCode: VK.BACKSPACE,
              action: action(backspaceDelete, editor, false)
            },
            {
              keyCode: VK.BACKSPACE,
              action: action(backspaceDelete$5, editor, false)
            },
            {
              keyCode: VK.DELETE,
              action: action(backspaceDelete$5, editor, true)
            },
            {
              keyCode: VK.BACKSPACE,
              action: action(backspaceDelete$6, editor, false)
            },
            {
              keyCode: VK.DELETE,
              action: action(backspaceDelete$6, editor, true)
            },
            {
              keyCode: VK.BACKSPACE,
              action: action(backspaceDelete$3, editor, caret, false)
            },
            {
              keyCode: VK.DELETE,
              action: action(backspaceDelete$3, editor, caret, true)
            },
            {
              keyCode: VK.BACKSPACE,
              action: action(backspaceDelete$9, editor, false)
            },
            {
              keyCode: VK.DELETE,
              action: action(backspaceDelete$9, editor, true)
            },
            {
              keyCode: VK.BACKSPACE,
              action: action(backspaceDelete$4, editor, false)
            },
            {
              keyCode: VK.DELETE,
              action: action(backspaceDelete$4, editor, true)
            },
            {
              keyCode: VK.BACKSPACE,
              action: action(backspaceDelete$1, editor, false)
            },
            {
              keyCode: VK.DELETE,
              action: action(backspaceDelete$1, editor, true)
            },
            {
              keyCode: VK.BACKSPACE,
              action: action(backspaceDelete$7, editor, false)
            },
            {
              keyCode: VK.DELETE,
              action: action(backspaceDelete$7, editor, true)
            },
            {
              keyCode: VK.BACKSPACE,
              action: action(backspaceDelete$8, editor, false)
            },
            {
              keyCode: VK.DELETE,
              action: action(backspaceDelete$8, editor, true)
            },
            {
              keyCode: VK.BACKSPACE,
              action: action(backspaceDelete$2, editor, false)
            },
            {
              keyCode: VK.DELETE,
              action: action(backspaceDelete$2, editor, true)
            }
          ], evt).each(function(_2) {
            evt.preventDefault();
          });
        };
        var executeKeyupOverride = function(editor, evt) {
          execute2([
            {
              keyCode: VK.BACKSPACE,
              action: action(paddEmptyElement, editor)
            },
            {
              keyCode: VK.DELETE,
              action: action(paddEmptyElement, editor)
            }
          ], evt);
        };
        var setup$a = function(editor, caret) {
          editor.on("keydown", function(evt) {
            if (evt.isDefaultPrevented() === false) {
              executeKeydownOverride$2(editor, caret, evt);
            }
          });
          editor.on("keyup", function(evt) {
            if (evt.isDefaultPrevented() === false) {
              executeKeyupOverride(editor, evt);
            }
          });
        };
        var firstNonWhiteSpaceNodeSibling = function(node) {
          while (node) {
            if (node.nodeType === 1 || node.nodeType === 3 && node.data && /[\r\n\s]/.test(node.data)) {
              return node;
            }
            node = node.nextSibling;
          }
        };
        var moveToCaretPosition = function(editor, root) {
          var node, lastNode = root;
          var dom2 = editor.dom;
          var moveCaretBeforeOnEnterElementsMap = editor.schema.getMoveCaretBeforeOnEnterElements();
          if (!root) {
            return;
          }
          if (/^(LI|DT|DD)$/.test(root.nodeName)) {
            var firstChild2 = firstNonWhiteSpaceNodeSibling(root.firstChild);
            if (firstChild2 && /^(UL|OL|DL)$/.test(firstChild2.nodeName)) {
              root.insertBefore(dom2.doc.createTextNode(nbsp), root.firstChild);
            }
          }
          var rng = dom2.createRng();
          root.normalize();
          if (root.hasChildNodes()) {
            var walker = new DomTreeWalker(root, root);
            while (node = walker.current()) {
              if (isText$7(node)) {
                rng.setStart(node, 0);
                rng.setEnd(node, 0);
                break;
              }
              if (moveCaretBeforeOnEnterElementsMap[node.nodeName.toLowerCase()]) {
                rng.setStartBefore(node);
                rng.setEndBefore(node);
                break;
              }
              lastNode = node;
              node = walker.next();
            }
            if (!node) {
              rng.setStart(lastNode, 0);
              rng.setEnd(lastNode, 0);
            }
          } else {
            if (isBr$5(root)) {
              if (root.nextSibling && dom2.isBlock(root.nextSibling)) {
                rng.setStartBefore(root);
                rng.setEndBefore(root);
              } else {
                rng.setStartAfter(root);
                rng.setEndAfter(root);
              }
            } else {
              rng.setStart(root, 0);
              rng.setEnd(root, 0);
            }
          }
          editor.selection.setRng(rng);
          scrollRangeIntoView(editor, rng);
        };
        var getEditableRoot$1 = function(dom2, node) {
          var root = dom2.getRoot();
          var parent2, editableRoot;
          parent2 = node;
          while (parent2 !== root && dom2.getContentEditable(parent2) !== "false") {
            if (dom2.getContentEditable(parent2) === "true") {
              editableRoot = parent2;
            }
            parent2 = parent2.parentNode;
          }
          return parent2 !== root ? editableRoot : root;
        };
        var getParentBlock = function(editor) {
          return Optional.from(editor.dom.getParent(editor.selection.getStart(true), editor.dom.isBlock));
        };
        var getParentBlockName = function(editor) {
          return getParentBlock(editor).fold(constant(""), function(parentBlock) {
            return parentBlock.nodeName.toUpperCase();
          });
        };
        var isListItemParentBlock = function(editor) {
          return getParentBlock(editor).filter(function(elm) {
            return isListItem(SugarElement.fromDom(elm));
          }).isSome();
        };
        var hasFirstChild = function(elm, name2) {
          return elm.firstChild && elm.firstChild.nodeName === name2;
        };
        var isFirstChild = function(elm) {
          var _a;
          return ((_a = elm.parentNode) === null || _a === void 0 ? void 0 : _a.firstChild) === elm;
        };
        var hasParent = function(elm, parentName) {
          return elm && elm.parentNode && elm.parentNode.nodeName === parentName;
        };
        var isListBlock = function(elm) {
          return elm && /^(OL|UL|LI)$/.test(elm.nodeName);
        };
        var isNestedList = function(elm) {
          return isListBlock(elm) && isListBlock(elm.parentNode);
        };
        var getContainerBlock = function(containerBlock) {
          var containerBlockParent = containerBlock.parentNode;
          if (/^(LI|DT|DD)$/.test(containerBlockParent.nodeName)) {
            return containerBlockParent;
          }
          return containerBlock;
        };
        var isFirstOrLastLi = function(containerBlock, parentBlock, first2) {
          var node = containerBlock[first2 ? "firstChild" : "lastChild"];
          while (node) {
            if (isElement$5(node)) {
              break;
            }
            node = node[first2 ? "nextSibling" : "previousSibling"];
          }
          return node === parentBlock;
        };
        var insert$3 = function(editor, createNewBlock, containerBlock, parentBlock, newBlockName) {
          var dom2 = editor.dom;
          var rng = editor.selection.getRng();
          if (containerBlock === editor.getBody()) {
            return;
          }
          if (isNestedList(containerBlock)) {
            newBlockName = "LI";
          }
          var newBlock = newBlockName ? createNewBlock(newBlockName) : dom2.create("BR");
          if (isFirstOrLastLi(containerBlock, parentBlock, true) && isFirstOrLastLi(containerBlock, parentBlock, false)) {
            if (hasParent(containerBlock, "LI")) {
              var containerBlockParent = getContainerBlock(containerBlock);
              dom2.insertAfter(newBlock, containerBlockParent);
              if (isFirstChild(containerBlock)) {
                dom2.remove(containerBlockParent);
              } else {
                dom2.remove(containerBlock);
              }
            } else {
              dom2.replace(newBlock, containerBlock);
            }
          } else if (isFirstOrLastLi(containerBlock, parentBlock, true)) {
            if (hasParent(containerBlock, "LI")) {
              dom2.insertAfter(newBlock, getContainerBlock(containerBlock));
              newBlock.appendChild(dom2.doc.createTextNode(" "));
              newBlock.appendChild(containerBlock);
            } else {
              containerBlock.parentNode.insertBefore(newBlock, containerBlock);
            }
            dom2.remove(parentBlock);
          } else if (isFirstOrLastLi(containerBlock, parentBlock, false)) {
            dom2.insertAfter(newBlock, getContainerBlock(containerBlock));
            dom2.remove(parentBlock);
          } else {
            containerBlock = getContainerBlock(containerBlock);
            var tmpRng = rng.cloneRange();
            tmpRng.setStartAfter(parentBlock);
            tmpRng.setEndAfter(containerBlock);
            var fragment = tmpRng.extractContents();
            if (newBlockName === "LI" && hasFirstChild(fragment, "LI")) {
              newBlock = fragment.firstChild;
              dom2.insertAfter(fragment, containerBlock);
            } else {
              dom2.insertAfter(fragment, containerBlock);
              dom2.insertAfter(newBlock, containerBlock);
            }
            dom2.remove(parentBlock);
          }
          moveToCaretPosition(editor, newBlock);
        };
        var trimZwsp = function(fragment) {
          each$k(descendants$1(SugarElement.fromDom(fragment), isText$8), function(text) {
            var rawNode = text.dom;
            rawNode.nodeValue = trim$2(rawNode.nodeValue);
          });
        };
        var isEmptyAnchor = function(dom2, elm) {
          return elm && elm.nodeName === "A" && dom2.isEmpty(elm);
        };
        var isTableCell = function(node) {
          return node && /^(TD|TH|CAPTION)$/.test(node.nodeName);
        };
        var emptyBlock = function(elm) {
          elm.innerHTML = '<br data-mce-bogus="1">';
        };
        var containerAndSiblingName = function(container, nodeName) {
          return container.nodeName === nodeName || container.previousSibling && container.previousSibling.nodeName === nodeName;
        };
        var canSplitBlock = function(dom2, node) {
          return node && dom2.isBlock(node) && !/^(TD|TH|CAPTION|FORM)$/.test(node.nodeName) && !/^(fixed|absolute)/i.test(node.style.position) && dom2.getContentEditable(node) !== "true";
        };
        var trimInlineElementsOnLeftSideOfBlock = function(dom2, nonEmptyElementsMap, block) {
          var node = block;
          var firstChilds = [];
          var i2;
          if (!node) {
            return;
          }
          while (node = node.firstChild) {
            if (dom2.isBlock(node)) {
              return;
            }
            if (isElement$5(node) && !nonEmptyElementsMap[node.nodeName.toLowerCase()]) {
              firstChilds.push(node);
            }
          }
          i2 = firstChilds.length;
          while (i2--) {
            node = firstChilds[i2];
            if (!node.hasChildNodes() || node.firstChild === node.lastChild && node.firstChild.nodeValue === "") {
              dom2.remove(node);
            } else {
              if (isEmptyAnchor(dom2, node)) {
                dom2.remove(node);
              }
            }
          }
        };
        var normalizeZwspOffset = function(start5, container, offset2) {
          if (isText$7(container) === false) {
            return offset2;
          } else if (start5) {
            return offset2 === 1 && container.data.charAt(offset2 - 1) === ZWSP$1 ? 0 : offset2;
          } else {
            return offset2 === container.data.length - 1 && container.data.charAt(offset2) === ZWSP$1 ? container.data.length : offset2;
          }
        };
        var includeZwspInRange = function(rng) {
          var newRng = rng.cloneRange();
          newRng.setStart(rng.startContainer, normalizeZwspOffset(true, rng.startContainer, rng.startOffset));
          newRng.setEnd(rng.endContainer, normalizeZwspOffset(false, rng.endContainer, rng.endOffset));
          return newRng;
        };
        var trimLeadingLineBreaks = function(node) {
          do {
            if (isText$7(node)) {
              node.nodeValue = node.nodeValue.replace(/^[\r\n]+/, "");
            }
            node = node.firstChild;
          } while (node);
        };
        var getEditableRoot = function(dom2, node) {
          var root = dom2.getRoot();
          var parent2, editableRoot;
          parent2 = node;
          while (parent2 !== root && dom2.getContentEditable(parent2) !== "false") {
            if (dom2.getContentEditable(parent2) === "true") {
              editableRoot = parent2;
            }
            parent2 = parent2.parentNode;
          }
          return parent2 !== root ? editableRoot : root;
        };
        var applyAttributes = function(editor, node, forcedRootBlockAttrs) {
          var dom2 = editor.dom;
          Optional.from(forcedRootBlockAttrs.style).map(dom2.parseStyle).each(function(attrStyles) {
            var currentStyles = getAllRaw(SugarElement.fromDom(node));
            var newStyles = __assign(__assign({}, currentStyles), attrStyles);
            dom2.setStyles(node, newStyles);
          });
          var attrClassesOpt = Optional.from(forcedRootBlockAttrs.class).map(function(attrClasses) {
            return attrClasses.split(/\s+/);
          });
          var currentClassesOpt = Optional.from(node.className).map(function(currentClasses) {
            return filter$4(currentClasses.split(/\s+/), function(clazz) {
              return clazz !== "";
            });
          });
          lift2(attrClassesOpt, currentClassesOpt, function(attrClasses, currentClasses) {
            var filteredClasses = filter$4(currentClasses, function(clazz) {
              return !contains$3(attrClasses, clazz);
            });
            var newClasses = __spreadArray(__spreadArray([], attrClasses, true), filteredClasses, true);
            dom2.setAttrib(node, "class", newClasses.join(" "));
          });
          var appliedAttrs = [
            "style",
            "class"
          ];
          var remainingAttrs = filter$3(forcedRootBlockAttrs, function(_2, attrs) {
            return !contains$3(appliedAttrs, attrs);
          });
          dom2.setAttribs(node, remainingAttrs);
        };
        var setForcedBlockAttrs = function(editor, node) {
          var forcedRootBlockName = getForcedRootBlock(editor);
          if (forcedRootBlockName && forcedRootBlockName.toLowerCase() === node.tagName.toLowerCase()) {
            var forcedRootBlockAttrs = getForcedRootBlockAttrs(editor);
            applyAttributes(editor, node, forcedRootBlockAttrs);
          }
        };
        var wrapSelfAndSiblingsInDefaultBlock = function(editor, newBlockName, rng, container, offset2) {
          var newBlock, parentBlock, startNode, node, next, rootBlockName;
          var blockName = newBlockName || "P";
          var dom2 = editor.dom, editableRoot = getEditableRoot(dom2, container);
          parentBlock = dom2.getParent(container, dom2.isBlock);
          if (!parentBlock || !canSplitBlock(dom2, parentBlock)) {
            parentBlock = parentBlock || editableRoot;
            if (parentBlock === editor.getBody() || isTableCell(parentBlock)) {
              rootBlockName = parentBlock.nodeName.toLowerCase();
            } else {
              rootBlockName = parentBlock.parentNode.nodeName.toLowerCase();
            }
            if (!parentBlock.hasChildNodes()) {
              newBlock = dom2.create(blockName);
              setForcedBlockAttrs(editor, newBlock);
              parentBlock.appendChild(newBlock);
              rng.setStart(newBlock, 0);
              rng.setEnd(newBlock, 0);
              return newBlock;
            }
            node = container;
            while (node.parentNode !== parentBlock) {
              node = node.parentNode;
            }
            while (node && !dom2.isBlock(node)) {
              startNode = node;
              node = node.previousSibling;
            }
            if (startNode && editor.schema.isValidChild(rootBlockName, blockName.toLowerCase())) {
              newBlock = dom2.create(blockName);
              setForcedBlockAttrs(editor, newBlock);
              startNode.parentNode.insertBefore(newBlock, startNode);
              node = startNode;
              while (node && !dom2.isBlock(node)) {
                next = node.nextSibling;
                newBlock.appendChild(node);
                node = next;
              }
              rng.setStart(container, offset2);
              rng.setEnd(container, offset2);
            }
          }
          return container;
        };
        var addBrToBlockIfNeeded = function(dom2, block) {
          block.normalize();
          var lastChild2 = block.lastChild;
          if (!lastChild2 || /^(left|right)$/gi.test(dom2.getStyle(lastChild2, "float", true))) {
            dom2.add(block, "br");
          }
        };
        var insert$2 = function(editor, evt) {
          var tmpRng, container, offset2, parentBlock;
          var newBlock, fragment, containerBlock, parentBlockName, newBlockName, isAfterLastNodeInContainer;
          var dom2 = editor.dom;
          var schema = editor.schema, nonEmptyElementsMap = schema.getNonEmptyElements();
          var rng = editor.selection.getRng();
          var createNewBlock = function(name2) {
            var node = container, block, clonedNode, caretNode;
            var textInlineElements = schema.getTextInlineElements();
            if (name2 || parentBlockName === "TABLE" || parentBlockName === "HR") {
              block = dom2.create(name2 || newBlockName);
            } else {
              block = parentBlock.cloneNode(false);
            }
            caretNode = block;
            if (shouldKeepStyles(editor) === false) {
              dom2.setAttrib(block, "style", null);
              dom2.setAttrib(block, "class", null);
            } else {
              do {
                if (textInlineElements[node.nodeName]) {
                  if (isCaretNode(node) || isBookmarkNode$1(node)) {
                    continue;
                  }
                  clonedNode = node.cloneNode(false);
                  dom2.setAttrib(clonedNode, "id", "");
                  if (block.hasChildNodes()) {
                    clonedNode.appendChild(block.firstChild);
                    block.appendChild(clonedNode);
                  } else {
                    caretNode = clonedNode;
                    block.appendChild(clonedNode);
                  }
                }
              } while ((node = node.parentNode) && node !== editableRoot);
            }
            setForcedBlockAttrs(editor, block);
            emptyBlock(caretNode);
            return block;
          };
          var isCaretAtStartOrEndOfBlock = function(start5) {
            var node, name2;
            var normalizedOffset = normalizeZwspOffset(start5, container, offset2);
            if (isText$7(container) && (start5 ? normalizedOffset > 0 : normalizedOffset < container.nodeValue.length)) {
              return false;
            }
            if (container.parentNode === parentBlock && isAfterLastNodeInContainer && !start5) {
              return true;
            }
            if (start5 && isElement$5(container) && container === parentBlock.firstChild) {
              return true;
            }
            if (containerAndSiblingName(container, "TABLE") || containerAndSiblingName(container, "HR")) {
              return isAfterLastNodeInContainer && !start5 || !isAfterLastNodeInContainer && start5;
            }
            var walker = new DomTreeWalker(container, parentBlock);
            if (isText$7(container)) {
              if (start5 && normalizedOffset === 0) {
                walker.prev();
              } else if (!start5 && normalizedOffset === container.nodeValue.length) {
                walker.next();
              }
            }
            while (node = walker.current()) {
              if (isElement$5(node)) {
                if (!node.getAttribute("data-mce-bogus")) {
                  name2 = node.nodeName.toLowerCase();
                  if (nonEmptyElementsMap[name2] && name2 !== "br") {
                    return false;
                  }
                }
              } else if (isText$7(node) && !isWhitespaceText(node.nodeValue)) {
                return false;
              }
              if (start5) {
                walker.prev();
              } else {
                walker.next();
              }
            }
            return true;
          };
          var insertNewBlockAfter = function() {
            if (/^(H[1-6]|PRE|FIGURE)$/.test(parentBlockName) && containerBlockName !== "HGROUP") {
              newBlock = createNewBlock(newBlockName);
            } else {
              newBlock = createNewBlock();
            }
            if (shouldEndContainerOnEmptyBlock(editor) && canSplitBlock(dom2, containerBlock) && dom2.isEmpty(parentBlock)) {
              newBlock = dom2.split(containerBlock, parentBlock);
            } else {
              dom2.insertAfter(newBlock, parentBlock);
            }
            moveToCaretPosition(editor, newBlock);
          };
          normalize$2(dom2, rng).each(function(normRng) {
            rng.setStart(normRng.startContainer, normRng.startOffset);
            rng.setEnd(normRng.endContainer, normRng.endOffset);
          });
          container = rng.startContainer;
          offset2 = rng.startOffset;
          newBlockName = getForcedRootBlock(editor);
          var shiftKey = !!(evt && evt.shiftKey);
          var ctrlKey = !!(evt && evt.ctrlKey);
          if (isElement$5(container) && container.hasChildNodes()) {
            isAfterLastNodeInContainer = offset2 > container.childNodes.length - 1;
            container = container.childNodes[Math.min(offset2, container.childNodes.length - 1)] || container;
            if (isAfterLastNodeInContainer && isText$7(container)) {
              offset2 = container.nodeValue.length;
            } else {
              offset2 = 0;
            }
          }
          var editableRoot = getEditableRoot(dom2, container);
          if (!editableRoot) {
            return;
          }
          if (newBlockName && !shiftKey || !newBlockName && shiftKey) {
            container = wrapSelfAndSiblingsInDefaultBlock(editor, newBlockName, rng, container, offset2);
          }
          parentBlock = dom2.getParent(container, dom2.isBlock);
          containerBlock = parentBlock ? dom2.getParent(parentBlock.parentNode, dom2.isBlock) : null;
          parentBlockName = parentBlock ? parentBlock.nodeName.toUpperCase() : "";
          var containerBlockName = containerBlock ? containerBlock.nodeName.toUpperCase() : "";
          if (containerBlockName === "LI" && !ctrlKey) {
            parentBlock = containerBlock;
            containerBlock = containerBlock.parentNode;
            parentBlockName = containerBlockName;
          }
          if (/^(LI|DT|DD)$/.test(parentBlockName)) {
            if (dom2.isEmpty(parentBlock)) {
              insert$3(editor, createNewBlock, containerBlock, parentBlock, newBlockName);
              return;
            }
          }
          if (newBlockName && parentBlock === editor.getBody()) {
            return;
          }
          newBlockName = newBlockName || "P";
          if (isCaretContainerBlock$1(parentBlock)) {
            newBlock = showCaretContainerBlock(parentBlock);
            if (dom2.isEmpty(parentBlock)) {
              emptyBlock(parentBlock);
            }
            setForcedBlockAttrs(editor, newBlock);
            moveToCaretPosition(editor, newBlock);
          } else if (isCaretAtStartOrEndOfBlock()) {
            insertNewBlockAfter();
          } else if (isCaretAtStartOrEndOfBlock(true)) {
            newBlock = parentBlock.parentNode.insertBefore(createNewBlock(), parentBlock);
            moveToCaretPosition(editor, containerAndSiblingName(parentBlock, "HR") ? newBlock : parentBlock);
          } else {
            tmpRng = includeZwspInRange(rng).cloneRange();
            tmpRng.setEndAfter(parentBlock);
            fragment = tmpRng.extractContents();
            trimZwsp(fragment);
            trimLeadingLineBreaks(fragment);
            newBlock = fragment.firstChild;
            dom2.insertAfter(fragment, parentBlock);
            trimInlineElementsOnLeftSideOfBlock(dom2, nonEmptyElementsMap, newBlock);
            addBrToBlockIfNeeded(dom2, parentBlock);
            if (dom2.isEmpty(parentBlock)) {
              emptyBlock(parentBlock);
            }
            newBlock.normalize();
            if (dom2.isEmpty(newBlock)) {
              dom2.remove(newBlock);
              insertNewBlockAfter();
            } else {
              setForcedBlockAttrs(editor, newBlock);
              moveToCaretPosition(editor, newBlock);
            }
          }
          dom2.setAttrib(newBlock, "id", "");
          editor.fire("NewBlock", { newBlock });
        };
        var hasRightSideContent = function(schema, container, parentBlock) {
          var walker = new DomTreeWalker(container, parentBlock);
          var node;
          var nonEmptyElementsMap = schema.getNonEmptyElements();
          while (node = walker.next()) {
            if (nonEmptyElementsMap[node.nodeName.toLowerCase()] || node.length > 0) {
              return true;
            }
          }
        };
        var moveSelectionToBr = function(editor, brElm, extraBr) {
          var rng = editor.dom.createRng();
          if (!extraBr) {
            rng.setStartAfter(brElm);
            rng.setEndAfter(brElm);
          } else {
            rng.setStartBefore(brElm);
            rng.setEndBefore(brElm);
          }
          editor.selection.setRng(rng);
          scrollRangeIntoView(editor, rng);
        };
        var insertBrAtCaret = function(editor, evt) {
          var selection = editor.selection;
          var dom2 = editor.dom;
          var rng = selection.getRng();
          var brElm;
          var extraBr;
          normalize$2(dom2, rng).each(function(normRng) {
            rng.setStart(normRng.startContainer, normRng.startOffset);
            rng.setEnd(normRng.endContainer, normRng.endOffset);
          });
          var offset2 = rng.startOffset;
          var container = rng.startContainer;
          if (container.nodeType === 1 && container.hasChildNodes()) {
            var isAfterLastNodeInContainer = offset2 > container.childNodes.length - 1;
            container = container.childNodes[Math.min(offset2, container.childNodes.length - 1)] || container;
            if (isAfterLastNodeInContainer && container.nodeType === 3) {
              offset2 = container.nodeValue.length;
            } else {
              offset2 = 0;
            }
          }
          var parentBlock = dom2.getParent(container, dom2.isBlock);
          var containerBlock = parentBlock ? dom2.getParent(parentBlock.parentNode, dom2.isBlock) : null;
          var containerBlockName = containerBlock ? containerBlock.nodeName.toUpperCase() : "";
          var isControlKey = !!(evt && evt.ctrlKey);
          if (containerBlockName === "LI" && !isControlKey) {
            parentBlock = containerBlock;
          }
          if (container && container.nodeType === 3 && offset2 >= container.nodeValue.length) {
            if (!hasRightSideContent(editor.schema, container, parentBlock)) {
              brElm = dom2.create("br");
              rng.insertNode(brElm);
              rng.setStartAfter(brElm);
              rng.setEndAfter(brElm);
              extraBr = true;
            }
          }
          brElm = dom2.create("br");
          rangeInsertNode(dom2, rng, brElm);
          moveSelectionToBr(editor, brElm, extraBr);
          editor.undoManager.add();
        };
        var insertBrBefore = function(editor, inline) {
          var br = SugarElement.fromTag("br");
          before$4(SugarElement.fromDom(inline), br);
          editor.undoManager.add();
        };
        var insertBrAfter = function(editor, inline) {
          if (!hasBrAfter(editor.getBody(), inline)) {
            after$3(SugarElement.fromDom(inline), SugarElement.fromTag("br"));
          }
          var br = SugarElement.fromTag("br");
          after$3(SugarElement.fromDom(inline), br);
          moveSelectionToBr(editor, br.dom, false);
          editor.undoManager.add();
        };
        var isBeforeBr = function(pos) {
          return isBr$5(pos.getNode());
        };
        var hasBrAfter = function(rootNode, startNode) {
          if (isBeforeBr(CaretPosition.after(startNode))) {
            return true;
          } else {
            return nextPosition(rootNode, CaretPosition.after(startNode)).map(function(pos) {
              return isBr$5(pos.getNode());
            }).getOr(false);
          }
        };
        var isAnchorLink = function(elm) {
          return elm && elm.nodeName === "A" && "href" in elm;
        };
        var isInsideAnchor = function(location2) {
          return location2.fold(never, isAnchorLink, isAnchorLink, never);
        };
        var readInlineAnchorLocation = function(editor) {
          var isInlineTarget$1 = curry(isInlineTarget, editor);
          var position = CaretPosition.fromRangeStart(editor.selection.getRng());
          return readLocation(isInlineTarget$1, editor.getBody(), position).filter(isInsideAnchor);
        };
        var insertBrOutsideAnchor = function(editor, location2) {
          location2.fold(noop3, curry(insertBrBefore, editor), curry(insertBrAfter, editor), noop3);
        };
        var insert$1 = function(editor, evt) {
          var anchorLocation = readInlineAnchorLocation(editor);
          if (anchorLocation.isSome()) {
            anchorLocation.each(curry(insertBrOutsideAnchor, editor));
          } else {
            insertBrAtCaret(editor, evt);
          }
        };
        var matchesSelector = function(editor, selector) {
          return getParentBlock(editor).filter(function(parentBlock) {
            return selector.length > 0 && is$2(SugarElement.fromDom(parentBlock), selector);
          }).isSome();
        };
        var shouldInsertBr = function(editor) {
          return matchesSelector(editor, getBrNewLineSelector(editor));
        };
        var shouldBlockNewLine$1 = function(editor) {
          return matchesSelector(editor, getNoNewLineSelector(editor));
        };
        var newLineAction = Adt.generate([
          { br: [] },
          { block: [] },
          { none: [] }
        ]);
        var shouldBlockNewLine = function(editor, _shiftKey) {
          return shouldBlockNewLine$1(editor);
        };
        var isBrMode = function(requiredState) {
          return function(editor, _shiftKey) {
            var brMode = getForcedRootBlock(editor) === "";
            return brMode === requiredState;
          };
        };
        var inListBlock = function(requiredState) {
          return function(editor, _shiftKey) {
            return isListItemParentBlock(editor) === requiredState;
          };
        };
        var inBlock = function(blockName, requiredState) {
          return function(editor, _shiftKey) {
            var state = getParentBlockName(editor) === blockName.toUpperCase();
            return state === requiredState;
          };
        };
        var inPreBlock = function(requiredState) {
          return inBlock("pre", requiredState);
        };
        var inSummaryBlock = function() {
          return inBlock("summary", true);
        };
        var shouldPutBrInPre = function(requiredState) {
          return function(editor, _shiftKey) {
            return shouldPutBrInPre$1(editor) === requiredState;
          };
        };
        var inBrContext = function(editor, _shiftKey) {
          return shouldInsertBr(editor);
        };
        var hasShiftKey = function(_editor, shiftKey) {
          return shiftKey;
        };
        var canInsertIntoEditableRoot = function(editor) {
          var forcedRootBlock = getForcedRootBlock(editor);
          var rootEditable = getEditableRoot$1(editor.dom, editor.selection.getStart());
          return rootEditable && editor.schema.isValidChild(rootEditable.nodeName, forcedRootBlock ? forcedRootBlock : "P");
        };
        var match2 = function(predicates, action2) {
          return function(editor, shiftKey) {
            var isMatch = foldl(predicates, function(res, p2) {
              return res && p2(editor, shiftKey);
            }, true);
            return isMatch ? Optional.some(action2) : Optional.none();
          };
        };
        var getAction2 = function(editor, evt) {
          return evaluateUntil([
            match2([shouldBlockNewLine], newLineAction.none()),
            match2([inSummaryBlock()], newLineAction.br()),
            match2([
              inPreBlock(true),
              shouldPutBrInPre(false),
              hasShiftKey
            ], newLineAction.br()),
            match2([
              inPreBlock(true),
              shouldPutBrInPre(false)
            ], newLineAction.block()),
            match2([
              inPreBlock(true),
              shouldPutBrInPre(true),
              hasShiftKey
            ], newLineAction.block()),
            match2([
              inPreBlock(true),
              shouldPutBrInPre(true)
            ], newLineAction.br()),
            match2([
              inListBlock(true),
              hasShiftKey
            ], newLineAction.br()),
            match2([inListBlock(true)], newLineAction.block()),
            match2([
              isBrMode(true),
              hasShiftKey,
              canInsertIntoEditableRoot
            ], newLineAction.block()),
            match2([isBrMode(true)], newLineAction.br()),
            match2([inBrContext], newLineAction.br()),
            match2([
              isBrMode(false),
              hasShiftKey
            ], newLineAction.br()),
            match2([canInsertIntoEditableRoot], newLineAction.block())
          ], [
            editor,
            !!(evt && evt.shiftKey)
          ]).getOr(newLineAction.none());
        };
        var insert = function(editor, evt) {
          getAction2(editor, evt).fold(function() {
            insert$1(editor, evt);
          }, function() {
            insert$2(editor, evt);
          }, noop3);
        };
        var handleEnterKeyEvent = function(editor, event) {
          if (event.isDefaultPrevented()) {
            return;
          }
          event.preventDefault();
          endTypingLevelIgnoreLocks(editor.undoManager);
          editor.undoManager.transact(function() {
            if (editor.selection.isCollapsed() === false) {
              editor.execCommand("Delete");
            }
            insert(editor, event);
          });
        };
        var setup$9 = function(editor) {
          editor.on("keydown", function(event) {
            if (event.keyCode === VK.ENTER) {
              handleEnterKeyEvent(editor, event);
            }
          });
        };
        var executeKeydownOverride$1 = function(editor, caret, evt) {
          execute2([
            {
              keyCode: VK.END,
              action: action(moveToLineEndPoint$1, editor, true)
            },
            {
              keyCode: VK.HOME,
              action: action(moveToLineEndPoint$1, editor, false)
            },
            {
              keyCode: VK.END,
              action: action(moveToLineEndPoint, editor, true)
            },
            {
              keyCode: VK.HOME,
              action: action(moveToLineEndPoint, editor, false)
            },
            {
              keyCode: VK.END,
              action: action(moveToLineEndPoint$2, editor, true, caret)
            },
            {
              keyCode: VK.HOME,
              action: action(moveToLineEndPoint$2, editor, false, caret)
            }
          ], evt).each(function(_2) {
            evt.preventDefault();
          });
        };
        var setup$8 = function(editor, caret) {
          editor.on("keydown", function(evt) {
            if (evt.isDefaultPrevented() === false) {
              executeKeydownOverride$1(editor, caret, evt);
            }
          });
        };
        var browser = detect().browser;
        var setupIeInput = function(editor) {
          var keypressThrotter = first(function() {
            if (!editor.composing) {
              normalizeNbspsInEditor(editor);
            }
          }, 0);
          if (browser.isIE()) {
            editor.on("keypress", function(_e2) {
              keypressThrotter.throttle();
            });
            editor.on("remove", function(_e2) {
              keypressThrotter.cancel();
            });
          }
        };
        var setup$7 = function(editor) {
          setupIeInput(editor);
          editor.on("input", function(e2) {
            if (e2.isComposing === false) {
              normalizeNbspsInEditor(editor);
            }
          });
        };
        var platform = detect();
        var executeKeyupAction = function(editor, caret, evt) {
          execute2([
            {
              keyCode: VK.PAGE_UP,
              action: action(moveToLineEndPoint$2, editor, false, caret)
            },
            {
              keyCode: VK.PAGE_DOWN,
              action: action(moveToLineEndPoint$2, editor, true, caret)
            }
          ], evt);
        };
        var stopImmediatePropagation = function(e2) {
          return e2.stopImmediatePropagation();
        };
        var isPageUpDown = function(evt) {
          return evt.keyCode === VK.PAGE_UP || evt.keyCode === VK.PAGE_DOWN;
        };
        var setNodeChangeBlocker = function(blocked, editor, block) {
          if (block && !blocked.get()) {
            editor.on("NodeChange", stopImmediatePropagation, true);
          } else if (!block && blocked.get()) {
            editor.off("NodeChange", stopImmediatePropagation);
          }
          blocked.set(block);
        };
        var setup$6 = function(editor, caret) {
          if (platform.os.isOSX()) {
            return;
          }
          var blocked = Cell(false);
          editor.on("keydown", function(evt) {
            if (isPageUpDown(evt)) {
              setNodeChangeBlocker(blocked, editor, true);
            }
          });
          editor.on("keyup", function(evt) {
            if (evt.isDefaultPrevented() === false) {
              executeKeyupAction(editor, caret, evt);
            }
            if (isPageUpDown(evt) && blocked.get()) {
              setNodeChangeBlocker(blocked, editor, false);
              editor.nodeChanged();
            }
          });
        };
        var insertTextAtPosition = function(text, pos) {
          var container = pos.container();
          var offset2 = pos.offset();
          if (isText$7(container)) {
            container.insertData(offset2, text);
            return Optional.some(CaretPosition(container, offset2 + text.length));
          } else {
            return getElementFromPosition(pos).map(function(elm) {
              var textNode = SugarElement.fromText(text);
              if (pos.isAtEnd()) {
                after$3(elm, textNode);
              } else {
                before$4(elm, textNode);
              }
              return CaretPosition(textNode.dom, text.length);
            });
          }
        };
        var insertNbspAtPosition = curry(insertTextAtPosition, nbsp);
        var insertSpaceAtPosition = curry(insertTextAtPosition, " ");
        var locationToCaretPosition = function(root) {
          return function(location2) {
            return location2.fold(function(element) {
              return prevPosition(root.dom, CaretPosition.before(element));
            }, function(element) {
              return firstPositionIn(element);
            }, function(element) {
              return lastPositionIn(element);
            }, function(element) {
              return nextPosition(root.dom, CaretPosition.after(element));
            });
          };
        };
        var insertInlineBoundarySpaceOrNbsp = function(root, pos) {
          return function(checkPos) {
            return needsToHaveNbsp(root, checkPos) ? insertNbspAtPosition(pos) : insertSpaceAtPosition(pos);
          };
        };
        var setSelection = function(editor) {
          return function(pos) {
            editor.selection.setRng(pos.toRange());
            editor.nodeChanged();
            return true;
          };
        };
        var insertSpaceOrNbspAtSelection = function(editor) {
          var pos = CaretPosition.fromRangeStart(editor.selection.getRng());
          var root = SugarElement.fromDom(editor.getBody());
          if (editor.selection.isCollapsed()) {
            var isInlineTarget$1 = curry(isInlineTarget, editor);
            var caretPosition = CaretPosition.fromRangeStart(editor.selection.getRng());
            return readLocation(isInlineTarget$1, editor.getBody(), caretPosition).bind(locationToCaretPosition(root)).bind(insertInlineBoundarySpaceOrNbsp(root, pos)).exists(setSelection(editor));
          } else {
            return false;
          }
        };
        var executeKeydownOverride = function(editor, evt) {
          execute2([{
            keyCode: VK.SPACEBAR,
            action: action(insertSpaceOrNbspAtSelection, editor)
          }], evt).each(function(_2) {
            evt.preventDefault();
          });
        };
        var setup$5 = function(editor) {
          editor.on("keydown", function(evt) {
            if (evt.isDefaultPrevented() === false) {
              executeKeydownOverride(editor, evt);
            }
          });
        };
        var registerKeyboardOverrides = function(editor) {
          var caret = setupSelectedState(editor);
          setup$c(editor);
          setup$b(editor, caret);
          setup$a(editor, caret);
          setup$9(editor);
          setup$5(editor);
          setup$7(editor);
          setup$8(editor, caret);
          setup$6(editor, caret);
          return caret;
        };
        var setup$4 = function(editor) {
          if (!isRtc(editor)) {
            return registerKeyboardOverrides(editor);
          } else {
            return Cell(null);
          }
        };
        var NodeChange = function() {
          function NodeChange2(editor) {
            this.lastPath = [];
            this.editor = editor;
            var lastRng;
            var self2 = this;
            if (!("onselectionchange" in editor.getDoc())) {
              editor.on("NodeChange click mouseup keyup focus", function(e2) {
                var nativeRng = editor.selection.getRng();
                var fakeRng = {
                  startContainer: nativeRng.startContainer,
                  startOffset: nativeRng.startOffset,
                  endContainer: nativeRng.endContainer,
                  endOffset: nativeRng.endOffset
                };
                if (e2.type === "nodechange" || !isEq$4(fakeRng, lastRng)) {
                  editor.fire("SelectionChange");
                }
                lastRng = fakeRng;
              });
            }
            editor.on("contextmenu", function() {
              editor.fire("SelectionChange");
            });
            editor.on("SelectionChange", function() {
              var startElm = editor.selection.getStart(true);
              if (!startElm || !Env.range && editor.selection.isCollapsed()) {
                return;
              }
              if (hasAnyRanges(editor) && !self2.isSameElementPath(startElm) && editor.dom.isChildOf(startElm, editor.getBody())) {
                editor.nodeChanged({ selectionChange: true });
              }
            });
            editor.on("mouseup", function(e2) {
              if (!e2.isDefaultPrevented() && hasAnyRanges(editor)) {
                if (editor.selection.getNode().nodeName === "IMG") {
                  Delay.setEditorTimeout(editor, function() {
                    editor.nodeChanged();
                  });
                } else {
                  editor.nodeChanged();
                }
              }
            });
          }
          NodeChange2.prototype.nodeChanged = function(args) {
            var selection = this.editor.selection;
            var node, parents2, root;
            if (this.editor.initialized && selection && !shouldDisableNodeChange(this.editor) && !this.editor.mode.isReadOnly()) {
              root = this.editor.getBody();
              node = selection.getStart(true) || root;
              if (node.ownerDocument !== this.editor.getDoc() || !this.editor.dom.isChildOf(node, root)) {
                node = root;
              }
              parents2 = [];
              this.editor.dom.getParent(node, function(node2) {
                if (node2 === root) {
                  return true;
                }
                parents2.push(node2);
              });
              args = args || {};
              args.element = node;
              args.parents = parents2;
              this.editor.fire("NodeChange", args);
            }
          };
          NodeChange2.prototype.isSameElementPath = function(startElm) {
            var i2;
            var currentPath = this.editor.$(startElm).parentsUntil(this.editor.getBody()).add(startElm);
            if (currentPath.length === this.lastPath.length) {
              for (i2 = currentPath.length; i2 >= 0; i2--) {
                if (currentPath[i2] !== this.lastPath[i2]) {
                  break;
                }
              }
              if (i2 === -1) {
                this.lastPath = currentPath;
                return true;
              }
            }
            this.lastPath = currentPath;
            return false;
          };
          return NodeChange2;
        }();
        var preventSummaryToggle = function(editor) {
          editor.on("click", function(e2) {
            if (editor.dom.getParent(e2.target, "details")) {
              e2.preventDefault();
            }
          });
        };
        var filterDetails = function(editor) {
          editor.parser.addNodeFilter("details", function(elms) {
            each$k(elms, function(details) {
              details.attr("data-mce-open", details.attr("open"));
              details.attr("open", "open");
            });
          });
          editor.serializer.addNodeFilter("details", function(elms) {
            each$k(elms, function(details) {
              var open = details.attr("data-mce-open");
              details.attr("open", isString$1(open) ? open : null);
              details.attr("data-mce-open", null);
            });
          });
        };
        var setup$3 = function(editor) {
          preventSummaryToggle(editor);
          filterDetails(editor);
        };
        var isTextBlockNode = function(node) {
          return isElement$5(node) && isTextBlock$2(SugarElement.fromDom(node));
        };
        var normalizeSelection = function(editor) {
          var rng = editor.selection.getRng();
          var startPos = CaretPosition.fromRangeStart(rng);
          var endPos = CaretPosition.fromRangeEnd(rng);
          if (CaretPosition.isElementPosition(startPos)) {
            var container = startPos.container();
            if (isTextBlockNode(container)) {
              firstPositionIn(container).each(function(pos) {
                return rng.setStart(pos.container(), pos.offset());
              });
            }
          }
          if (CaretPosition.isElementPosition(endPos)) {
            var container = startPos.container();
            if (isTextBlockNode(container)) {
              lastPositionIn(container).each(function(pos) {
                return rng.setEnd(pos.container(), pos.offset());
              });
            }
          }
          editor.selection.setRng(normalize(rng));
        };
        var setup$2 = function(editor) {
          editor.on("click", function(e2) {
            if (e2.detail >= 3) {
              normalizeSelection(editor);
            }
          });
        };
        var getAbsolutePosition = function(elm) {
          var clientRect = elm.getBoundingClientRect();
          var doc2 = elm.ownerDocument;
          var docElem2 = doc2.documentElement;
          var win = doc2.defaultView;
          return {
            top: clientRect.top + win.pageYOffset - docElem2.clientTop,
            left: clientRect.left + win.pageXOffset - docElem2.clientLeft
          };
        };
        var getBodyPosition = function(editor) {
          return editor.inline ? getAbsolutePosition(editor.getBody()) : {
            left: 0,
            top: 0
          };
        };
        var getScrollPosition = function(editor) {
          var body = editor.getBody();
          return editor.inline ? {
            left: body.scrollLeft,
            top: body.scrollTop
          } : {
            left: 0,
            top: 0
          };
        };
        var getBodyScroll = function(editor) {
          var body = editor.getBody(), docElm = editor.getDoc().documentElement;
          var inlineScroll = {
            left: body.scrollLeft,
            top: body.scrollTop
          };
          var iframeScroll = {
            left: body.scrollLeft || docElm.scrollLeft,
            top: body.scrollTop || docElm.scrollTop
          };
          return editor.inline ? inlineScroll : iframeScroll;
        };
        var getMousePosition = function(editor, event) {
          if (event.target.ownerDocument !== editor.getDoc()) {
            var iframePosition = getAbsolutePosition(editor.getContentAreaContainer());
            var scrollPosition = getBodyScroll(editor);
            return {
              left: event.pageX - iframePosition.left + scrollPosition.left,
              top: event.pageY - iframePosition.top + scrollPosition.top
            };
          }
          return {
            left: event.pageX,
            top: event.pageY
          };
        };
        var calculatePosition = function(bodyPosition, scrollPosition, mousePosition) {
          return {
            pageX: mousePosition.left - bodyPosition.left + scrollPosition.left,
            pageY: mousePosition.top - bodyPosition.top + scrollPosition.top
          };
        };
        var calc = function(editor, event) {
          return calculatePosition(getBodyPosition(editor), getScrollPosition(editor), getMousePosition(editor, event));
        };
        var isContentEditableFalse$1 = isContentEditableFalse$b, isContentEditableTrue$1 = isContentEditableTrue$4;
        var isDraggable = function(rootElm, elm) {
          return isContentEditableFalse$1(elm) && elm !== rootElm;
        };
        var isValidDropTarget = function(editor, targetElement, dragElement) {
          if (targetElement === dragElement || editor.dom.isChildOf(targetElement, dragElement)) {
            return false;
          }
          return !isContentEditableFalse$1(targetElement);
        };
        var cloneElement = function(elm) {
          var cloneElm = elm.cloneNode(true);
          cloneElm.removeAttribute("data-mce-selected");
          return cloneElm;
        };
        var createGhost = function(editor, elm, width, height) {
          var dom2 = editor.dom;
          var clonedElm = elm.cloneNode(true);
          dom2.setStyles(clonedElm, {
            width,
            height
          });
          dom2.setAttrib(clonedElm, "data-mce-selected", null);
          var ghostElm = dom2.create("div", {
            "class": "mce-drag-container",
            "data-mce-bogus": "all",
            "unselectable": "on",
            "contenteditable": "false"
          });
          dom2.setStyles(ghostElm, {
            position: "absolute",
            opacity: 0.5,
            overflow: "hidden",
            border: 0,
            padding: 0,
            margin: 0,
            width,
            height
          });
          dom2.setStyles(clonedElm, {
            margin: 0,
            boxSizing: "border-box"
          });
          ghostElm.appendChild(clonedElm);
          return ghostElm;
        };
        var appendGhostToBody = function(ghostElm, bodyElm) {
          if (ghostElm.parentNode !== bodyElm) {
            bodyElm.appendChild(ghostElm);
          }
        };
        var moveGhost = function(ghostElm, position, width, height, maxX, maxY) {
          var overflowX = 0, overflowY = 0;
          ghostElm.style.left = position.pageX + "px";
          ghostElm.style.top = position.pageY + "px";
          if (position.pageX + width > maxX) {
            overflowX = position.pageX + width - maxX;
          }
          if (position.pageY + height > maxY) {
            overflowY = position.pageY + height - maxY;
          }
          ghostElm.style.width = width - overflowX + "px";
          ghostElm.style.height = height - overflowY + "px";
        };
        var removeElement = function(elm) {
          if (elm && elm.parentNode) {
            elm.parentNode.removeChild(elm);
          }
        };
        var isLeftMouseButtonPressed = function(e2) {
          return e2.button === 0;
        };
        var applyRelPos = function(state, position) {
          return {
            pageX: position.pageX - state.relX,
            pageY: position.pageY + 5
          };
        };
        var start4 = function(state, editor) {
          return function(e2) {
            if (isLeftMouseButtonPressed(e2)) {
              var ceElm = find$3(editor.dom.getParents(e2.target), or(isContentEditableFalse$1, isContentEditableTrue$1)).getOr(null);
              if (isDraggable(editor.getBody(), ceElm)) {
                var elmPos = editor.dom.getPos(ceElm);
                var bodyElm = editor.getBody();
                var docElm = editor.getDoc().documentElement;
                state.set({
                  element: ceElm,
                  dragging: false,
                  screenX: e2.screenX,
                  screenY: e2.screenY,
                  maxX: (editor.inline ? bodyElm.scrollWidth : docElm.offsetWidth) - 2,
                  maxY: (editor.inline ? bodyElm.scrollHeight : docElm.offsetHeight) - 2,
                  relX: e2.pageX - elmPos.x,
                  relY: e2.pageY - elmPos.y,
                  width: ceElm.offsetWidth,
                  height: ceElm.offsetHeight,
                  ghost: createGhost(editor, ceElm, ceElm.offsetWidth, ceElm.offsetHeight)
                });
              }
            }
          };
        };
        var move = function(state, editor) {
          var throttledPlaceCaretAt = Delay.throttle(function(clientX, clientY) {
            editor._selectionOverrides.hideFakeCaret();
            editor.selection.placeCaretAt(clientX, clientY);
          }, 0);
          editor.on("remove", throttledPlaceCaretAt.stop);
          return function(e2) {
            return state.on(function(state2) {
              var movement = Math.max(Math.abs(e2.screenX - state2.screenX), Math.abs(e2.screenY - state2.screenY));
              if (!state2.dragging && movement > 10) {
                var args = editor.fire("dragstart", { target: state2.element });
                if (args.isDefaultPrevented()) {
                  return;
                }
                state2.dragging = true;
                editor.focus();
              }
              if (state2.dragging) {
                var targetPos = applyRelPos(state2, calc(editor, e2));
                appendGhostToBody(state2.ghost, editor.getBody());
                moveGhost(state2.ghost, targetPos, state2.width, state2.height, state2.maxX, state2.maxY);
                throttledPlaceCaretAt(e2.clientX, e2.clientY);
              }
            });
          };
        };
        var getRawTarget = function(selection) {
          var rng = selection.getSel().getRangeAt(0);
          var startContainer = rng.startContainer;
          return startContainer.nodeType === 3 ? startContainer.parentNode : startContainer;
        };
        var drop = function(state, editor) {
          return function(e2) {
            state.on(function(state2) {
              if (state2.dragging) {
                if (isValidDropTarget(editor, getRawTarget(editor.selection), state2.element)) {
                  var targetClone_1 = cloneElement(state2.element);
                  var args = editor.fire("drop", {
                    clientX: e2.clientX,
                    clientY: e2.clientY
                  });
                  if (!args.isDefaultPrevented()) {
                    editor.undoManager.transact(function() {
                      removeElement(state2.element);
                      editor.insertContent(editor.dom.getOuterHTML(targetClone_1));
                      editor._selectionOverrides.hideFakeCaret();
                    });
                  }
                }
                editor.fire("dragend");
              }
            });
            removeDragState(state);
          };
        };
        var stop = function(state, editor) {
          return function() {
            state.on(function(state2) {
              if (state2.dragging) {
                editor.fire("dragend");
              }
            });
            removeDragState(state);
          };
        };
        var removeDragState = function(state) {
          state.on(function(state2) {
            removeElement(state2.ghost);
          });
          state.clear();
        };
        var bindFakeDragEvents = function(editor) {
          var state = value();
          var pageDom = DOMUtils.DOM;
          var rootDocument = document;
          var dragStartHandler = start4(state, editor);
          var dragHandler = move(state, editor);
          var dropHandler = drop(state, editor);
          var dragEndHandler = stop(state, editor);
          editor.on("mousedown", dragStartHandler);
          editor.on("mousemove", dragHandler);
          editor.on("mouseup", dropHandler);
          pageDom.bind(rootDocument, "mousemove", dragHandler);
          pageDom.bind(rootDocument, "mouseup", dragEndHandler);
          editor.on("remove", function() {
            pageDom.unbind(rootDocument, "mousemove", dragHandler);
            pageDom.unbind(rootDocument, "mouseup", dragEndHandler);
          });
          editor.on("keydown", function(e2) {
            if (e2.keyCode === VK.ESC) {
              dragEndHandler();
            }
          });
        };
        var blockIeDrop = function(editor) {
          editor.on("drop", function(e2) {
            var realTarget = typeof e2.clientX !== "undefined" ? editor.getDoc().elementFromPoint(e2.clientX, e2.clientY) : null;
            if (isContentEditableFalse$1(realTarget) || editor.dom.getContentEditableParent(realTarget) === "false") {
              e2.preventDefault();
            }
          });
        };
        var blockUnsupportedFileDrop = function(editor) {
          var preventFileDrop = function(e2) {
            if (!e2.isDefaultPrevented()) {
              var dataTransfer = e2.dataTransfer;
              if (dataTransfer && (contains$3(dataTransfer.types, "Files") || dataTransfer.files.length > 0)) {
                e2.preventDefault();
                if (e2.type === "drop") {
                  displayError(editor, "Dropped file type is not supported");
                }
              }
            }
          };
          var preventFileDropIfUIElement = function(e2) {
            if (isUIElement(editor, e2.target)) {
              preventFileDrop(e2);
            }
          };
          var setup2 = function() {
            var pageDom = DOMUtils.DOM;
            var dom2 = editor.dom;
            var doc2 = document;
            var editorRoot = editor.inline ? editor.getBody() : editor.getDoc();
            var eventNames = [
              "drop",
              "dragover"
            ];
            each$k(eventNames, function(name2) {
              pageDom.bind(doc2, name2, preventFileDropIfUIElement);
              dom2.bind(editorRoot, name2, preventFileDrop);
            });
            editor.on("remove", function() {
              each$k(eventNames, function(name2) {
                pageDom.unbind(doc2, name2, preventFileDropIfUIElement);
                dom2.unbind(editorRoot, name2, preventFileDrop);
              });
            });
          };
          editor.on("init", function() {
            Delay.setEditorTimeout(editor, setup2, 0);
          });
        };
        var init$2 = function(editor) {
          bindFakeDragEvents(editor);
          blockIeDrop(editor);
          if (shouldBlockUnsupportedDrop(editor)) {
            blockUnsupportedFileDrop(editor);
          }
        };
        var setup$1 = function(editor) {
          var renderFocusCaret = first(function() {
            if (!editor.removed && editor.getBody().contains(document.activeElement)) {
              var rng = editor.selection.getRng();
              if (rng.collapsed) {
                var caretRange = renderRangeCaret(editor, rng, false);
                editor.selection.setRng(caretRange);
              }
            }
          }, 0);
          editor.on("focus", function() {
            renderFocusCaret.throttle();
          });
          editor.on("blur", function() {
            renderFocusCaret.cancel();
          });
        };
        var setup = function(editor) {
          editor.on("init", function() {
            editor.on("focusin", function(e2) {
              var target = e2.target;
              if (isMedia$2(target)) {
                var ceRoot = getContentEditableRoot$1(editor.getBody(), target);
                var node = isContentEditableFalse$b(ceRoot) ? ceRoot : target;
                if (editor.selection.getNode() !== node) {
                  selectNode(editor, node).each(function(rng) {
                    return editor.selection.setRng(rng);
                  });
                }
              }
            });
          });
        };
        var isContentEditableTrue = isContentEditableTrue$4;
        var isContentEditableFalse = isContentEditableFalse$b;
        var getContentEditableRoot = function(editor, node) {
          return getContentEditableRoot$1(editor.getBody(), node);
        };
        var SelectionOverrides = function(editor) {
          var selection = editor.selection, dom2 = editor.dom;
          var isBlock2 = dom2.isBlock;
          var rootNode = editor.getBody();
          var fakeCaret = FakeCaret(editor, rootNode, isBlock2, function() {
            return hasFocus(editor);
          });
          var realSelectionId = "sel-" + dom2.uniqueId();
          var elementSelectionAttr = "data-mce-selected";
          var selectedElement;
          var isFakeSelectionElement = function(node) {
            return dom2.hasClass(node, "mce-offscreen-selection");
          };
          var isFakeSelectionTargetElement = function(node) {
            return node !== rootNode && (isContentEditableFalse(node) || isMedia$2(node)) && dom2.isChildOf(node, rootNode);
          };
          var isNearFakeSelectionElement = function(pos) {
            return isBeforeContentEditableFalse(pos) || isAfterContentEditableFalse(pos) || isBeforeMedia(pos) || isAfterMedia(pos);
          };
          var getRealSelectionElement = function() {
            var container = dom2.get(realSelectionId);
            return container ? container.getElementsByTagName("*")[0] : container;
          };
          var setRange = function(range2) {
            if (range2) {
              selection.setRng(range2);
            }
          };
          var getRange = selection.getRng;
          var showCaret2 = function(direction, node, before2, scrollIntoView) {
            if (scrollIntoView === void 0) {
              scrollIntoView = true;
            }
            var e2 = editor.fire("ShowCaret", {
              target: node,
              direction,
              before: before2
            });
            if (e2.isDefaultPrevented()) {
              return null;
            }
            if (scrollIntoView) {
              selection.scrollIntoView(node, direction === -1);
            }
            return fakeCaret.show(before2, node);
          };
          var showBlockCaretContainer2 = function(blockCaretContainer) {
            if (blockCaretContainer.hasAttribute("data-mce-caret")) {
              showCaretContainerBlock(blockCaretContainer);
              setRange(getRange());
              selection.scrollIntoView(blockCaretContainer);
            }
          };
          var registerEvents2 = function() {
            editor.on("mouseup", function(e2) {
              var range2 = getRange();
              if (range2.collapsed && isXYInContentArea(editor, e2.clientX, e2.clientY)) {
                renderCaretAtRange(editor, range2, false).each(setRange);
              }
            });
            editor.on("click", function(e2) {
              var contentEditableRoot = getContentEditableRoot(editor, e2.target);
              if (contentEditableRoot) {
                if (isContentEditableFalse(contentEditableRoot)) {
                  e2.preventDefault();
                  editor.focus();
                }
                if (isContentEditableTrue(contentEditableRoot)) {
                  if (dom2.isChildOf(contentEditableRoot, selection.getNode())) {
                    removeElementSelection();
                  }
                }
              }
            });
            editor.on("blur NewBlock", removeElementSelection);
            editor.on("ResizeWindow FullscreenStateChanged", fakeCaret.reposition);
            var hasNormalCaretPosition = function(elm) {
              var start5 = elm.firstChild;
              if (isNullable(start5)) {
                return false;
              }
              var startPos = CaretPosition.before(start5);
              if (isBr$5(startPos.getNode()) && elm.childNodes.length === 1) {
                return !isNearFakeSelectionElement(startPos);
              } else {
                var caretWalker = CaretWalker(elm);
                var newPos = caretWalker.next(startPos);
                return newPos && !isNearFakeSelectionElement(newPos);
              }
            };
            var isInSameBlock2 = function(node1, node2) {
              var block1 = dom2.getParent(node1, isBlock2);
              var block2 = dom2.getParent(node2, isBlock2);
              return block1 === block2;
            };
            var hasBetterMouseTarget = function(targetNode, caretNode) {
              var targetBlock = dom2.getParent(targetNode, isBlock2);
              var caretBlock = dom2.getParent(caretNode, isBlock2);
              if (isNullable(targetBlock)) {
                return false;
              }
              if (targetNode !== caretBlock && dom2.isChildOf(targetBlock, caretBlock) && isContentEditableFalse(getContentEditableRoot(editor, targetBlock)) === false) {
                return true;
              }
              return !dom2.isChildOf(caretBlock, targetBlock) && !isInSameBlock2(targetBlock, caretBlock) && hasNormalCaretPosition(targetBlock);
            };
            editor.on("tap", function(e2) {
              var targetElm = e2.target;
              var contentEditableRoot = getContentEditableRoot(editor, targetElm);
              if (isContentEditableFalse(contentEditableRoot)) {
                e2.preventDefault();
                selectNode(editor, contentEditableRoot).each(setElementSelection);
              } else if (isFakeSelectionTargetElement(targetElm)) {
                selectNode(editor, targetElm).each(setElementSelection);
              }
            }, true);
            editor.on("mousedown", function(e2) {
              var targetElm = e2.target;
              if (targetElm !== rootNode && targetElm.nodeName !== "HTML" && !dom2.isChildOf(targetElm, rootNode)) {
                return;
              }
              if (isXYInContentArea(editor, e2.clientX, e2.clientY) === false) {
                return;
              }
              var contentEditableRoot = getContentEditableRoot(editor, targetElm);
              if (contentEditableRoot) {
                if (isContentEditableFalse(contentEditableRoot)) {
                  e2.preventDefault();
                  selectNode(editor, contentEditableRoot).each(setElementSelection);
                } else {
                  removeElementSelection();
                  if (!(isContentEditableTrue(contentEditableRoot) && e2.shiftKey) && !isXYWithinRange(e2.clientX, e2.clientY, selection.getRng())) {
                    hideFakeCaret();
                    selection.placeCaretAt(e2.clientX, e2.clientY);
                  }
                }
              } else if (isFakeSelectionTargetElement(targetElm)) {
                selectNode(editor, targetElm).each(setElementSelection);
              } else if (isFakeCaretTarget(targetElm) === false) {
                removeElementSelection();
                hideFakeCaret();
                var fakeCaretInfo = closestFakeCaret(rootNode, e2.clientX, e2.clientY);
                if (fakeCaretInfo) {
                  if (!hasBetterMouseTarget(targetElm, fakeCaretInfo.node)) {
                    e2.preventDefault();
                    var range2 = showCaret2(1, fakeCaretInfo.node, fakeCaretInfo.before, false);
                    setRange(range2);
                    editor.getBody().focus();
                  }
                }
              }
            });
            editor.on("keypress", function(e2) {
              if (VK.modifierPressed(e2)) {
                return;
              }
              if (isContentEditableFalse(selection.getNode())) {
                e2.preventDefault();
              }
            });
            editor.on("GetSelectionRange", function(e2) {
              var rng = e2.range;
              if (selectedElement) {
                if (!selectedElement.parentNode) {
                  selectedElement = null;
                  return;
                }
                rng = rng.cloneRange();
                rng.selectNode(selectedElement);
                e2.range = rng;
              }
            });
            editor.on("SetSelectionRange", function(e2) {
              e2.range = normalizeShortEndedElementSelection(e2.range);
              var rng = setElementSelection(e2.range, e2.forward);
              if (rng) {
                e2.range = rng;
              }
            });
            var isPasteBin = function(node) {
              return node.id === "mcepastebin";
            };
            editor.on("AfterSetSelectionRange", function(e2) {
              var rng = e2.range;
              var parentNode = rng.startContainer.parentNode;
              if (!isRangeInCaretContainer(rng) && !isPasteBin(parentNode)) {
                hideFakeCaret();
              }
              if (!isFakeSelectionElement(parentNode)) {
                removeElementSelection();
              }
            });
            editor.on("copy", function(e2) {
              var clipboardData = e2.clipboardData;
              if (!e2.isDefaultPrevented() && e2.clipboardData && !Env.ie) {
                var realSelectionElement = getRealSelectionElement();
                if (realSelectionElement) {
                  e2.preventDefault();
                  clipboardData.clearData();
                  clipboardData.setData("text/html", realSelectionElement.outerHTML);
                  clipboardData.setData("text/plain", realSelectionElement.outerText || realSelectionElement.innerText);
                }
              }
            });
            init$2(editor);
            setup$1(editor);
            setup(editor);
          };
          var isWithinCaretContainer = function(node) {
            return isCaretContainer$2(node) || startsWithCaretContainer$1(node) || endsWithCaretContainer$1(node);
          };
          var isRangeInCaretContainer = function(rng) {
            return isWithinCaretContainer(rng.startContainer) || isWithinCaretContainer(rng.endContainer);
          };
          var normalizeShortEndedElementSelection = function(rng) {
            var shortEndedElements = editor.schema.getShortEndedElements();
            var newRng = dom2.createRng();
            var startContainer = rng.startContainer;
            var startOffset = rng.startOffset;
            var endContainer = rng.endContainer;
            var endOffset = rng.endOffset;
            if (has$2(shortEndedElements, startContainer.nodeName.toLowerCase())) {
              if (startOffset === 0) {
                newRng.setStartBefore(startContainer);
              } else {
                newRng.setStartAfter(startContainer);
              }
            } else {
              newRng.setStart(startContainer, startOffset);
            }
            if (has$2(shortEndedElements, endContainer.nodeName.toLowerCase())) {
              if (endOffset === 0) {
                newRng.setEndBefore(endContainer);
              } else {
                newRng.setEndAfter(endContainer);
              }
            } else {
              newRng.setEnd(endContainer, endOffset);
            }
            return newRng;
          };
          var setupOffscreenSelection = function(node, targetClone, origTargetClone) {
            var $2 = editor.$;
            var $realSelectionContainer = descendant(SugarElement.fromDom(editor.getBody()), "#" + realSelectionId).fold(function() {
              return $2([]);
            }, function(elm) {
              return $2([elm.dom]);
            });
            if ($realSelectionContainer.length === 0) {
              $realSelectionContainer = $2('<div data-mce-bogus="all" class="mce-offscreen-selection"></div>').attr("id", realSelectionId);
              $realSelectionContainer.appendTo(editor.getBody());
            }
            var newRange = dom2.createRng();
            if (targetClone === origTargetClone && Env.ie) {
              $realSelectionContainer.empty().append('<p style="font-size: 0" data-mce-bogus="all">\xA0</p>').append(targetClone);
              newRange.setStartAfter($realSelectionContainer[0].firstChild.firstChild);
              newRange.setEndAfter(targetClone);
            } else {
              $realSelectionContainer.empty().append(nbsp).append(targetClone).append(nbsp);
              newRange.setStart($realSelectionContainer[0].firstChild, 1);
              newRange.setEnd($realSelectionContainer[0].lastChild, 0);
            }
            $realSelectionContainer.css({ top: dom2.getPos(node, editor.getBody()).y });
            $realSelectionContainer[0].focus();
            var sel = selection.getSel();
            sel.removeAllRanges();
            sel.addRange(newRange);
            return newRange;
          };
          var selectElement = function(elm) {
            var targetClone = elm.cloneNode(true);
            var e2 = editor.fire("ObjectSelected", {
              target: elm,
              targetClone
            });
            if (e2.isDefaultPrevented()) {
              return null;
            }
            var range2 = setupOffscreenSelection(elm, e2.targetClone, targetClone);
            var nodeElm = SugarElement.fromDom(elm);
            each$k(descendants(SugarElement.fromDom(editor.getBody()), "*[data-mce-selected]"), function(elm2) {
              if (!eq2(nodeElm, elm2)) {
                remove$6(elm2, elementSelectionAttr);
              }
            });
            if (!dom2.getAttrib(elm, elementSelectionAttr)) {
              elm.setAttribute(elementSelectionAttr, "1");
            }
            selectedElement = elm;
            hideFakeCaret();
            return range2;
          };
          var setElementSelection = function(range2, forward) {
            if (!range2) {
              return null;
            }
            if (range2.collapsed) {
              if (!isRangeInCaretContainer(range2)) {
                var dir2 = forward ? 1 : -1;
                var caretPosition = getNormalizedRangeEndPoint(dir2, rootNode, range2);
                var beforeNode = caretPosition.getNode(!forward);
                if (isFakeCaretTarget(beforeNode)) {
                  return showCaret2(dir2, beforeNode, forward ? !caretPosition.isAtEnd() : false, false);
                }
                var afterNode = caretPosition.getNode(forward);
                if (isFakeCaretTarget(afterNode)) {
                  return showCaret2(dir2, afterNode, forward ? false : !caretPosition.isAtEnd(), false);
                }
              }
              return null;
            }
            var startContainer = range2.startContainer;
            var startOffset = range2.startOffset;
            var endOffset = range2.endOffset;
            if (startContainer.nodeType === 3 && startOffset === 0 && isContentEditableFalse(startContainer.parentNode)) {
              startContainer = startContainer.parentNode;
              startOffset = dom2.nodeIndex(startContainer);
              startContainer = startContainer.parentNode;
            }
            if (startContainer.nodeType !== 1) {
              return null;
            }
            if (endOffset === startOffset + 1 && startContainer === range2.endContainer) {
              var node = startContainer.childNodes[startOffset];
              if (isFakeSelectionTargetElement(node)) {
                return selectElement(node);
              }
            }
            return null;
          };
          var removeElementSelection = function() {
            if (selectedElement) {
              selectedElement.removeAttribute(elementSelectionAttr);
            }
            descendant(SugarElement.fromDom(editor.getBody()), "#" + realSelectionId).each(remove$7);
            selectedElement = null;
          };
          var destroy2 = function() {
            fakeCaret.destroy();
            selectedElement = null;
          };
          var hideFakeCaret = function() {
            fakeCaret.hide();
          };
          if (Env.ceFalse && !isRtc(editor)) {
            registerEvents2();
          }
          return {
            showCaret: showCaret2,
            showBlockCaretContainer: showBlockCaretContainer2,
            hideFakeCaret,
            destroy: destroy2
          };
        };
        var Quirks = function(editor) {
          var each3 = Tools.each;
          var BACKSPACE = VK.BACKSPACE, DELETE2 = VK.DELETE, dom2 = editor.dom, selection = editor.selection, parser = editor.parser;
          var isGecko = Env.gecko, isIE2 = Env.ie, isWebKit = Env.webkit;
          var mceInternalUrlPrefix = "data:text/mce-internal,";
          var mceInternalDataType = isIE2 ? "Text" : "URL";
          var setEditorCommandState2 = function(cmd, state) {
            try {
              editor.getDoc().execCommand(cmd, false, state);
            } catch (ex) {
            }
          };
          var isDefaultPrevented = function(e2) {
            return e2.isDefaultPrevented();
          };
          var setMceInternalContent = function(e2) {
            var selectionHtml, internalContent;
            if (e2.dataTransfer) {
              if (editor.selection.isCollapsed() && e2.target.tagName === "IMG") {
                selection.select(e2.target);
              }
              selectionHtml = editor.selection.getContent();
              if (selectionHtml.length > 0) {
                internalContent = mceInternalUrlPrefix + escape(editor.id) + "," + escape(selectionHtml);
                e2.dataTransfer.setData(mceInternalDataType, internalContent);
              }
            }
          };
          var getMceInternalContent = function(e2) {
            var internalContent;
            if (e2.dataTransfer) {
              internalContent = e2.dataTransfer.getData(mceInternalDataType);
              if (internalContent && internalContent.indexOf(mceInternalUrlPrefix) >= 0) {
                internalContent = internalContent.substr(mceInternalUrlPrefix.length).split(",");
                return {
                  id: unescape(internalContent[0]),
                  html: unescape(internalContent[1])
                };
              }
            }
            return null;
          };
          var insertClipboardContents = function(content, internal) {
            if (editor.queryCommandSupported("mceInsertClipboardContent")) {
              editor.execCommand("mceInsertClipboardContent", false, {
                content,
                internal
              });
            } else {
              editor.execCommand("mceInsertContent", false, content);
            }
          };
          var emptyEditorWhenDeleting = function() {
            var serializeRng = function(rng) {
              var body = dom2.create("body");
              var contents = rng.cloneContents();
              body.appendChild(contents);
              return selection.serializer.serialize(body, { format: "html" });
            };
            var allContentsSelected = function(rng) {
              var selection2 = serializeRng(rng);
              var allRng = dom2.createRng();
              allRng.selectNode(editor.getBody());
              var allSelection = serializeRng(allRng);
              return selection2 === allSelection;
            };
            editor.on("keydown", function(e2) {
              var keyCode = e2.keyCode;
              var isCollapsed, body;
              if (!isDefaultPrevented(e2) && (keyCode === DELETE2 || keyCode === BACKSPACE)) {
                isCollapsed = editor.selection.isCollapsed();
                body = editor.getBody();
                if (isCollapsed && !dom2.isEmpty(body)) {
                  return;
                }
                if (!isCollapsed && !allContentsSelected(editor.selection.getRng())) {
                  return;
                }
                e2.preventDefault();
                editor.setContent("");
                if (body.firstChild && dom2.isBlock(body.firstChild)) {
                  editor.selection.setCursorLocation(body.firstChild, 0);
                } else {
                  editor.selection.setCursorLocation(body, 0);
                }
                editor.nodeChanged();
              }
            });
          };
          var selectAll = function() {
            editor.shortcuts.add("meta+a", null, "SelectAll");
          };
          var documentElementEditingFocus = function() {
            if (!editor.inline) {
              dom2.bind(editor.getDoc(), "mousedown mouseup", function(e2) {
                var rng;
                if (e2.target === editor.getDoc().documentElement) {
                  rng = selection.getRng();
                  editor.getBody().focus();
                  if (e2.type === "mousedown") {
                    if (isCaretContainer$2(rng.startContainer)) {
                      return;
                    }
                    selection.placeCaretAt(e2.clientX, e2.clientY);
                  } else {
                    selection.setRng(rng);
                  }
                }
              });
            }
          };
          var removeHrOnBackspace = function() {
            editor.on("keydown", function(e2) {
              if (!isDefaultPrevented(e2) && e2.keyCode === BACKSPACE) {
                if (!editor.getBody().getElementsByTagName("hr").length) {
                  return;
                }
                if (selection.isCollapsed() && selection.getRng().startOffset === 0) {
                  var node = selection.getNode();
                  var previousSibling = node.previousSibling;
                  if (node.nodeName === "HR") {
                    dom2.remove(node);
                    e2.preventDefault();
                    return;
                  }
                  if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === "hr") {
                    dom2.remove(previousSibling);
                    e2.preventDefault();
                  }
                }
              }
            });
          };
          var focusBody2 = function() {
            if (!Range.prototype.getClientRects) {
              editor.on("mousedown", function(e2) {
                if (!isDefaultPrevented(e2) && e2.target.nodeName === "HTML") {
                  var body_1 = editor.getBody();
                  body_1.blur();
                  Delay.setEditorTimeout(editor, function() {
                    body_1.focus();
                  });
                }
              });
            }
          };
          var selectControlElements = function() {
            editor.on("click", function(e2) {
              var target = e2.target;
              if (/^(IMG|HR)$/.test(target.nodeName) && dom2.getContentEditableParent(target) !== "false") {
                e2.preventDefault();
                editor.selection.select(target);
                editor.nodeChanged();
              }
              if (target.nodeName === "A" && dom2.hasClass(target, "mce-item-anchor")) {
                e2.preventDefault();
                selection.select(target);
              }
            });
          };
          var removeStylesWhenDeletingAcrossBlockElements = function() {
            var getAttributeApplyFunction = function() {
              var template = dom2.getAttribs(selection.getStart().cloneNode(false));
              return function() {
                var target = selection.getStart();
                if (target !== editor.getBody()) {
                  dom2.setAttrib(target, "style", null);
                  each3(template, function(attr) {
                    target.setAttributeNode(attr.cloneNode(true));
                  });
                }
              };
            };
            var isSelectionAcrossElements = function() {
              return !selection.isCollapsed() && dom2.getParent(selection.getStart(), dom2.isBlock) !== dom2.getParent(selection.getEnd(), dom2.isBlock);
            };
            editor.on("keypress", function(e2) {
              var applyAttributes2;
              if (!isDefaultPrevented(e2) && (e2.keyCode === 8 || e2.keyCode === 46) && isSelectionAcrossElements()) {
                applyAttributes2 = getAttributeApplyFunction();
                editor.getDoc().execCommand("delete", false, null);
                applyAttributes2();
                e2.preventDefault();
                return false;
              }
            });
            dom2.bind(editor.getDoc(), "cut", function(e2) {
              var applyAttributes2;
              if (!isDefaultPrevented(e2) && isSelectionAcrossElements()) {
                applyAttributes2 = getAttributeApplyFunction();
                Delay.setEditorTimeout(editor, function() {
                  applyAttributes2();
                });
              }
            });
          };
          var disableBackspaceIntoATable = function() {
            editor.on("keydown", function(e2) {
              if (!isDefaultPrevented(e2) && e2.keyCode === BACKSPACE) {
                if (selection.isCollapsed() && selection.getRng().startOffset === 0) {
                  var previousSibling = selection.getNode().previousSibling;
                  if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === "table") {
                    e2.preventDefault();
                    return false;
                  }
                }
              }
            });
          };
          var removeBlockQuoteOnBackSpace = function() {
            editor.on("keydown", function(e2) {
              var rng, parent2;
              if (isDefaultPrevented(e2) || e2.keyCode !== VK.BACKSPACE) {
                return;
              }
              rng = selection.getRng();
              var container = rng.startContainer;
              var offset2 = rng.startOffset;
              var root = dom2.getRoot();
              parent2 = container;
              if (!rng.collapsed || offset2 !== 0) {
                return;
              }
              while (parent2 && parent2.parentNode && parent2.parentNode.firstChild === parent2 && parent2.parentNode !== root) {
                parent2 = parent2.parentNode;
              }
              if (parent2.tagName === "BLOCKQUOTE") {
                editor.formatter.toggle("blockquote", null, parent2);
                rng = dom2.createRng();
                rng.setStart(container, 0);
                rng.setEnd(container, 0);
                selection.setRng(rng);
              }
            });
          };
          var setGeckoEditingOptions = function() {
            var setOpts = function() {
              setEditorCommandState2("StyleWithCSS", false);
              setEditorCommandState2("enableInlineTableEditing", false);
              if (!getObjectResizing(editor)) {
                setEditorCommandState2("enableObjectResizing", false);
              }
            };
            if (!isReadOnly$1(editor)) {
              editor.on("BeforeExecCommand mousedown", setOpts);
            }
          };
          var addBrAfterLastLinks = function() {
            var fixLinks = function() {
              each3(dom2.select("a"), function(node) {
                var parentNode = node.parentNode;
                var root = dom2.getRoot();
                if (parentNode.lastChild === node) {
                  while (parentNode && !dom2.isBlock(parentNode)) {
                    if (parentNode.parentNode.lastChild !== parentNode || parentNode === root) {
                      return;
                    }
                    parentNode = parentNode.parentNode;
                  }
                  dom2.add(parentNode, "br", { "data-mce-bogus": 1 });
                }
              });
            };
            editor.on("SetContent ExecCommand", function(e2) {
              if (e2.type === "setcontent" || e2.command === "mceInsertLink") {
                fixLinks();
              }
            });
          };
          var setDefaultBlockType = function() {
            if (getForcedRootBlock(editor)) {
              editor.on("init", function() {
                setEditorCommandState2("DefaultParagraphSeparator", getForcedRootBlock(editor));
              });
            }
          };
          var normalizeSelection2 = function() {
            editor.on("keyup focusin mouseup", function(e2) {
              if (!VK.modifierPressed(e2)) {
                selection.normalize();
              }
            }, true);
          };
          var showBrokenImageIcon = function() {
            editor.contentStyles.push("img:-moz-broken {-moz-force-broken-image-icon:1;min-width:24px;min-height:24px}");
          };
          var restoreFocusOnKeyDown = function() {
            if (!editor.inline) {
              editor.on("keydown", function() {
                if (document.activeElement === document.body) {
                  editor.getWin().focus();
                }
              });
            }
          };
          var bodyHeight = function() {
            if (!editor.inline) {
              editor.contentStyles.push("body {min-height: 150px}");
              editor.on("click", function(e2) {
                var rng;
                if (e2.target.nodeName === "HTML") {
                  if (Env.ie > 11) {
                    editor.getBody().focus();
                    return;
                  }
                  rng = editor.selection.getRng();
                  editor.getBody().focus();
                  editor.selection.setRng(rng);
                  editor.selection.normalize();
                  editor.nodeChanged();
                }
              });
            }
          };
          var blockCmdArrowNavigation = function() {
            if (Env.mac) {
              editor.on("keydown", function(e2) {
                if (VK.metaKeyPressed(e2) && !e2.shiftKey && (e2.keyCode === 37 || e2.keyCode === 39)) {
                  e2.preventDefault();
                  var selection_1 = editor.selection.getSel();
                  selection_1.modify("move", e2.keyCode === 37 ? "backward" : "forward", "lineboundary");
                }
              });
            }
          };
          var disableAutoUrlDetect = function() {
            setEditorCommandState2("AutoUrlDetect", false);
          };
          var tapLinksAndImages = function() {
            editor.on("click", function(e2) {
              var elm = e2.target;
              do {
                if (elm.tagName === "A") {
                  e2.preventDefault();
                  return;
                }
              } while (elm = elm.parentNode);
            });
            editor.contentStyles.push(".mce-content-body {-webkit-touch-callout: none}");
          };
          var blockFormSubmitInsideEditor = function() {
            editor.on("init", function() {
              editor.dom.bind(editor.getBody(), "submit", function(e2) {
                e2.preventDefault();
              });
            });
          };
          var removeAppleInterchangeBrs = function() {
            parser.addNodeFilter("br", function(nodes) {
              var i2 = nodes.length;
              while (i2--) {
                if (nodes[i2].attr("class") === "Apple-interchange-newline") {
                  nodes[i2].remove();
                }
              }
            });
          };
          var ieInternalDragAndDrop = function() {
            editor.on("dragstart", function(e2) {
              setMceInternalContent(e2);
            });
            editor.on("drop", function(e2) {
              if (!isDefaultPrevented(e2)) {
                var internalContent = getMceInternalContent(e2);
                if (internalContent && internalContent.id !== editor.id) {
                  e2.preventDefault();
                  var rng = fromPoint(e2.x, e2.y, editor.getDoc());
                  selection.setRng(rng);
                  insertClipboardContents(internalContent.html, true);
                }
              }
            });
          };
          var refreshContentEditable = noop3;
          var isHidden = function() {
            if (!isGecko || editor.removed) {
              return false;
            }
            var sel = editor.selection.getSel();
            return !sel || !sel.rangeCount || sel.rangeCount === 0;
          };
          var setupRtc = function() {
            if (isWebKit) {
              documentElementEditingFocus();
              selectControlElements();
              blockFormSubmitInsideEditor();
              selectAll();
              if (Env.iOS) {
                restoreFocusOnKeyDown();
                bodyHeight();
                tapLinksAndImages();
              }
            }
            if (isGecko) {
              focusBody2();
              setGeckoEditingOptions();
              showBrokenImageIcon();
              blockCmdArrowNavigation();
            }
          };
          var setup2 = function() {
            removeBlockQuoteOnBackSpace();
            emptyEditorWhenDeleting();
            if (!Env.windowsPhone) {
              normalizeSelection2();
            }
            if (isWebKit) {
              documentElementEditingFocus();
              selectControlElements();
              setDefaultBlockType();
              blockFormSubmitInsideEditor();
              disableBackspaceIntoATable();
              removeAppleInterchangeBrs();
              if (Env.iOS) {
                restoreFocusOnKeyDown();
                bodyHeight();
                tapLinksAndImages();
              } else {
                selectAll();
              }
            }
            if (Env.ie >= 11) {
              bodyHeight();
              disableBackspaceIntoATable();
            }
            if (Env.ie) {
              selectAll();
              disableAutoUrlDetect();
              ieInternalDragAndDrop();
            }
            if (isGecko) {
              removeHrOnBackspace();
              focusBody2();
              removeStylesWhenDeletingAcrossBlockElements();
              setGeckoEditingOptions();
              addBrAfterLastLinks();
              showBrokenImageIcon();
              blockCmdArrowNavigation();
              disableBackspaceIntoATable();
            }
          };
          if (isRtc(editor)) {
            setupRtc();
          } else {
            setup2();
          }
          return {
            refreshContentEditable,
            isHidden
          };
        };
        var DOM$6 = DOMUtils.DOM;
        var appendStyle = function(editor, text) {
          var body = SugarElement.fromDom(editor.getBody());
          var container = getStyleContainer(getRootNode(body));
          var style = SugarElement.fromTag("style");
          set$1(style, "type", "text/css");
          append$1(style, SugarElement.fromText(text));
          append$1(container, style);
          editor.on("remove", function() {
            remove$7(style);
          });
        };
        var getRootName = function(editor) {
          return editor.inline ? editor.getElement().nodeName.toLowerCase() : void 0;
        };
        var removeUndefined = function(obj) {
          return filter$3(obj, function(v2) {
            return isUndefined(v2) === false;
          });
        };
        var mkParserSettings = function(editor) {
          var settings = editor.settings;
          var blobCache = editor.editorUpload.blobCache;
          return removeUndefined({
            allow_conditional_comments: settings.allow_conditional_comments,
            allow_html_data_urls: settings.allow_html_data_urls,
            allow_svg_data_urls: settings.allow_svg_data_urls,
            allow_html_in_named_anchor: settings.allow_html_in_named_anchor,
            allow_script_urls: settings.allow_script_urls,
            allow_unsafe_link_target: settings.allow_unsafe_link_target,
            convert_fonts_to_spans: settings.convert_fonts_to_spans,
            fix_list_elements: settings.fix_list_elements,
            font_size_legacy_values: settings.font_size_legacy_values,
            forced_root_block: settings.forced_root_block,
            forced_root_block_attrs: settings.forced_root_block_attrs,
            padd_empty_with_br: settings.padd_empty_with_br,
            preserve_cdata: settings.preserve_cdata,
            remove_trailing_brs: settings.remove_trailing_brs,
            inline_styles: settings.inline_styles,
            root_name: getRootName(editor),
            validate: true,
            blob_cache: blobCache,
            document: editor.getDoc(),
            images_dataimg_filter: settings.images_dataimg_filter
          });
        };
        var mkSerializerSettings = function(editor) {
          var settings = editor.settings;
          return __assign(__assign({}, mkParserSettings(editor)), removeUndefined({
            url_converter: settings.url_converter,
            url_converter_scope: settings.url_converter_scope,
            element_format: settings.element_format,
            entities: settings.entities,
            entity_encoding: settings.entity_encoding,
            indent: settings.indent,
            indent_after: settings.indent_after,
            indent_before: settings.indent_before,
            block_elements: settings.block_elements,
            boolean_attributes: settings.boolean_attributes,
            custom_elements: settings.custom_elements,
            extended_valid_elements: settings.extended_valid_elements,
            invalid_elements: settings.invalid_elements,
            invalid_styles: settings.invalid_styles,
            move_caret_before_on_enter_elements: settings.move_caret_before_on_enter_elements,
            non_empty_elements: settings.non_empty_elements,
            schema: settings.schema,
            self_closing_elements: settings.self_closing_elements,
            short_ended_elements: settings.short_ended_elements,
            special: settings.special,
            text_block_elements: settings.text_block_elements,
            text_inline_elements: settings.text_inline_elements,
            valid_children: settings.valid_children,
            valid_classes: settings.valid_classes,
            valid_elements: settings.valid_elements,
            valid_styles: settings.valid_styles,
            verify_html: settings.verify_html,
            whitespace_elements: settings.whitespace_elements
          }));
        };
        var createParser = function(editor) {
          var parser = DomParser(mkParserSettings(editor), editor.schema);
          parser.addAttributeFilter("src,href,style,tabindex", function(nodes, name2) {
            var i2 = nodes.length, node, value2;
            var dom2 = editor.dom;
            var internalName = "data-mce-" + name2;
            while (i2--) {
              node = nodes[i2];
              value2 = node.attr(name2);
              if (value2 && !node.attr(internalName)) {
                if (value2.indexOf("data:") === 0 || value2.indexOf("blob:") === 0) {
                  continue;
                }
                if (name2 === "style") {
                  value2 = dom2.serializeStyle(dom2.parseStyle(value2), node.name);
                  if (!value2.length) {
                    value2 = null;
                  }
                  node.attr(internalName, value2);
                  node.attr(name2, value2);
                } else if (name2 === "tabindex") {
                  node.attr(internalName, value2);
                  node.attr(name2, null);
                } else {
                  node.attr(internalName, editor.convertURL(value2, name2, node.name));
                }
              }
            }
          });
          parser.addNodeFilter("script", function(nodes) {
            var i2 = nodes.length;
            while (i2--) {
              var node = nodes[i2];
              var type2 = node.attr("type") || "no/type";
              if (type2.indexOf("mce-") !== 0) {
                node.attr("type", "mce-" + type2);
              }
            }
          });
          if (editor.settings.preserve_cdata) {
            parser.addNodeFilter("#cdata", function(nodes) {
              var i2 = nodes.length;
              while (i2--) {
                var node = nodes[i2];
                node.type = 8;
                node.name = "#comment";
                node.value = "[CDATA[" + editor.dom.encode(node.value) + "]]";
              }
            });
          }
          parser.addNodeFilter("p,h1,h2,h3,h4,h5,h6,div", function(nodes) {
            var i2 = nodes.length;
            var nonEmptyElements = editor.schema.getNonEmptyElements();
            while (i2--) {
              var node = nodes[i2];
              if (node.isEmpty(nonEmptyElements) && node.getAll("br").length === 0) {
                node.append(new AstNode("br", 1)).shortEnded = true;
              }
            }
          });
          return parser;
        };
        var autoFocus = function(editor) {
          if (editor.settings.auto_focus) {
            Delay.setEditorTimeout(editor, function() {
              var focusEditor2;
              if (editor.settings.auto_focus === true) {
                focusEditor2 = editor;
              } else {
                focusEditor2 = editor.editorManager.get(editor.settings.auto_focus);
              }
              if (!focusEditor2.destroyed) {
                focusEditor2.focus();
              }
            }, 100);
          }
        };
        var moveSelectionToFirstCaretPosition = function(editor) {
          var root = editor.dom.getRoot();
          if (!editor.inline && (!hasAnyRanges(editor) || editor.selection.getStart(true) === root)) {
            firstPositionIn(root).each(function(pos) {
              var node = pos.getNode();
              var caretPos = isTable$3(node) ? firstPositionIn(node).getOr(pos) : pos;
              if (Env.browser.isIE()) {
                storeNative(editor, caretPos.toRange());
              } else {
                editor.selection.setRng(caretPos.toRange());
              }
            });
          }
        };
        var initEditor = function(editor) {
          editor.bindPendingEventDelegates();
          editor.initialized = true;
          fireInit(editor);
          editor.focus(true);
          moveSelectionToFirstCaretPosition(editor);
          editor.nodeChanged({ initial: true });
          editor.execCallback("init_instance_callback", editor);
          autoFocus(editor);
        };
        var getStyleSheetLoader$1 = function(editor) {
          return editor.inline ? editor.ui.styleSheetLoader : editor.dom.styleSheetLoader;
        };
        var makeStylesheetLoadingPromises = function(editor, css, framedFonts) {
          var promises = [new promiseObj(function(resolve3, reject) {
            return getStyleSheetLoader$1(editor).loadAll(css, resolve3, reject);
          })];
          if (editor.inline) {
            return promises;
          } else {
            return promises.concat([new promiseObj(function(resolve3, reject) {
              return editor.ui.styleSheetLoader.loadAll(framedFonts, resolve3, reject);
            })]);
          }
        };
        var loadContentCss = function(editor) {
          var styleSheetLoader = getStyleSheetLoader$1(editor);
          var fontCss = getFontCss(editor);
          var css = editor.contentCSS;
          var removeCss = function() {
            styleSheetLoader.unloadAll(css);
            if (!editor.inline) {
              editor.ui.styleSheetLoader.unloadAll(fontCss);
            }
          };
          var loaded = function() {
            if (editor.removed) {
              removeCss();
            } else {
              editor.on("remove", removeCss);
            }
          };
          if (editor.contentStyles.length > 0) {
            var contentCssText_1 = "";
            Tools.each(editor.contentStyles, function(style) {
              contentCssText_1 += style + "\r\n";
            });
            editor.dom.addStyle(contentCssText_1);
          }
          var allStylesheets = promiseObj.all(makeStylesheetLoadingPromises(editor, css, fontCss)).then(loaded).catch(loaded);
          if (editor.settings.content_style) {
            appendStyle(editor, editor.settings.content_style);
          }
          return allStylesheets;
        };
        var preInit = function(editor) {
          var settings = editor.settings, doc2 = editor.getDoc(), body = editor.getBody();
          firePreInit(editor);
          if (!settings.browser_spellcheck && !settings.gecko_spellcheck) {
            doc2.body.spellcheck = false;
            DOM$6.setAttrib(body, "spellcheck", "false");
          }
          editor.quirks = Quirks(editor);
          firePostRender(editor);
          var directionality = getDirectionality(editor);
          if (directionality !== void 0) {
            body.dir = directionality;
          }
          if (settings.protect) {
            editor.on("BeforeSetContent", function(e2) {
              Tools.each(settings.protect, function(pattern) {
                e2.content = e2.content.replace(pattern, function(str) {
                  return "<!--mce:protected " + escape(str) + "-->";
                });
              });
            });
          }
          editor.on("SetContent", function() {
            editor.addVisual(editor.getBody());
          });
          editor.on("compositionstart compositionend", function(e2) {
            editor.composing = e2.type === "compositionstart";
          });
        };
        var loadInitialContent = function(editor) {
          if (!isRtc(editor)) {
            editor.load({
              initial: true,
              format: "html"
            });
          }
          editor.startContent = editor.getContent({ format: "raw" });
        };
        var initEditorWithInitialContent = function(editor) {
          if (editor.removed !== true) {
            loadInitialContent(editor);
            initEditor(editor);
          }
        };
        var initContentBody = function(editor, skipWrite) {
          var settings = editor.settings;
          var targetElm = editor.getElement();
          var doc2 = editor.getDoc();
          if (!settings.inline) {
            editor.getElement().style.visibility = editor.orgVisibility;
          }
          if (!skipWrite && !editor.inline) {
            doc2.open();
            doc2.write(editor.iframeHTML);
            doc2.close();
          }
          if (editor.inline) {
            DOM$6.addClass(targetElm, "mce-content-body");
            editor.contentDocument = doc2 = document;
            editor.contentWindow = window;
            editor.bodyElement = targetElm;
            editor.contentAreaContainer = targetElm;
          }
          var body = editor.getBody();
          body.disabled = true;
          editor.readonly = !!settings.readonly;
          if (!editor.readonly) {
            if (editor.inline && DOM$6.getStyle(body, "position", true) === "static") {
              body.style.position = "relative";
            }
            body.contentEditable = editor.getParam("content_editable_state", true);
          }
          body.disabled = false;
          editor.editorUpload = EditorUpload(editor);
          editor.schema = Schema(settings);
          editor.dom = DOMUtils(doc2, {
            keep_values: true,
            url_converter: editor.convertURL,
            url_converter_scope: editor,
            hex_colors: settings.force_hex_style_colors,
            update_styles: true,
            root_element: editor.inline ? editor.getBody() : null,
            collect: function() {
              return editor.inline;
            },
            schema: editor.schema,
            contentCssCors: shouldUseContentCssCors(editor),
            referrerPolicy: getReferrerPolicy(editor),
            onSetAttrib: function(e2) {
              editor.fire("SetAttrib", e2);
            }
          });
          editor.parser = createParser(editor);
          editor.serializer = DomSerializer(mkSerializerSettings(editor), editor);
          editor.selection = EditorSelection(editor.dom, editor.getWin(), editor.serializer, editor);
          editor.annotator = Annotator(editor);
          editor.formatter = Formatter(editor);
          editor.undoManager = UndoManager(editor);
          editor._nodeChangeDispatcher = new NodeChange(editor);
          editor._selectionOverrides = SelectionOverrides(editor);
          setup$e(editor);
          setup$3(editor);
          if (!isRtc(editor)) {
            setup$2(editor);
          }
          var caret = setup$4(editor);
          setup$f(editor, caret);
          setup$d(editor);
          setup$g(editor);
          var setupRtcThunk = setup$i(editor);
          preInit(editor);
          setupRtcThunk.fold(function() {
            loadContentCss(editor).then(function() {
              return initEditorWithInitialContent(editor);
            });
          }, function(setupRtc) {
            editor.setProgressState(true);
            loadContentCss(editor).then(function() {
              setupRtc().then(function(_rtcMode) {
                editor.setProgressState(false);
                initEditorWithInitialContent(editor);
              }, function(err) {
                editor.notificationManager.open({
                  type: "error",
                  text: String(err)
                });
                initEditorWithInitialContent(editor);
              });
            });
          });
        };
        var DOM$5 = DOMUtils.DOM;
        var relaxDomain = function(editor, ifr) {
          if (document.domain !== window.location.hostname && Env.browser.isIE()) {
            var bodyUuid = uuid2("mce");
            editor[bodyUuid] = function() {
              initContentBody(editor);
            };
            var domainRelaxUrl = 'javascript:(function(){document.open();document.domain="' + document.domain + '";var ed = window.parent.tinymce.get("' + editor.id + '");document.write(ed.iframeHTML);document.close();ed.' + bodyUuid + "(true);})()";
            DOM$5.setAttrib(ifr, "src", domainRelaxUrl);
            return true;
          }
          return false;
        };
        var createIframeElement = function(id2, title, height, customAttrs) {
          var iframe = SugarElement.fromTag("iframe");
          setAll$1(iframe, customAttrs);
          setAll$1(iframe, {
            id: id2 + "_ifr",
            frameBorder: "0",
            allowTransparency: "true",
            title
          });
          add$1(iframe, "tox-edit-area__iframe");
          return iframe;
        };
        var getIframeHtml = function(editor) {
          var iframeHTML = getDocType(editor) + "<html><head>";
          if (getDocumentBaseUrl(editor) !== editor.documentBaseUrl) {
            iframeHTML += '<base href="' + editor.documentBaseURI.getURI() + '" />';
          }
          iframeHTML += '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
          var bodyId = getBodyId(editor);
          var bodyClass = getBodyClass(editor);
          var translatedAriaText = editor.translate(getIframeAriaText(editor));
          if (getContentSecurityPolicy(editor)) {
            iframeHTML += '<meta http-equiv="Content-Security-Policy" content="' + getContentSecurityPolicy(editor) + '" />';
          }
          iframeHTML += "</head>" + ('<body id="' + bodyId + '" class="mce-content-body ' + bodyClass + '" data-id="' + editor.id + '" aria-label="' + translatedAriaText + '">') + "<br></body></html>";
          return iframeHTML;
        };
        var createIframe = function(editor, o2) {
          var iframeTitle = editor.translate("Rich Text Area");
          var ifr = createIframeElement(editor.id, iframeTitle, o2.height, getIframeAttrs(editor)).dom;
          ifr.onload = function() {
            ifr.onload = null;
            editor.fire("load");
          };
          var isDomainRelaxed = relaxDomain(editor, ifr);
          editor.contentAreaContainer = o2.iframeContainer;
          editor.iframeElement = ifr;
          editor.iframeHTML = getIframeHtml(editor);
          DOM$5.add(o2.iframeContainer, ifr);
          return isDomainRelaxed;
        };
        var init$1 = function(editor, boxInfo) {
          var isDomainRelaxed = createIframe(editor, boxInfo);
          if (boxInfo.editorContainer) {
            DOM$5.get(boxInfo.editorContainer).style.display = editor.orgDisplay;
            editor.hidden = DOM$5.isHidden(boxInfo.editorContainer);
          }
          editor.getElement().style.display = "none";
          DOM$5.setAttrib(editor.id, "aria-hidden", "true");
          if (!isDomainRelaxed) {
            initContentBody(editor);
          }
        };
        var DOM$4 = DOMUtils.DOM;
        var initPlugin = function(editor, initializedPlugins, plugin) {
          var Plugin = PluginManager.get(plugin);
          var pluginUrl = PluginManager.urls[plugin] || editor.documentBaseUrl.replace(/\/$/, "");
          plugin = Tools.trim(plugin);
          if (Plugin && Tools.inArray(initializedPlugins, plugin) === -1) {
            Tools.each(PluginManager.dependencies(plugin), function(dep) {
              initPlugin(editor, initializedPlugins, dep);
            });
            if (editor.plugins[plugin]) {
              return;
            }
            try {
              var pluginInstance = new Plugin(editor, pluginUrl, editor.$);
              editor.plugins[plugin] = pluginInstance;
              if (pluginInstance.init) {
                pluginInstance.init(editor, pluginUrl);
                initializedPlugins.push(plugin);
              }
            } catch (e2) {
              pluginInitError(editor, plugin, e2);
            }
          }
        };
        var trimLegacyPrefix = function(name2) {
          return name2.replace(/^\-/, "");
        };
        var initPlugins = function(editor) {
          var initializedPlugins = [];
          Tools.each(getPlugins(editor).split(/[ ,]/), function(name2) {
            initPlugin(editor, initializedPlugins, trimLegacyPrefix(name2));
          });
        };
        var initIcons = function(editor) {
          var iconPackName = Tools.trim(getIconPackName(editor));
          var currentIcons = editor.ui.registry.getAll().icons;
          var loadIcons2 = __assign(__assign({}, IconManager.get("default").icons), IconManager.get(iconPackName).icons);
          each$j(loadIcons2, function(svgData, icon) {
            if (!has$2(currentIcons, icon)) {
              editor.ui.registry.addIcon(icon, svgData);
            }
          });
        };
        var initTheme = function(editor) {
          var theme = getTheme(editor);
          if (isString$1(theme)) {
            editor.settings.theme = trimLegacyPrefix(theme);
            var Theme = ThemeManager.get(theme);
            editor.theme = new Theme(editor, ThemeManager.urls[theme]);
            if (editor.theme.init) {
              editor.theme.init(editor, ThemeManager.urls[theme] || editor.documentBaseUrl.replace(/\/$/, ""), editor.$);
            }
          } else {
            editor.theme = {};
          }
        };
        var renderFromLoadedTheme = function(editor) {
          return editor.theme.renderUI();
        };
        var renderFromThemeFunc = function(editor) {
          var elm = editor.getElement();
          var theme = getTheme(editor);
          var info = theme(editor, elm);
          if (info.editorContainer.nodeType) {
            info.editorContainer.id = info.editorContainer.id || editor.id + "_parent";
          }
          if (info.iframeContainer && info.iframeContainer.nodeType) {
            info.iframeContainer.id = info.iframeContainer.id || editor.id + "_iframecontainer";
          }
          info.height = info.iframeHeight ? info.iframeHeight : elm.offsetHeight;
          return info;
        };
        var createThemeFalseResult = function(element) {
          return {
            editorContainer: element,
            iframeContainer: element,
            api: {}
          };
        };
        var renderThemeFalseIframe = function(targetElement) {
          var iframeContainer = DOM$4.create("div");
          DOM$4.insertAfter(iframeContainer, targetElement);
          return createThemeFalseResult(iframeContainer);
        };
        var renderThemeFalse = function(editor) {
          var targetElement = editor.getElement();
          return editor.inline ? createThemeFalseResult(null) : renderThemeFalseIframe(targetElement);
        };
        var renderThemeUi = function(editor) {
          var elm = editor.getElement();
          editor.orgDisplay = elm.style.display;
          if (isString$1(getTheme(editor))) {
            return renderFromLoadedTheme(editor);
          } else if (isFunction2(getTheme(editor))) {
            return renderFromThemeFunc(editor);
          } else {
            return renderThemeFalse(editor);
          }
        };
        var augmentEditorUiApi = function(editor, api2) {
          var uiApiFacade = {
            show: Optional.from(api2.show).getOr(noop3),
            hide: Optional.from(api2.hide).getOr(noop3),
            disable: Optional.from(api2.disable).getOr(noop3),
            isDisabled: Optional.from(api2.isDisabled).getOr(never),
            enable: function() {
              if (!editor.mode.isReadOnly()) {
                Optional.from(api2.enable).map(call);
              }
            }
          };
          editor.ui = __assign(__assign({}, editor.ui), uiApiFacade);
        };
        var init = function(editor) {
          editor.fire("ScriptsLoaded");
          initIcons(editor);
          initTheme(editor);
          initPlugins(editor);
          var renderInfo = renderThemeUi(editor);
          augmentEditorUiApi(editor, Optional.from(renderInfo.api).getOr({}));
          var boxInfo = {
            editorContainer: renderInfo.editorContainer,
            iframeContainer: renderInfo.iframeContainer
          };
          editor.editorContainer = boxInfo.editorContainer ? boxInfo.editorContainer : null;
          appendContentCssFromSettings(editor);
          if (editor.inline) {
            return initContentBody(editor);
          } else {
            return init$1(editor, boxInfo);
          }
        };
        var DOM$3 = DOMUtils.DOM;
        var hasSkipLoadPrefix = function(name2) {
          return name2.charAt(0) === "-";
        };
        var loadLanguage = function(scriptLoader, editor) {
          var languageCode = getLanguageCode(editor);
          var languageUrl = getLanguageUrl(editor);
          if (I18n.hasCode(languageCode) === false && languageCode !== "en") {
            var url_1 = languageUrl !== "" ? languageUrl : editor.editorManager.baseURL + "/langs/" + languageCode + ".js";
            scriptLoader.add(url_1, noop3, void 0, function() {
              languageLoadError(editor, url_1, languageCode);
            });
          }
        };
        var loadTheme = function(scriptLoader, editor, suffix, callback2) {
          var theme = getTheme(editor);
          if (isString$1(theme)) {
            if (!hasSkipLoadPrefix(theme) && !has$2(ThemeManager.urls, theme)) {
              var themeUrl = getThemeUrl(editor);
              if (themeUrl) {
                ThemeManager.load(theme, editor.documentBaseURI.toAbsolute(themeUrl));
              } else {
                ThemeManager.load(theme, "themes/" + theme + "/theme" + suffix + ".js");
              }
            }
            scriptLoader.loadQueue(function() {
              ThemeManager.waitFor(theme, callback2);
            });
          } else {
            callback2();
          }
        };
        var getIconsUrlMetaFromUrl = function(editor) {
          return Optional.from(getIconsUrl(editor)).filter(function(url) {
            return url.length > 0;
          }).map(function(url) {
            return {
              url,
              name: Optional.none()
            };
          });
        };
        var getIconsUrlMetaFromName = function(editor, name2, suffix) {
          return Optional.from(name2).filter(function(name3) {
            return name3.length > 0 && !IconManager.has(name3);
          }).map(function(name3) {
            return {
              url: editor.editorManager.baseURL + "/icons/" + name3 + "/icons" + suffix + ".js",
              name: Optional.some(name3)
            };
          });
        };
        var loadIcons = function(scriptLoader, editor, suffix) {
          var defaultIconsUrl = getIconsUrlMetaFromName(editor, "default", suffix);
          var customIconsUrl = getIconsUrlMetaFromUrl(editor).orThunk(function() {
            return getIconsUrlMetaFromName(editor, getIconPackName(editor), "");
          });
          each$k(cat([
            defaultIconsUrl,
            customIconsUrl
          ]), function(urlMeta) {
            scriptLoader.add(urlMeta.url, noop3, void 0, function() {
              iconsLoadError(editor, urlMeta.url, urlMeta.name.getOrUndefined());
            });
          });
        };
        var loadPlugins = function(editor, suffix) {
          Tools.each(getExternalPlugins$1(editor), function(url, name2) {
            PluginManager.load(name2, url, noop3, void 0, function() {
              pluginLoadError(editor, url, name2);
            });
            editor.settings.plugins += " " + name2;
          });
          Tools.each(getPlugins(editor).split(/[ ,]/), function(plugin) {
            plugin = Tools.trim(plugin);
            if (plugin && !PluginManager.urls[plugin]) {
              if (hasSkipLoadPrefix(plugin)) {
                plugin = plugin.substr(1, plugin.length);
                var dependencies = PluginManager.dependencies(plugin);
                Tools.each(dependencies, function(depPlugin) {
                  var defaultSettings = {
                    prefix: "plugins/",
                    resource: depPlugin,
                    suffix: "/plugin" + suffix + ".js"
                  };
                  var dep = PluginManager.createUrl(defaultSettings, depPlugin);
                  PluginManager.load(dep.resource, dep, noop3, void 0, function() {
                    pluginLoadError(editor, dep.prefix + dep.resource + dep.suffix, dep.resource);
                  });
                });
              } else {
                var url_2 = {
                  prefix: "plugins/",
                  resource: plugin,
                  suffix: "/plugin" + suffix + ".js"
                };
                PluginManager.load(plugin, url_2, noop3, void 0, function() {
                  pluginLoadError(editor, url_2.prefix + url_2.resource + url_2.suffix, plugin);
                });
              }
            }
          });
        };
        var loadScripts = function(editor, suffix) {
          var scriptLoader = ScriptLoader.ScriptLoader;
          loadTheme(scriptLoader, editor, suffix, function() {
            loadLanguage(scriptLoader, editor);
            loadIcons(scriptLoader, editor, suffix);
            loadPlugins(editor, suffix);
            scriptLoader.loadQueue(function() {
              if (!editor.removed) {
                init(editor);
              }
            }, editor, function() {
              if (!editor.removed) {
                init(editor);
              }
            });
          });
        };
        var getStyleSheetLoader = function(element, editor) {
          return instance.forElement(element, {
            contentCssCors: hasContentCssCors(editor),
            referrerPolicy: getReferrerPolicy(editor)
          });
        };
        var render = function(editor) {
          var id2 = editor.id;
          I18n.setCode(getLanguageCode(editor));
          var readyHandler = function() {
            DOM$3.unbind(window, "ready", readyHandler);
            editor.render();
          };
          if (!EventUtils.Event.domLoaded) {
            DOM$3.bind(window, "ready", readyHandler);
            return;
          }
          if (!editor.getElement()) {
            return;
          }
          if (!Env.contentEditable) {
            return;
          }
          var element = SugarElement.fromDom(editor.getElement());
          var snapshot = clone$3(element);
          editor.on("remove", function() {
            eachr(element.dom.attributes, function(attr) {
              return remove$6(element, attr.name);
            });
            setAll$1(element, snapshot);
          });
          editor.ui.styleSheetLoader = getStyleSheetLoader(element, editor);
          if (!isInline(editor)) {
            editor.orgVisibility = editor.getElement().style.visibility;
            editor.getElement().style.visibility = "hidden";
          } else {
            editor.inline = true;
          }
          var form = editor.getElement().form || DOM$3.getParent(id2, "form");
          if (form) {
            editor.formElement = form;
            if (hasHiddenInput(editor) && !isTextareaOrInput(editor.getElement())) {
              DOM$3.insertAfter(DOM$3.create("input", {
                type: "hidden",
                name: id2
              }), id2);
              editor.hasHiddenInput = true;
            }
            editor.formEventDelegate = function(e2) {
              editor.fire(e2.type, e2);
            };
            DOM$3.bind(form, "submit reset", editor.formEventDelegate);
            editor.on("reset", function() {
              editor.resetContent();
            });
            if (shouldPatchSubmit(editor) && !form.submit.nodeType && !form.submit.length && !form._mceOldSubmit) {
              form._mceOldSubmit = form.submit;
              form.submit = function() {
                editor.editorManager.triggerSave();
                editor.setDirty(false);
                return form._mceOldSubmit(form);
              };
            }
          }
          editor.windowManager = WindowManager(editor);
          editor.notificationManager = NotificationManager(editor);
          if (isEncodingXml(editor)) {
            editor.on("GetContent", function(e2) {
              if (e2.save) {
                e2.content = DOM$3.encode(e2.content);
              }
            });
          }
          if (shouldAddFormSubmitTrigger(editor)) {
            editor.on("submit", function() {
              if (editor.initialized) {
                editor.save();
              }
            });
          }
          if (shouldAddUnloadTrigger(editor)) {
            editor._beforeUnload = function() {
              if (editor.initialized && !editor.destroyed && !editor.isHidden()) {
                editor.save({
                  format: "raw",
                  no_events: true,
                  set_dirty: false
                });
              }
            };
            editor.editorManager.on("BeforeUnload", editor._beforeUnload);
          }
          editor.editorManager.add(editor);
          loadScripts(editor, editor.suffix);
        };
        var addVisual = function(editor, elm) {
          return addVisual$1(editor, elm);
        };
        var legacyPropNames = {
          "font-size": "size",
          "font-family": "face"
        };
        var getSpecifiedFontProp = function(propName, rootElm, elm) {
          var getProperty = function(elm2) {
            return getRaw(elm2, propName).orThunk(function() {
              if (name(elm2) === "font") {
                return get$9(legacyPropNames, propName).bind(function(legacyPropName) {
                  return getOpt(elm2, legacyPropName);
                });
              } else {
                return Optional.none();
              }
            });
          };
          var isRoot = function(elm2) {
            return eq2(SugarElement.fromDom(rootElm), elm2);
          };
          return closest$1(SugarElement.fromDom(elm), function(elm2) {
            return getProperty(elm2);
          }, isRoot);
        };
        var normalizeFontFamily = function(fontFamily) {
          return fontFamily.replace(/[\'\"\\]/g, "").replace(/,\s+/g, ",");
        };
        var getComputedFontProp = function(propName, elm) {
          return Optional.from(DOMUtils.DOM.getStyle(elm, propName, true));
        };
        var getFontProp = function(propName) {
          return function(rootElm, elm) {
            return Optional.from(elm).map(SugarElement.fromDom).filter(isElement$6).bind(function(element) {
              return getSpecifiedFontProp(propName, rootElm, element.dom).or(getComputedFontProp(propName, element.dom));
            }).getOr("");
          };
        };
        var getFontSize = getFontProp("font-size");
        var getFontFamily = compose(normalizeFontFamily, getFontProp("font-family"));
        var findFirstCaretElement = function(editor) {
          return firstPositionIn(editor.getBody()).map(function(caret) {
            var container = caret.container();
            return isText$7(container) ? container.parentNode : container;
          });
        };
        var getCaretElement = function(editor) {
          return Optional.from(editor.selection.getRng()).bind(function(rng) {
            var root = editor.getBody();
            var atStartOfNode = rng.startContainer === root && rng.startOffset === 0;
            return atStartOfNode ? Optional.none() : Optional.from(editor.selection.getStart(true));
          });
        };
        var bindRange = function(editor, binder) {
          return getCaretElement(editor).orThunk(curry(findFirstCaretElement, editor)).map(SugarElement.fromDom).filter(isElement$6).bind(binder);
        };
        var mapRange = function(editor, mapper) {
          return bindRange(editor, compose1(Optional.some, mapper));
        };
        var fromFontSizeNumber = function(editor, value2) {
          if (/^[0-9.]+$/.test(value2)) {
            var fontSizeNumber = parseInt(value2, 10);
            if (fontSizeNumber >= 1 && fontSizeNumber <= 7) {
              var fontSizes = getFontStyleValues(editor);
              var fontClasses = getFontSizeClasses(editor);
              if (fontClasses) {
                return fontClasses[fontSizeNumber - 1] || value2;
              } else {
                return fontSizes[fontSizeNumber - 1] || value2;
              }
            } else {
              return value2;
            }
          } else {
            return value2;
          }
        };
        var normalizeFontNames = function(font) {
          var fonts = font.split(/\s*,\s*/);
          return map$3(fonts, function(font2) {
            if (font2.indexOf(" ") !== -1 && !(startsWith(font2, '"') || startsWith(font2, "'"))) {
              return "'" + font2 + "'";
            } else {
              return font2;
            }
          }).join(",");
        };
        var fontNameAction = function(editor, value2) {
          var font = fromFontSizeNumber(editor, value2);
          editor.formatter.toggle("fontname", { value: normalizeFontNames(font) });
          editor.nodeChanged();
        };
        var fontNameQuery = function(editor) {
          return mapRange(editor, function(elm) {
            return getFontFamily(editor.getBody(), elm.dom);
          }).getOr("");
        };
        var fontSizeAction = function(editor, value2) {
          editor.formatter.toggle("fontsize", { value: fromFontSizeNumber(editor, value2) });
          editor.nodeChanged();
        };
        var fontSizeQuery = function(editor) {
          return mapRange(editor, function(elm) {
            return getFontSize(editor.getBody(), elm.dom);
          }).getOr("");
        };
        var lineHeightQuery = function(editor) {
          return mapRange(editor, function(elm) {
            var root = SugarElement.fromDom(editor.getBody());
            var specifiedStyle = closest$1(elm, function(elm2) {
              return getRaw(elm2, "line-height");
            }, curry(eq2, root));
            var computedStyle = function() {
              var lineHeight = parseFloat(get$5(elm, "line-height"));
              var fontSize = parseFloat(get$5(elm, "font-size"));
              return String(lineHeight / fontSize);
            };
            return specifiedStyle.getOrThunk(computedStyle);
          }).getOr("");
        };
        var lineHeightAction = function(editor, lineHeight) {
          editor.formatter.toggle("lineheight", { value: String(lineHeight) });
          editor.nodeChanged();
        };
        var processValue = function(value2) {
          if (typeof value2 !== "string") {
            var details = Tools.extend({
              paste: value2.paste,
              data: { paste: value2.paste }
            }, value2);
            return {
              content: value2.content,
              details
            };
          }
          return {
            content: value2,
            details: {}
          };
        };
        var insertAtCaret = function(editor, value2) {
          var result = processValue(value2);
          insertContent(editor, result.content, result.details);
        };
        var each$4 = Tools.each;
        var map3 = Tools.map, inArray = Tools.inArray;
        var EditorCommands = function() {
          function EditorCommands2(editor) {
            this.commands = {
              state: {},
              exec: {},
              value: {}
            };
            this.editor = editor;
            this.setupCommands(editor);
          }
          EditorCommands2.prototype.execCommand = function(command, ui2, value2, args) {
            var func, state = false;
            var self2 = this;
            if (self2.editor.removed) {
              return;
            }
            if (command.toLowerCase() !== "mcefocus") {
              if (!/^(mceAddUndoLevel|mceEndUndoLevel|mceBeginUndoLevel|mceRepaint)$/.test(command) && (!args || !args.skip_focus)) {
                self2.editor.focus();
              } else {
                restore(self2.editor);
              }
            }
            args = self2.editor.fire("BeforeExecCommand", {
              command,
              ui: ui2,
              value: value2
            });
            if (args.isDefaultPrevented()) {
              return false;
            }
            var customCommand = command.toLowerCase();
            if (func = self2.commands.exec[customCommand]) {
              func(customCommand, ui2, value2);
              self2.editor.fire("ExecCommand", {
                command,
                ui: ui2,
                value: value2
              });
              return true;
            }
            each$4(this.editor.plugins, function(p2) {
              if (p2.execCommand && p2.execCommand(command, ui2, value2)) {
                self2.editor.fire("ExecCommand", {
                  command,
                  ui: ui2,
                  value: value2
                });
                state = true;
                return false;
              }
            });
            if (state) {
              return state;
            }
            if (self2.editor.theme && self2.editor.theme.execCommand && self2.editor.theme.execCommand(command, ui2, value2)) {
              self2.editor.fire("ExecCommand", {
                command,
                ui: ui2,
                value: value2
              });
              return true;
            }
            try {
              state = self2.editor.getDoc().execCommand(command, ui2, value2);
            } catch (ex) {
            }
            if (state) {
              self2.editor.fire("ExecCommand", {
                command,
                ui: ui2,
                value: value2
              });
              return true;
            }
            return false;
          };
          EditorCommands2.prototype.queryCommandState = function(command) {
            var func;
            if (this.editor.quirks.isHidden() || this.editor.removed) {
              return;
            }
            command = command.toLowerCase();
            if (func = this.commands.state[command]) {
              return func(command);
            }
            try {
              return this.editor.getDoc().queryCommandState(command);
            } catch (ex) {
            }
            return false;
          };
          EditorCommands2.prototype.queryCommandValue = function(command) {
            var func;
            if (this.editor.quirks.isHidden() || this.editor.removed) {
              return;
            }
            command = command.toLowerCase();
            if (func = this.commands.value[command]) {
              return func(command);
            }
            try {
              return this.editor.getDoc().queryCommandValue(command);
            } catch (ex) {
            }
          };
          EditorCommands2.prototype.addCommands = function(commandList, type2) {
            if (type2 === void 0) {
              type2 = "exec";
            }
            var self2 = this;
            each$4(commandList, function(callback2, command) {
              each$4(command.toLowerCase().split(","), function(command2) {
                self2.commands[type2][command2] = callback2;
              });
            });
          };
          EditorCommands2.prototype.addCommand = function(command, callback2, scope) {
            var _this = this;
            command = command.toLowerCase();
            this.commands.exec[command] = function(command2, ui2, value2, args) {
              return callback2.call(scope || _this.editor, ui2, value2, args);
            };
          };
          EditorCommands2.prototype.queryCommandSupported = function(command) {
            command = command.toLowerCase();
            if (this.commands.exec[command]) {
              return true;
            }
            try {
              return this.editor.getDoc().queryCommandSupported(command);
            } catch (ex) {
            }
            return false;
          };
          EditorCommands2.prototype.addQueryStateHandler = function(command, callback2, scope) {
            var _this = this;
            command = command.toLowerCase();
            this.commands.state[command] = function() {
              return callback2.call(scope || _this.editor);
            };
          };
          EditorCommands2.prototype.addQueryValueHandler = function(command, callback2, scope) {
            var _this = this;
            command = command.toLowerCase();
            this.commands.value[command] = function() {
              return callback2.call(scope || _this.editor);
            };
          };
          EditorCommands2.prototype.hasCustomCommand = function(command) {
            command = command.toLowerCase();
            return !!this.commands.exec[command];
          };
          EditorCommands2.prototype.execNativeCommand = function(command, ui2, value2) {
            if (ui2 === void 0) {
              ui2 = false;
            }
            if (value2 === void 0) {
              value2 = null;
            }
            return this.editor.getDoc().execCommand(command, ui2, value2);
          };
          EditorCommands2.prototype.isFormatMatch = function(name2) {
            return this.editor.formatter.match(name2);
          };
          EditorCommands2.prototype.toggleFormat = function(name2, value2) {
            this.editor.formatter.toggle(name2, value2);
            this.editor.nodeChanged();
          };
          EditorCommands2.prototype.storeSelection = function(type2) {
            this.selectionBookmark = this.editor.selection.getBookmark(type2);
          };
          EditorCommands2.prototype.restoreSelection = function() {
            this.editor.selection.moveToBookmark(this.selectionBookmark);
          };
          EditorCommands2.prototype.setupCommands = function(editor) {
            var self2 = this;
            this.addCommands({
              "mceResetDesignMode,mceBeginUndoLevel": noop3,
              "mceEndUndoLevel,mceAddUndoLevel": function() {
                editor.undoManager.add();
              },
              "mceFocus": function(_command, _ui, value2) {
                focus(editor, value2);
              },
              "Cut,Copy,Paste": function(command) {
                var doc2 = editor.getDoc();
                var failed;
                try {
                  self2.execNativeCommand(command);
                } catch (ex) {
                  failed = true;
                }
                if (command === "paste" && !doc2.queryCommandEnabled(command)) {
                  failed = true;
                }
                if (failed || !doc2.queryCommandSupported(command)) {
                  var msg = editor.translate("Your browser doesn't support direct access to the clipboard. Please use the Ctrl+X/C/V keyboard shortcuts instead.");
                  if (Env.mac) {
                    msg = msg.replace(/Ctrl\+/g, "\u2318+");
                  }
                  editor.notificationManager.open({
                    text: msg,
                    type: "error"
                  });
                }
              },
              "unlink": function() {
                if (editor.selection.isCollapsed()) {
                  var elm = editor.dom.getParent(editor.selection.getStart(), "a");
                  if (elm) {
                    editor.dom.remove(elm, true);
                  }
                  return;
                }
                editor.formatter.remove("link");
              },
              "JustifyLeft,JustifyCenter,JustifyRight,JustifyFull,JustifyNone": function(command) {
                var align = command.substring(7);
                if (align === "full") {
                  align = "justify";
                }
                each$4("left,center,right,justify".split(","), function(name2) {
                  if (align !== name2) {
                    editor.formatter.remove("align" + name2);
                  }
                });
                if (align !== "none") {
                  self2.toggleFormat("align" + align);
                }
              },
              "InsertUnorderedList,InsertOrderedList": function(command) {
                var listParent;
                self2.execNativeCommand(command);
                var listElm = editor.dom.getParent(editor.selection.getNode(), "ol,ul");
                if (listElm) {
                  listParent = listElm.parentNode;
                  if (/^(H[1-6]|P|ADDRESS|PRE)$/.test(listParent.nodeName)) {
                    self2.storeSelection();
                    editor.dom.split(listParent, listElm);
                    self2.restoreSelection();
                  }
                }
              },
              "Bold,Italic,Underline,Strikethrough,Superscript,Subscript": function(command) {
                self2.toggleFormat(command);
              },
              "ForeColor,HiliteColor": function(command, ui2, value2) {
                self2.toggleFormat(command, { value: value2 });
              },
              "FontName": function(command, ui2, value2) {
                fontNameAction(editor, value2);
              },
              "FontSize": function(command, ui2, value2) {
                fontSizeAction(editor, value2);
              },
              "LineHeight": function(command, ui2, value2) {
                lineHeightAction(editor, value2);
              },
              "Lang": function(command, ui2, lang) {
                self2.toggleFormat(command, {
                  value: lang.code,
                  customValue: lang.customCode
                });
              },
              "RemoveFormat": function(command) {
                editor.formatter.remove(command);
              },
              "mceBlockQuote": function() {
                self2.toggleFormat("blockquote");
              },
              "FormatBlock": function(command, ui2, value2) {
                return self2.toggleFormat(value2 || "p");
              },
              "mceCleanup": function() {
                var bookmark = editor.selection.getBookmark();
                editor.setContent(editor.getContent());
                editor.selection.moveToBookmark(bookmark);
              },
              "mceRemoveNode": function(command, ui2, value2) {
                var node = value2 || editor.selection.getNode();
                if (node !== editor.getBody()) {
                  self2.storeSelection();
                  editor.dom.remove(node, true);
                  self2.restoreSelection();
                }
              },
              "mceSelectNodeDepth": function(command, ui2, value2) {
                var counter = 0;
                editor.dom.getParent(editor.selection.getNode(), function(node) {
                  if (node.nodeType === 1 && counter++ === value2) {
                    editor.selection.select(node);
                    return false;
                  }
                }, editor.getBody());
              },
              "mceSelectNode": function(command, ui2, value2) {
                editor.selection.select(value2);
              },
              "mceInsertContent": function(command, ui2, value2) {
                insertAtCaret(editor, value2);
              },
              "mceInsertRawHTML": function(command, ui2, value2) {
                editor.selection.setContent("tiny_mce_marker");
                var content = editor.getContent();
                editor.setContent(content.replace(/tiny_mce_marker/g, function() {
                  return value2;
                }));
              },
              "mceInsertNewLine": function(command, ui2, value2) {
                insert(editor, value2);
              },
              "mceToggleFormat": function(command, ui2, value2) {
                self2.toggleFormat(value2);
              },
              "mceSetContent": function(command, ui2, value2) {
                editor.setContent(value2);
              },
              "Indent,Outdent": function(command) {
                handle(editor, command);
              },
              "mceRepaint": noop3,
              "InsertHorizontalRule": function() {
                editor.execCommand("mceInsertContent", false, "<hr />");
              },
              "mceToggleVisualAid": function() {
                editor.hasVisual = !editor.hasVisual;
                editor.addVisual();
              },
              "mceReplaceContent": function(command, ui2, value2) {
                editor.execCommand("mceInsertContent", false, value2.replace(/\{\$selection\}/g, editor.selection.getContent({ format: "text" })));
              },
              "mceInsertLink": function(command, ui2, value2) {
                if (typeof value2 === "string") {
                  value2 = { href: value2 };
                }
                var anchor = editor.dom.getParent(editor.selection.getNode(), "a");
                value2.href = value2.href.replace(/ /g, "%20");
                if (!anchor || !value2.href) {
                  editor.formatter.remove("link");
                }
                if (value2.href) {
                  editor.formatter.apply("link", value2, anchor);
                }
              },
              "selectAll": function() {
                var editingHost = editor.dom.getParent(editor.selection.getStart(), isContentEditableTrue$4);
                if (editingHost) {
                  var rng = editor.dom.createRng();
                  rng.selectNodeContents(editingHost);
                  editor.selection.setRng(rng);
                }
              },
              "mceNewDocument": function() {
                editor.setContent("");
              },
              "InsertLineBreak": function(command, ui2, value2) {
                insert$1(editor, value2);
                return true;
              }
            });
            var alignStates = function(name2) {
              return function() {
                var selection = editor.selection;
                var nodes = selection.isCollapsed() ? [editor.dom.getParent(selection.getNode(), editor.dom.isBlock)] : selection.getSelectedBlocks();
                var matches2 = map3(nodes, function(node) {
                  return !!editor.formatter.matchNode(node, name2);
                });
                return inArray(matches2, true) !== -1;
              };
            };
            self2.addCommands({
              "JustifyLeft": alignStates("alignleft"),
              "JustifyCenter": alignStates("aligncenter"),
              "JustifyRight": alignStates("alignright"),
              "JustifyFull": alignStates("alignjustify"),
              "Bold,Italic,Underline,Strikethrough,Superscript,Subscript": function(command) {
                return self2.isFormatMatch(command);
              },
              "mceBlockQuote": function() {
                return self2.isFormatMatch("blockquote");
              },
              "Outdent": function() {
                return canOutdent(editor);
              },
              "InsertUnorderedList,InsertOrderedList": function(command) {
                var list = editor.dom.getParent(editor.selection.getNode(), "ul,ol");
                return list && (command === "insertunorderedlist" && list.tagName === "UL" || command === "insertorderedlist" && list.tagName === "OL");
              }
            }, "state");
            self2.addCommands({
              Undo: function() {
                editor.undoManager.undo();
              },
              Redo: function() {
                editor.undoManager.redo();
              }
            });
            self2.addQueryValueHandler("FontName", function() {
              return fontNameQuery(editor);
            }, this);
            self2.addQueryValueHandler("FontSize", function() {
              return fontSizeQuery(editor);
            }, this);
            self2.addQueryValueHandler("LineHeight", function() {
              return lineHeightQuery(editor);
            }, this);
          };
          return EditorCommands2;
        }();
        var internalContentEditableAttr = "data-mce-contenteditable";
        var toggleClass = function(elm, cls, state) {
          if (has(elm, cls) && state === false) {
            remove$3(elm, cls);
          } else if (state) {
            add$1(elm, cls);
          }
        };
        var setEditorCommandState = function(editor, cmd, state) {
          try {
            editor.getDoc().execCommand(cmd, false, String(state));
          } catch (ex) {
          }
        };
        var setContentEditable = function(elm, state) {
          elm.dom.contentEditable = state ? "true" : "false";
        };
        var switchOffContentEditableTrue = function(elm) {
          each$k(descendants(elm, '*[contenteditable="true"]'), function(elm2) {
            set$1(elm2, internalContentEditableAttr, "true");
            setContentEditable(elm2, false);
          });
        };
        var switchOnContentEditableTrue = function(elm) {
          each$k(descendants(elm, "*[" + internalContentEditableAttr + '="true"]'), function(elm2) {
            remove$6(elm2, internalContentEditableAttr);
            setContentEditable(elm2, true);
          });
        };
        var removeFakeSelection = function(editor) {
          Optional.from(editor.selection.getNode()).each(function(elm) {
            elm.removeAttribute("data-mce-selected");
          });
        };
        var restoreFakeSelection = function(editor) {
          editor.selection.setRng(editor.selection.getRng());
        };
        var toggleReadOnly = function(editor, state) {
          var body = SugarElement.fromDom(editor.getBody());
          toggleClass(body, "mce-content-readonly", state);
          if (state) {
            editor.selection.controlSelection.hideResizeRect();
            editor._selectionOverrides.hideFakeCaret();
            removeFakeSelection(editor);
            editor.readonly = true;
            setContentEditable(body, false);
            switchOffContentEditableTrue(body);
          } else {
            editor.readonly = false;
            setContentEditable(body, true);
            switchOnContentEditableTrue(body);
            setEditorCommandState(editor, "StyleWithCSS", false);
            setEditorCommandState(editor, "enableInlineTableEditing", false);
            setEditorCommandState(editor, "enableObjectResizing", false);
            if (hasEditorOrUiFocus(editor)) {
              editor.focus();
            }
            restoreFakeSelection(editor);
            editor.nodeChanged();
          }
        };
        var isReadOnly = function(editor) {
          return editor.readonly;
        };
        var registerFilters = function(editor) {
          editor.parser.addAttributeFilter("contenteditable", function(nodes) {
            if (isReadOnly(editor)) {
              each$k(nodes, function(node) {
                node.attr(internalContentEditableAttr, node.attr("contenteditable"));
                node.attr("contenteditable", "false");
              });
            }
          });
          editor.serializer.addAttributeFilter(internalContentEditableAttr, function(nodes) {
            if (isReadOnly(editor)) {
              each$k(nodes, function(node) {
                node.attr("contenteditable", node.attr(internalContentEditableAttr));
              });
            }
          });
          editor.serializer.addTempAttr(internalContentEditableAttr);
        };
        var registerReadOnlyContentFilters = function(editor) {
          if (editor.serializer) {
            registerFilters(editor);
          } else {
            editor.on("PreInit", function() {
              registerFilters(editor);
            });
          }
        };
        var isClickEvent = function(e2) {
          return e2.type === "click";
        };
        var getAnchorHrefOpt = function(editor, elm) {
          var isRoot = function(elm2) {
            return eq2(elm2, SugarElement.fromDom(editor.getBody()));
          };
          return closest$2(elm, "a", isRoot).bind(function(a2) {
            return getOpt(a2, "href");
          });
        };
        var processReadonlyEvents = function(editor, e2) {
          if (isClickEvent(e2) && !VK.metaKeyPressed(e2)) {
            var elm = SugarElement.fromDom(e2.target);
            getAnchorHrefOpt(editor, elm).each(function(href) {
              e2.preventDefault();
              if (/^#/.test(href)) {
                var targetEl = editor.dom.select(href + ',[name="' + removeLeading(href, "#") + '"]');
                if (targetEl.length) {
                  editor.selection.scrollIntoView(targetEl[0], true);
                }
              } else {
                window.open(href, "_blank", "rel=noopener noreferrer,menubar=yes,toolbar=yes,location=yes,status=yes,resizable=yes,scrollbars=yes");
              }
            });
          }
        };
        var registerReadOnlySelectionBlockers = function(editor) {
          editor.on("ShowCaret", function(e2) {
            if (isReadOnly(editor)) {
              e2.preventDefault();
            }
          });
          editor.on("ObjectSelected", function(e2) {
            if (isReadOnly(editor)) {
              e2.preventDefault();
            }
          });
        };
        var nativeEvents2 = Tools.makeMap("focus blur focusin focusout click dblclick mousedown mouseup mousemove mouseover beforepaste paste cut copy selectionchange mouseout mouseenter mouseleave wheel keydown keypress keyup input beforeinput contextmenu dragstart dragend dragover draggesture dragdrop drop drag submit compositionstart compositionend compositionupdate touchstart touchmove touchend touchcancel", " ");
        var EventDispatcher = function() {
          function EventDispatcher2(settings) {
            this.bindings = {};
            this.settings = settings || {};
            this.scope = this.settings.scope || this;
            this.toggleEvent = this.settings.toggleEvent || never;
          }
          EventDispatcher2.isNative = function(name2) {
            return !!nativeEvents2[name2.toLowerCase()];
          };
          EventDispatcher2.prototype.fire = function(name2, args) {
            var lcName = name2.toLowerCase();
            var event = normalize$3(lcName, args || {}, this.scope);
            if (this.settings.beforeFire) {
              this.settings.beforeFire(event);
            }
            var handlers = this.bindings[lcName];
            if (handlers) {
              for (var i2 = 0, l2 = handlers.length; i2 < l2; i2++) {
                var callback2 = handlers[i2];
                if (callback2.removed) {
                  continue;
                }
                if (callback2.once) {
                  this.off(lcName, callback2.func);
                }
                if (event.isImmediatePropagationStopped()) {
                  return event;
                }
                if (callback2.func.call(this.scope, event) === false) {
                  event.preventDefault();
                  return event;
                }
              }
            }
            return event;
          };
          EventDispatcher2.prototype.on = function(name2, callback2, prepend2, extra2) {
            if (callback2 === false) {
              callback2 = never;
            }
            if (callback2) {
              var wrappedCallback = {
                func: callback2,
                removed: false
              };
              if (extra2) {
                Tools.extend(wrappedCallback, extra2);
              }
              var names2 = name2.toLowerCase().split(" ");
              var i2 = names2.length;
              while (i2--) {
                var currentName = names2[i2];
                var handlers = this.bindings[currentName];
                if (!handlers) {
                  handlers = [];
                  this.toggleEvent(currentName, true);
                }
                if (prepend2) {
                  handlers = __spreadArray([wrappedCallback], handlers, true);
                } else {
                  handlers = __spreadArray(__spreadArray([], handlers, true), [wrappedCallback], false);
                }
                this.bindings[currentName] = handlers;
              }
            }
            return this;
          };
          EventDispatcher2.prototype.off = function(name2, callback2) {
            var _this = this;
            if (name2) {
              var names2 = name2.toLowerCase().split(" ");
              var i2 = names2.length;
              while (i2--) {
                var currentName = names2[i2];
                var handlers = this.bindings[currentName];
                if (!currentName) {
                  each$j(this.bindings, function(_value, bindingName) {
                    _this.toggleEvent(bindingName, false);
                    delete _this.bindings[bindingName];
                  });
                  return this;
                }
                if (handlers) {
                  if (!callback2) {
                    handlers.length = 0;
                  } else {
                    var filteredHandlers = partition(handlers, function(handler) {
                      return handler.func === callback2;
                    });
                    handlers = filteredHandlers.fail;
                    this.bindings[currentName] = handlers;
                    each$k(filteredHandlers.pass, function(handler) {
                      handler.removed = true;
                    });
                  }
                  if (!handlers.length) {
                    this.toggleEvent(name2, false);
                    delete this.bindings[currentName];
                  }
                }
              }
            } else {
              each$j(this.bindings, function(_value, name3) {
                _this.toggleEvent(name3, false);
              });
              this.bindings = {};
            }
            return this;
          };
          EventDispatcher2.prototype.once = function(name2, callback2, prepend2) {
            return this.on(name2, callback2, prepend2, { once: true });
          };
          EventDispatcher2.prototype.has = function(name2) {
            name2 = name2.toLowerCase();
            return !(!this.bindings[name2] || this.bindings[name2].length === 0);
          };
          return EventDispatcher2;
        }();
        var getEventDispatcher = function(obj) {
          if (!obj._eventDispatcher) {
            obj._eventDispatcher = new EventDispatcher({
              scope: obj,
              toggleEvent: function(name2, state) {
                if (EventDispatcher.isNative(name2) && obj.toggleNativeEvent) {
                  obj.toggleNativeEvent(name2, state);
                }
              }
            });
          }
          return obj._eventDispatcher;
        };
        var Observable = {
          fire: function(name2, args, bubble) {
            var self2 = this;
            if (self2.removed && name2 !== "remove" && name2 !== "detach") {
              return args;
            }
            var dispatcherArgs = getEventDispatcher(self2).fire(name2, args);
            if (bubble !== false && self2.parent) {
              var parent_1 = self2.parent();
              while (parent_1 && !dispatcherArgs.isPropagationStopped()) {
                parent_1.fire(name2, dispatcherArgs, false);
                parent_1 = parent_1.parent();
              }
            }
            return dispatcherArgs;
          },
          on: function(name2, callback2, prepend2) {
            return getEventDispatcher(this).on(name2, callback2, prepend2);
          },
          off: function(name2, callback2) {
            return getEventDispatcher(this).off(name2, callback2);
          },
          once: function(name2, callback2) {
            return getEventDispatcher(this).once(name2, callback2);
          },
          hasEventListeners: function(name2) {
            return getEventDispatcher(this).has(name2);
          }
        };
        var DOM$2 = DOMUtils.DOM;
        var customEventRootDelegates;
        var getEventTarget = function(editor, eventName) {
          if (eventName === "selectionchange") {
            return editor.getDoc();
          }
          if (!editor.inline && /^mouse|touch|click|contextmenu|drop|dragover|dragend/.test(eventName)) {
            return editor.getDoc().documentElement;
          }
          var eventRoot = getEventRoot(editor);
          if (eventRoot) {
            if (!editor.eventRoot) {
              editor.eventRoot = DOM$2.select(eventRoot)[0];
            }
            return editor.eventRoot;
          }
          return editor.getBody();
        };
        var isListening = function(editor) {
          return !editor.hidden && !isReadOnly(editor);
        };
        var fireEvent = function(editor, eventName, e2) {
          if (isListening(editor)) {
            editor.fire(eventName, e2);
          } else if (isReadOnly(editor)) {
            processReadonlyEvents(editor, e2);
          }
        };
        var bindEventDelegate = function(editor, eventName) {
          var delegate;
          if (!editor.delegates) {
            editor.delegates = {};
          }
          if (editor.delegates[eventName] || editor.removed) {
            return;
          }
          var eventRootElm = getEventTarget(editor, eventName);
          if (getEventRoot(editor)) {
            if (!customEventRootDelegates) {
              customEventRootDelegates = {};
              editor.editorManager.on("removeEditor", function() {
                if (!editor.editorManager.activeEditor) {
                  if (customEventRootDelegates) {
                    each$j(customEventRootDelegates, function(_value, name2) {
                      editor.dom.unbind(getEventTarget(editor, name2));
                    });
                    customEventRootDelegates = null;
                  }
                }
              });
            }
            if (customEventRootDelegates[eventName]) {
              return;
            }
            delegate = function(e2) {
              var target = e2.target;
              var editors2 = editor.editorManager.get();
              var i2 = editors2.length;
              while (i2--) {
                var body = editors2[i2].getBody();
                if (body === target || DOM$2.isChildOf(target, body)) {
                  fireEvent(editors2[i2], eventName, e2);
                }
              }
            };
            customEventRootDelegates[eventName] = delegate;
            DOM$2.bind(eventRootElm, eventName, delegate);
          } else {
            delegate = function(e2) {
              fireEvent(editor, eventName, e2);
            };
            DOM$2.bind(eventRootElm, eventName, delegate);
            editor.delegates[eventName] = delegate;
          }
        };
        var EditorObservable = __assign(__assign({}, Observable), {
          bindPendingEventDelegates: function() {
            var self2 = this;
            Tools.each(self2._pendingNativeEvents, function(name2) {
              bindEventDelegate(self2, name2);
            });
          },
          toggleNativeEvent: function(name2, state) {
            var self2 = this;
            if (name2 === "focus" || name2 === "blur") {
              return;
            }
            if (self2.removed) {
              return;
            }
            if (state) {
              if (self2.initialized) {
                bindEventDelegate(self2, name2);
              } else {
                if (!self2._pendingNativeEvents) {
                  self2._pendingNativeEvents = [name2];
                } else {
                  self2._pendingNativeEvents.push(name2);
                }
              }
            } else if (self2.initialized) {
              self2.dom.unbind(getEventTarget(self2, name2), name2, self2.delegates[name2]);
              delete self2.delegates[name2];
            }
          },
          unbindAllNativeEvents: function() {
            var self2 = this;
            var body = self2.getBody();
            var dom2 = self2.dom;
            if (self2.delegates) {
              each$j(self2.delegates, function(value2, name2) {
                self2.dom.unbind(getEventTarget(self2, name2), name2, value2);
              });
              delete self2.delegates;
            }
            if (!self2.inline && body && dom2) {
              body.onload = null;
              dom2.unbind(self2.getWin());
              dom2.unbind(self2.getDoc());
            }
            if (dom2) {
              dom2.unbind(body);
              dom2.unbind(self2.getContainer());
            }
          }
        });
        var defaultModes = [
          "design",
          "readonly"
        ];
        var switchToMode = function(editor, activeMode, availableModes, mode) {
          var oldMode = availableModes[activeMode.get()];
          var newMode = availableModes[mode];
          try {
            newMode.activate();
          } catch (e2) {
            console.error("problem while activating editor mode " + mode + ":", e2);
            return;
          }
          oldMode.deactivate();
          if (oldMode.editorReadOnly !== newMode.editorReadOnly) {
            toggleReadOnly(editor, newMode.editorReadOnly);
          }
          activeMode.set(mode);
          fireSwitchMode(editor, mode);
        };
        var setMode = function(editor, availableModes, activeMode, mode) {
          if (mode === activeMode.get()) {
            return;
          } else if (!has$2(availableModes, mode)) {
            throw new Error("Editor mode '" + mode + "' is invalid");
          }
          if (editor.initialized) {
            switchToMode(editor, activeMode, availableModes, mode);
          } else {
            editor.on("init", function() {
              return switchToMode(editor, activeMode, availableModes, mode);
            });
          }
        };
        var registerMode = function(availableModes, mode, api2) {
          var _a;
          if (contains$3(defaultModes, mode)) {
            throw new Error("Cannot override default mode " + mode);
          }
          return __assign(__assign({}, availableModes), (_a = {}, _a[mode] = __assign(__assign({}, api2), {
            deactivate: function() {
              try {
                api2.deactivate();
              } catch (e2) {
                console.error("problem while deactivating editor mode " + mode + ":", e2);
              }
            }
          }), _a));
        };
        var create$4 = function(editor) {
          var activeMode = Cell("design");
          var availableModes = Cell({
            design: {
              activate: noop3,
              deactivate: noop3,
              editorReadOnly: false
            },
            readonly: {
              activate: noop3,
              deactivate: noop3,
              editorReadOnly: true
            }
          });
          registerReadOnlyContentFilters(editor);
          registerReadOnlySelectionBlockers(editor);
          return {
            isReadOnly: function() {
              return isReadOnly(editor);
            },
            set: function(mode) {
              return setMode(editor, availableModes.get(), activeMode, mode);
            },
            get: function() {
              return activeMode.get();
            },
            register: function(mode, api2) {
              availableModes.set(registerMode(availableModes.get(), mode, api2));
            }
          };
        };
        var each$3 = Tools.each, explode$1 = Tools.explode;
        var keyCodeLookup = {
          f1: 112,
          f2: 113,
          f3: 114,
          f4: 115,
          f5: 116,
          f6: 117,
          f7: 118,
          f8: 119,
          f9: 120,
          f10: 121,
          f11: 122,
          f12: 123
        };
        var modifierNames = Tools.makeMap("alt,ctrl,shift,meta,access");
        var parseShortcut = function(pattern) {
          var key;
          var shortcut = {};
          each$3(explode$1(pattern.toLowerCase(), "+"), function(value2) {
            if (value2 in modifierNames) {
              shortcut[value2] = true;
            } else {
              if (/^[0-9]{2,}$/.test(value2)) {
                shortcut.keyCode = parseInt(value2, 10);
              } else {
                shortcut.charCode = value2.charCodeAt(0);
                shortcut.keyCode = keyCodeLookup[value2] || value2.toUpperCase().charCodeAt(0);
              }
            }
          });
          var id2 = [shortcut.keyCode];
          for (key in modifierNames) {
            if (shortcut[key]) {
              id2.push(key);
            } else {
              shortcut[key] = false;
            }
          }
          shortcut.id = id2.join(",");
          if (shortcut.access) {
            shortcut.alt = true;
            if (Env.mac) {
              shortcut.ctrl = true;
            } else {
              shortcut.shift = true;
            }
          }
          if (shortcut.meta) {
            if (Env.mac) {
              shortcut.meta = true;
            } else {
              shortcut.ctrl = true;
              shortcut.meta = false;
            }
          }
          return shortcut;
        };
        var Shortcuts = function() {
          function Shortcuts2(editor) {
            this.shortcuts = {};
            this.pendingPatterns = [];
            this.editor = editor;
            var self2 = this;
            editor.on("keyup keypress keydown", function(e2) {
              if ((self2.hasModifier(e2) || self2.isFunctionKey(e2)) && !e2.isDefaultPrevented()) {
                each$3(self2.shortcuts, function(shortcut) {
                  if (self2.matchShortcut(e2, shortcut)) {
                    self2.pendingPatterns = shortcut.subpatterns.slice(0);
                    if (e2.type === "keydown") {
                      self2.executeShortcutAction(shortcut);
                    }
                    return true;
                  }
                });
                if (self2.matchShortcut(e2, self2.pendingPatterns[0])) {
                  if (self2.pendingPatterns.length === 1) {
                    if (e2.type === "keydown") {
                      self2.executeShortcutAction(self2.pendingPatterns[0]);
                    }
                  }
                  self2.pendingPatterns.shift();
                }
              }
            });
          }
          Shortcuts2.prototype.add = function(pattern, desc, cmdFunc, scope) {
            var self2 = this;
            var func = self2.normalizeCommandFunc(cmdFunc);
            each$3(explode$1(Tools.trim(pattern)), function(pattern2) {
              var shortcut = self2.createShortcut(pattern2, desc, func, scope);
              self2.shortcuts[shortcut.id] = shortcut;
            });
            return true;
          };
          Shortcuts2.prototype.remove = function(pattern) {
            var shortcut = this.createShortcut(pattern);
            if (this.shortcuts[shortcut.id]) {
              delete this.shortcuts[shortcut.id];
              return true;
            }
            return false;
          };
          Shortcuts2.prototype.normalizeCommandFunc = function(cmdFunc) {
            var self2 = this;
            var cmd = cmdFunc;
            if (typeof cmd === "string") {
              return function() {
                self2.editor.execCommand(cmd, false, null);
              };
            } else if (Tools.isArray(cmd)) {
              return function() {
                self2.editor.execCommand(cmd[0], cmd[1], cmd[2]);
              };
            } else {
              return cmd;
            }
          };
          Shortcuts2.prototype.createShortcut = function(pattern, desc, cmdFunc, scope) {
            var shortcuts = Tools.map(explode$1(pattern, ">"), parseShortcut);
            shortcuts[shortcuts.length - 1] = Tools.extend(shortcuts[shortcuts.length - 1], {
              func: cmdFunc,
              scope: scope || this.editor
            });
            return Tools.extend(shortcuts[0], {
              desc: this.editor.translate(desc),
              subpatterns: shortcuts.slice(1)
            });
          };
          Shortcuts2.prototype.hasModifier = function(e2) {
            return e2.altKey || e2.ctrlKey || e2.metaKey;
          };
          Shortcuts2.prototype.isFunctionKey = function(e2) {
            return e2.type === "keydown" && e2.keyCode >= 112 && e2.keyCode <= 123;
          };
          Shortcuts2.prototype.matchShortcut = function(e2, shortcut) {
            if (!shortcut) {
              return false;
            }
            if (shortcut.ctrl !== e2.ctrlKey || shortcut.meta !== e2.metaKey) {
              return false;
            }
            if (shortcut.alt !== e2.altKey || shortcut.shift !== e2.shiftKey) {
              return false;
            }
            if (e2.keyCode === shortcut.keyCode || e2.charCode && e2.charCode === shortcut.charCode) {
              e2.preventDefault();
              return true;
            }
            return false;
          };
          Shortcuts2.prototype.executeShortcutAction = function(shortcut) {
            return shortcut.func ? shortcut.func.call(shortcut.scope) : null;
          };
          return Shortcuts2;
        }();
        var create$3 = function() {
          var buttons = {};
          var menuItems = {};
          var popups = {};
          var icons = {};
          var contextMenus = {};
          var contextToolbars = {};
          var sidebars = {};
          var add4 = function(collection, type2) {
            return function(name2, spec) {
              return collection[name2.toLowerCase()] = __assign(__assign({}, spec), { type: type2 });
            };
          };
          var addIcon = function(name2, svgData) {
            return icons[name2.toLowerCase()] = svgData;
          };
          return {
            addButton: add4(buttons, "button"),
            addGroupToolbarButton: add4(buttons, "grouptoolbarbutton"),
            addToggleButton: add4(buttons, "togglebutton"),
            addMenuButton: add4(buttons, "menubutton"),
            addSplitButton: add4(buttons, "splitbutton"),
            addMenuItem: add4(menuItems, "menuitem"),
            addNestedMenuItem: add4(menuItems, "nestedmenuitem"),
            addToggleMenuItem: add4(menuItems, "togglemenuitem"),
            addAutocompleter: add4(popups, "autocompleter"),
            addContextMenu: add4(contextMenus, "contextmenu"),
            addContextToolbar: add4(contextToolbars, "contexttoolbar"),
            addContextForm: add4(contextToolbars, "contextform"),
            addSidebar: add4(sidebars, "sidebar"),
            addIcon,
            getAll: function() {
              return {
                buttons,
                menuItems,
                icons,
                popups,
                contextMenus,
                contextToolbars,
                sidebars
              };
            }
          };
        };
        var registry2 = function() {
          var bridge = create$3();
          return {
            addAutocompleter: bridge.addAutocompleter,
            addButton: bridge.addButton,
            addContextForm: bridge.addContextForm,
            addContextMenu: bridge.addContextMenu,
            addContextToolbar: bridge.addContextToolbar,
            addIcon: bridge.addIcon,
            addMenuButton: bridge.addMenuButton,
            addMenuItem: bridge.addMenuItem,
            addNestedMenuItem: bridge.addNestedMenuItem,
            addSidebar: bridge.addSidebar,
            addSplitButton: bridge.addSplitButton,
            addToggleButton: bridge.addToggleButton,
            addGroupToolbarButton: bridge.addGroupToolbarButton,
            addToggleMenuItem: bridge.addToggleMenuItem,
            getAll: bridge.getAll
          };
        };
        var DOM$1 = DOMUtils.DOM;
        var extend$3 = Tools.extend, each$2 = Tools.each;
        var resolve2 = Tools.resolve;
        var ie2 = Env.ie;
        var Editor = function() {
          function Editor2(id2, settings, editorManager) {
            var _this = this;
            this.plugins = {};
            this.contentCSS = [];
            this.contentStyles = [];
            this.loadedCSS = {};
            this.isNotDirty = false;
            this.editorManager = editorManager;
            this.documentBaseUrl = editorManager.documentBaseURL;
            extend$3(this, EditorObservable);
            this.settings = getEditorSettings(this, id2, this.documentBaseUrl, editorManager.defaultSettings, settings);
            if (this.settings.suffix) {
              editorManager.suffix = this.settings.suffix;
            }
            this.suffix = editorManager.suffix;
            if (this.settings.base_url) {
              editorManager._setBaseUrl(this.settings.base_url);
            }
            this.baseUri = editorManager.baseURI;
            if (this.settings.referrer_policy) {
              ScriptLoader.ScriptLoader._setReferrerPolicy(this.settings.referrer_policy);
              DOMUtils.DOM.styleSheetLoader._setReferrerPolicy(this.settings.referrer_policy);
            }
            AddOnManager.languageLoad = this.settings.language_load;
            AddOnManager.baseURL = editorManager.baseURL;
            this.id = id2;
            this.setDirty(false);
            this.documentBaseURI = new URI(this.settings.document_base_url, { base_uri: this.baseUri });
            this.baseURI = this.baseUri;
            this.inline = !!this.settings.inline;
            this.shortcuts = new Shortcuts(this);
            this.editorCommands = new EditorCommands(this);
            if (this.settings.cache_suffix) {
              Env.cacheSuffix = this.settings.cache_suffix.replace(/^[\?\&]+/, "");
            }
            this.ui = {
              registry: registry2(),
              styleSheetLoader: void 0,
              show: noop3,
              hide: noop3,
              enable: noop3,
              disable: noop3,
              isDisabled: never
            };
            var self2 = this;
            var modeInstance = create$4(self2);
            this.mode = modeInstance;
            this.setMode = modeInstance.set;
            editorManager.fire("SetupEditor", { editor: this });
            this.execCallback("setup", this);
            this.$ = DomQuery.overrideDefaults(function() {
              return {
                context: _this.inline ? _this.getBody() : _this.getDoc(),
                element: _this.getBody()
              };
            });
          }
          Editor2.prototype.render = function() {
            render(this);
          };
          Editor2.prototype.focus = function(skipFocus) {
            this.execCommand("mceFocus", false, skipFocus);
          };
          Editor2.prototype.hasFocus = function() {
            return hasFocus(this);
          };
          Editor2.prototype.execCallback = function(name2) {
            var x2 = [];
            for (var _i2 = 1; _i2 < arguments.length; _i2++) {
              x2[_i2 - 1] = arguments[_i2];
            }
            var self2 = this;
            var callback2 = self2.settings[name2], scope;
            if (!callback2) {
              return;
            }
            if (self2.callbackLookup && (scope = self2.callbackLookup[name2])) {
              callback2 = scope.func;
              scope = scope.scope;
            }
            if (typeof callback2 === "string") {
              scope = callback2.replace(/\.\w+$/, "");
              scope = scope ? resolve2(scope) : 0;
              callback2 = resolve2(callback2);
              self2.callbackLookup = self2.callbackLookup || {};
              self2.callbackLookup[name2] = {
                func: callback2,
                scope
              };
            }
            return callback2.apply(scope || self2, x2);
          };
          Editor2.prototype.translate = function(text) {
            return I18n.translate(text);
          };
          Editor2.prototype.getParam = function(name2, defaultVal, type2) {
            return getParam(this, name2, defaultVal, type2);
          };
          Editor2.prototype.hasPlugin = function(name2, loaded) {
            var hasPlugin = contains$3(getPlugins(this).split(/[ ,]/), name2);
            if (hasPlugin) {
              return loaded ? PluginManager.get(name2) !== void 0 : true;
            } else {
              return false;
            }
          };
          Editor2.prototype.nodeChanged = function(args) {
            this._nodeChangeDispatcher.nodeChanged(args);
          };
          Editor2.prototype.addCommand = function(name2, callback2, scope) {
            this.editorCommands.addCommand(name2, callback2, scope);
          };
          Editor2.prototype.addQueryStateHandler = function(name2, callback2, scope) {
            this.editorCommands.addQueryStateHandler(name2, callback2, scope);
          };
          Editor2.prototype.addQueryValueHandler = function(name2, callback2, scope) {
            this.editorCommands.addQueryValueHandler(name2, callback2, scope);
          };
          Editor2.prototype.addShortcut = function(pattern, desc, cmdFunc, scope) {
            this.shortcuts.add(pattern, desc, cmdFunc, scope);
          };
          Editor2.prototype.execCommand = function(cmd, ui2, value2, args) {
            return this.editorCommands.execCommand(cmd, ui2, value2, args);
          };
          Editor2.prototype.queryCommandState = function(cmd) {
            return this.editorCommands.queryCommandState(cmd);
          };
          Editor2.prototype.queryCommandValue = function(cmd) {
            return this.editorCommands.queryCommandValue(cmd);
          };
          Editor2.prototype.queryCommandSupported = function(cmd) {
            return this.editorCommands.queryCommandSupported(cmd);
          };
          Editor2.prototype.show = function() {
            var self2 = this;
            if (self2.hidden) {
              self2.hidden = false;
              if (self2.inline) {
                self2.getBody().contentEditable = "true";
              } else {
                DOM$1.show(self2.getContainer());
                DOM$1.hide(self2.id);
              }
              self2.load();
              self2.fire("show");
            }
          };
          Editor2.prototype.hide = function() {
            var self2 = this, doc2 = self2.getDoc();
            if (!self2.hidden) {
              if (ie2 && doc2 && !self2.inline) {
                doc2.execCommand("SelectAll");
              }
              self2.save();
              if (self2.inline) {
                self2.getBody().contentEditable = "false";
                if (self2 === self2.editorManager.focusedEditor) {
                  self2.editorManager.focusedEditor = null;
                }
              } else {
                DOM$1.hide(self2.getContainer());
                DOM$1.setStyle(self2.id, "display", self2.orgDisplay);
              }
              self2.hidden = true;
              self2.fire("hide");
            }
          };
          Editor2.prototype.isHidden = function() {
            return !!this.hidden;
          };
          Editor2.prototype.setProgressState = function(state, time) {
            this.fire("ProgressState", {
              state,
              time
            });
          };
          Editor2.prototype.load = function(args) {
            var self2 = this;
            var elm = self2.getElement(), html;
            if (self2.removed) {
              return "";
            }
            if (elm) {
              args = args || {};
              args.load = true;
              var value2 = isTextareaOrInput(elm) ? elm.value : elm.innerHTML;
              html = self2.setContent(value2, args);
              args.element = elm;
              if (!args.no_events) {
                self2.fire("LoadContent", args);
              }
              args.element = elm = null;
              return html;
            }
          };
          Editor2.prototype.save = function(args) {
            var self2 = this;
            var elm = self2.getElement(), html, form;
            if (!elm || !self2.initialized || self2.removed) {
              return;
            }
            args = args || {};
            args.save = true;
            args.element = elm;
            html = args.content = self2.getContent(args);
            if (!args.no_events) {
              self2.fire("SaveContent", args);
            }
            if (args.format === "raw") {
              self2.fire("RawSaveContent", args);
            }
            html = args.content;
            if (!isTextareaOrInput(elm)) {
              if (args.is_removing || !self2.inline) {
                elm.innerHTML = html;
              }
              if (form = DOM$1.getParent(self2.id, "form")) {
                each$2(form.elements, function(elm2) {
                  if (elm2.name === self2.id) {
                    elm2.value = html;
                    return false;
                  }
                });
              }
            } else {
              elm.value = html;
            }
            args.element = elm = null;
            if (args.set_dirty !== false) {
              self2.setDirty(false);
            }
            return html;
          };
          Editor2.prototype.setContent = function(content, args) {
            return setContent(this, content, args);
          };
          Editor2.prototype.getContent = function(args) {
            return getContent(this, args);
          };
          Editor2.prototype.insertContent = function(content, args) {
            if (args) {
              content = extend$3({ content }, args);
            }
            this.execCommand("mceInsertContent", false, content);
          };
          Editor2.prototype.resetContent = function(initialContent) {
            if (initialContent === void 0) {
              setContent(this, this.startContent, { format: "raw" });
            } else {
              setContent(this, initialContent);
            }
            this.undoManager.reset();
            this.setDirty(false);
            this.nodeChanged();
          };
          Editor2.prototype.isDirty = function() {
            return !this.isNotDirty;
          };
          Editor2.prototype.setDirty = function(state) {
            var oldState = !this.isNotDirty;
            this.isNotDirty = !state;
            if (state && state !== oldState) {
              this.fire("dirty");
            }
          };
          Editor2.prototype.getContainer = function() {
            var self2 = this;
            if (!self2.container) {
              self2.container = DOM$1.get(self2.editorContainer || self2.id + "_parent");
            }
            return self2.container;
          };
          Editor2.prototype.getContentAreaContainer = function() {
            return this.contentAreaContainer;
          };
          Editor2.prototype.getElement = function() {
            if (!this.targetElm) {
              this.targetElm = DOM$1.get(this.id);
            }
            return this.targetElm;
          };
          Editor2.prototype.getWin = function() {
            var self2 = this;
            var elm;
            if (!self2.contentWindow) {
              elm = self2.iframeElement;
              if (elm) {
                self2.contentWindow = elm.contentWindow;
              }
            }
            return self2.contentWindow;
          };
          Editor2.prototype.getDoc = function() {
            var self2 = this;
            var win;
            if (!self2.contentDocument) {
              win = self2.getWin();
              if (win) {
                self2.contentDocument = win.document;
              }
            }
            return self2.contentDocument;
          };
          Editor2.prototype.getBody = function() {
            var doc2 = this.getDoc();
            return this.bodyElement || (doc2 ? doc2.body : null);
          };
          Editor2.prototype.convertURL = function(url, name2, elm) {
            var self2 = this, settings = self2.settings;
            if (settings.urlconverter_callback) {
              return self2.execCallback("urlconverter_callback", url, elm, true, name2);
            }
            if (!settings.convert_urls || elm && elm.nodeName === "LINK" || url.indexOf("file:") === 0 || url.length === 0) {
              return url;
            }
            if (settings.relative_urls) {
              return self2.documentBaseURI.toRelative(url);
            }
            url = self2.documentBaseURI.toAbsolute(url, settings.remove_script_host);
            return url;
          };
          Editor2.prototype.addVisual = function(elm) {
            addVisual(this, elm);
          };
          Editor2.prototype.remove = function() {
            remove(this);
          };
          Editor2.prototype.destroy = function(automatic) {
            destroy(this, automatic);
          };
          Editor2.prototype.uploadImages = function(callback2) {
            return this.editorUpload.uploadImages(callback2);
          };
          Editor2.prototype._scanForImages = function() {
            return this.editorUpload.scanForImages();
          };
          Editor2.prototype.addButton = function() {
            throw new Error("editor.addButton has been removed in tinymce 5x, use editor.ui.registry.addButton or editor.ui.registry.addToggleButton or editor.ui.registry.addSplitButton instead");
          };
          Editor2.prototype.addSidebar = function() {
            throw new Error("editor.addSidebar has been removed in tinymce 5x, use editor.ui.registry.addSidebar instead");
          };
          Editor2.prototype.addMenuItem = function() {
            throw new Error("editor.addMenuItem has been removed in tinymce 5x, use editor.ui.registry.addMenuItem instead");
          };
          Editor2.prototype.addContextToolbar = function() {
            throw new Error("editor.addContextToolbar has been removed in tinymce 5x, use editor.ui.registry.addContextToolbar instead");
          };
          return Editor2;
        }();
        var DOM = DOMUtils.DOM;
        var explode = Tools.explode, each$1 = Tools.each, extend$2 = Tools.extend;
        var instanceCounter = 0, boundGlobalEvents = false;
        var beforeUnloadDelegate;
        var legacyEditors = [];
        var editors = [];
        var isValidLegacyKey = function(id2) {
          return id2 !== "length";
        };
        var globalEventDelegate = function(e2) {
          var type2 = e2.type;
          each$1(EditorManager.get(), function(editor) {
            switch (type2) {
              case "scroll":
                editor.fire("ScrollWindow", e2);
                break;
              case "resize":
                editor.fire("ResizeWindow", e2);
                break;
            }
          });
        };
        var toggleGlobalEvents = function(state) {
          if (state !== boundGlobalEvents) {
            if (state) {
              DomQuery(window).on("resize scroll", globalEventDelegate);
            } else {
              DomQuery(window).off("resize scroll", globalEventDelegate);
            }
            boundGlobalEvents = state;
          }
        };
        var removeEditorFromList = function(targetEditor) {
          var oldEditors = editors;
          delete legacyEditors[targetEditor.id];
          for (var i2 = 0; i2 < legacyEditors.length; i2++) {
            if (legacyEditors[i2] === targetEditor) {
              legacyEditors.splice(i2, 1);
              break;
            }
          }
          editors = filter$4(editors, function(editor) {
            return targetEditor !== editor;
          });
          if (EditorManager.activeEditor === targetEditor) {
            EditorManager.activeEditor = editors.length > 0 ? editors[0] : null;
          }
          if (EditorManager.focusedEditor === targetEditor) {
            EditorManager.focusedEditor = null;
          }
          return oldEditors.length !== editors.length;
        };
        var purgeDestroyedEditor = function(editor) {
          if (editor && editor.initialized && !(editor.getContainer() || editor.getBody()).parentNode) {
            removeEditorFromList(editor);
            editor.unbindAllNativeEvents();
            editor.destroy(true);
            editor.removed = true;
            editor = null;
          }
          return editor;
        };
        var isQuirksMode = document.compatMode !== "CSS1Compat";
        var EditorManager = __assign(__assign({}, Observable), {
          baseURI: null,
          baseURL: null,
          defaultSettings: {},
          documentBaseURL: null,
          suffix: null,
          $: DomQuery,
          majorVersion: "5",
          minorVersion: "10.2",
          releaseDate: "2021-11-17",
          editors: legacyEditors,
          i18n: I18n,
          activeEditor: null,
          focusedEditor: null,
          settings: {},
          setup: function() {
            var self2 = this;
            var baseURL, documentBaseURL, suffix = "";
            documentBaseURL = URI.getDocumentBaseUrl(document.location);
            if (/^[^:]+:\/\/\/?[^\/]+\//.test(documentBaseURL)) {
              documentBaseURL = documentBaseURL.replace(/[\?#].*$/, "").replace(/[\/\\][^\/]+$/, "");
              if (!/[\/\\]$/.test(documentBaseURL)) {
                documentBaseURL += "/";
              }
            }
            var preInit2 = window.tinymce || window.tinyMCEPreInit;
            if (preInit2) {
              baseURL = preInit2.base || preInit2.baseURL;
              suffix = preInit2.suffix;
            } else {
              var scripts = document.getElementsByTagName("script");
              for (var i2 = 0; i2 < scripts.length; i2++) {
                var src = scripts[i2].src || "";
                if (src === "") {
                  continue;
                }
                var srcScript = src.substring(src.lastIndexOf("/"));
                if (/tinymce(\.full|\.jquery|)(\.min|\.dev|)\.js/.test(src)) {
                  if (srcScript.indexOf(".min") !== -1) {
                    suffix = ".min";
                  }
                  baseURL = src.substring(0, src.lastIndexOf("/"));
                  break;
                }
              }
              if (!baseURL && document.currentScript) {
                var src = document.currentScript.src;
                if (src.indexOf(".min") !== -1) {
                  suffix = ".min";
                }
                baseURL = src.substring(0, src.lastIndexOf("/"));
              }
            }
            self2.baseURL = new URI(documentBaseURL).toAbsolute(baseURL);
            self2.documentBaseURL = documentBaseURL;
            self2.baseURI = new URI(self2.baseURL);
            self2.suffix = suffix;
            setup$l(self2);
          },
          overrideDefaults: function(defaultSettings) {
            var baseUrl = defaultSettings.base_url;
            if (baseUrl) {
              this._setBaseUrl(baseUrl);
            }
            var suffix = defaultSettings.suffix;
            if (defaultSettings.suffix) {
              this.suffix = suffix;
            }
            this.defaultSettings = defaultSettings;
            var pluginBaseUrls = defaultSettings.plugin_base_urls;
            if (pluginBaseUrls !== void 0) {
              each$j(pluginBaseUrls, function(pluginBaseUrl, pluginName) {
                AddOnManager.PluginManager.urls[pluginName] = pluginBaseUrl;
              });
            }
          },
          init: function(settings) {
            var self2 = this;
            var result;
            var invalidInlineTargets = Tools.makeMap("area base basefont br col frame hr img input isindex link meta param embed source wbr track colgroup option table tbody tfoot thead tr th td script noscript style textarea video audio iframe object menu", " ");
            var isInvalidInlineTarget = function(settings2, elm) {
              return settings2.inline && elm.tagName.toLowerCase() in invalidInlineTargets;
            };
            var createId = function(elm) {
              var id2 = elm.id;
              if (!id2) {
                id2 = get$9(elm, "name").filter(function(name2) {
                  return !DOM.get(name2);
                }).getOrThunk(DOM.uniqueId);
                elm.setAttribute("id", id2);
              }
              return id2;
            };
            var execCallback = function(name2) {
              var callback2 = settings[name2];
              if (!callback2) {
                return;
              }
              return callback2.apply(self2, []);
            };
            var hasClass2 = function(elm, className) {
              return className.constructor === RegExp ? className.test(elm.className) : DOM.hasClass(elm, className);
            };
            var findTargets = function(settings2) {
              var targets = [];
              if (Env.browser.isIE() && Env.browser.version.major < 11) {
                initError("TinyMCE does not support the browser you are using. For a list of supported browsers please see: https://www.tinymce.com/docs/get-started/system-requirements/");
                return [];
              } else if (isQuirksMode) {
                initError("Failed to initialize the editor as the document is not in standards mode. TinyMCE requires standards mode.");
                return [];
              }
              if (settings2.types) {
                each$1(settings2.types, function(type2) {
                  targets = targets.concat(DOM.select(type2.selector));
                });
                return targets;
              } else if (settings2.selector) {
                return DOM.select(settings2.selector);
              } else if (settings2.target) {
                return [settings2.target];
              }
              switch (settings2.mode) {
                case "exact":
                  var l2 = settings2.elements || "";
                  if (l2.length > 0) {
                    each$1(explode(l2), function(id2) {
                      var elm = DOM.get(id2);
                      if (elm) {
                        targets.push(elm);
                      } else {
                        each$1(document.forms, function(f2) {
                          each$1(f2.elements, function(e2) {
                            if (e2.name === id2) {
                              id2 = "mce_editor_" + instanceCounter++;
                              DOM.setAttrib(e2, "id", id2);
                              targets.push(e2);
                            }
                          });
                        });
                      }
                    });
                  }
                  break;
                case "textareas":
                case "specific_textareas":
                  each$1(DOM.select("textarea"), function(elm) {
                    if (settings2.editor_deselector && hasClass2(elm, settings2.editor_deselector)) {
                      return;
                    }
                    if (!settings2.editor_selector || hasClass2(elm, settings2.editor_selector)) {
                      targets.push(elm);
                    }
                  });
                  break;
              }
              return targets;
            };
            var provideResults = function(editors2) {
              result = editors2;
            };
            var initEditors = function() {
              var initCount = 0;
              var editors2 = [];
              var targets;
              var createEditor = function(id2, settings2, targetElm) {
                var editor = new Editor(id2, settings2, self2);
                editors2.push(editor);
                editor.on("init", function() {
                  if (++initCount === targets.length) {
                    provideResults(editors2);
                  }
                });
                editor.targetElm = editor.targetElm || targetElm;
                editor.render();
              };
              DOM.unbind(window, "ready", initEditors);
              execCallback("onpageload");
              targets = DomQuery.unique(findTargets(settings));
              if (settings.types) {
                each$1(settings.types, function(type2) {
                  Tools.each(targets, function(elm) {
                    if (DOM.is(elm, type2.selector)) {
                      createEditor(createId(elm), extend$2({}, settings, type2), elm);
                      return false;
                    }
                    return true;
                  });
                });
                return;
              }
              Tools.each(targets, function(elm) {
                purgeDestroyedEditor(self2.get(elm.id));
              });
              targets = Tools.grep(targets, function(elm) {
                return !self2.get(elm.id);
              });
              if (targets.length === 0) {
                provideResults([]);
              } else {
                each$1(targets, function(elm) {
                  if (isInvalidInlineTarget(settings, elm)) {
                    initError("Could not initialize inline editor on invalid inline target element", elm);
                  } else {
                    createEditor(createId(elm), settings, elm);
                  }
                });
              }
            };
            self2.settings = settings;
            DOM.bind(window, "ready", initEditors);
            return new promiseObj(function(resolve3) {
              if (result) {
                resolve3(result);
              } else {
                provideResults = function(editors2) {
                  resolve3(editors2);
                };
              }
            });
          },
          get: function(id2) {
            if (arguments.length === 0) {
              return editors.slice(0);
            } else if (isString$1(id2)) {
              return find$3(editors, function(editor) {
                return editor.id === id2;
              }).getOr(null);
            } else if (isNumber2(id2)) {
              return editors[id2] ? editors[id2] : null;
            } else {
              return null;
            }
          },
          add: function(editor) {
            var self2 = this;
            var existingEditor = legacyEditors[editor.id];
            if (existingEditor === editor) {
              return editor;
            }
            if (self2.get(editor.id) === null) {
              if (isValidLegacyKey(editor.id)) {
                legacyEditors[editor.id] = editor;
              }
              legacyEditors.push(editor);
              editors.push(editor);
            }
            toggleGlobalEvents(true);
            self2.activeEditor = editor;
            self2.fire("AddEditor", { editor });
            if (!beforeUnloadDelegate) {
              beforeUnloadDelegate = function(e2) {
                var event = self2.fire("BeforeUnload");
                if (event.returnValue) {
                  e2.preventDefault();
                  e2.returnValue = event.returnValue;
                  return event.returnValue;
                }
              };
              window.addEventListener("beforeunload", beforeUnloadDelegate);
            }
            return editor;
          },
          createEditor: function(id2, settings) {
            return this.add(new Editor(id2, settings, this));
          },
          remove: function(selector) {
            var self2 = this;
            var i2, editor;
            if (!selector) {
              for (i2 = editors.length - 1; i2 >= 0; i2--) {
                self2.remove(editors[i2]);
              }
              return;
            }
            if (isString$1(selector)) {
              each$1(DOM.select(selector), function(elm) {
                editor = self2.get(elm.id);
                if (editor) {
                  self2.remove(editor);
                }
              });
              return;
            }
            editor = selector;
            if (isNull(self2.get(editor.id))) {
              return null;
            }
            if (removeEditorFromList(editor)) {
              self2.fire("RemoveEditor", { editor });
            }
            if (editors.length === 0) {
              window.removeEventListener("beforeunload", beforeUnloadDelegate);
            }
            editor.remove();
            toggleGlobalEvents(editors.length > 0);
            return editor;
          },
          execCommand: function(cmd, ui2, value2) {
            var self2 = this, editor = self2.get(value2);
            switch (cmd) {
              case "mceAddEditor":
                if (!self2.get(value2)) {
                  new Editor(value2, self2.settings, self2).render();
                }
                return true;
              case "mceRemoveEditor":
                if (editor) {
                  editor.remove();
                }
                return true;
              case "mceToggleEditor":
                if (!editor) {
                  self2.execCommand("mceAddEditor", false, value2);
                  return true;
                }
                if (editor.isHidden()) {
                  editor.show();
                } else {
                  editor.hide();
                }
                return true;
            }
            if (self2.activeEditor) {
              return self2.activeEditor.execCommand(cmd, ui2, value2);
            }
            return false;
          },
          triggerSave: function() {
            each$1(editors, function(editor) {
              editor.save();
            });
          },
          addI18n: function(code, items) {
            I18n.add(code, items);
          },
          translate: function(text) {
            return I18n.translate(text);
          },
          setActive: function(editor) {
            var activeEditor = this.activeEditor;
            if (this.activeEditor !== editor) {
              if (activeEditor) {
                activeEditor.fire("deactivate", { relatedTarget: editor });
              }
              editor.fire("activate", { relatedTarget: activeEditor });
            }
            this.activeEditor = editor;
          },
          _setBaseUrl: function(baseUrl) {
            this.baseURL = new URI(this.documentBaseURL).toAbsolute(baseUrl.replace(/\/+$/, ""));
            this.baseURI = new URI(this.baseURL);
          }
        });
        EditorManager.setup();
        var min$1 = Math.min, max$1 = Math.max, round$1 = Math.round;
        var relativePosition = function(rect, targetRect, rel) {
          var x2 = targetRect.x;
          var y2 = targetRect.y;
          var w2 = rect.w;
          var h3 = rect.h;
          var targetW = targetRect.w;
          var targetH = targetRect.h;
          var relChars = (rel || "").split("");
          if (relChars[0] === "b") {
            y2 += targetH;
          }
          if (relChars[1] === "r") {
            x2 += targetW;
          }
          if (relChars[0] === "c") {
            y2 += round$1(targetH / 2);
          }
          if (relChars[1] === "c") {
            x2 += round$1(targetW / 2);
          }
          if (relChars[3] === "b") {
            y2 -= h3;
          }
          if (relChars[4] === "r") {
            x2 -= w2;
          }
          if (relChars[3] === "c") {
            y2 -= round$1(h3 / 2);
          }
          if (relChars[4] === "c") {
            x2 -= round$1(w2 / 2);
          }
          return create$2(x2, y2, w2, h3);
        };
        var findBestRelativePosition = function(rect, targetRect, constrainRect, rels) {
          var pos, i2;
          for (i2 = 0; i2 < rels.length; i2++) {
            pos = relativePosition(rect, targetRect, rels[i2]);
            if (pos.x >= constrainRect.x && pos.x + pos.w <= constrainRect.w + constrainRect.x && pos.y >= constrainRect.y && pos.y + pos.h <= constrainRect.h + constrainRect.y) {
              return rels[i2];
            }
          }
          return null;
        };
        var inflate = function(rect, w2, h3) {
          return create$2(rect.x - w2, rect.y - h3, rect.w + w2 * 2, rect.h + h3 * 2);
        };
        var intersect = function(rect, cropRect) {
          var x1 = max$1(rect.x, cropRect.x);
          var y1 = max$1(rect.y, cropRect.y);
          var x2 = min$1(rect.x + rect.w, cropRect.x + cropRect.w);
          var y2 = min$1(rect.y + rect.h, cropRect.y + cropRect.h);
          if (x2 - x1 < 0 || y2 - y1 < 0) {
            return null;
          }
          return create$2(x1, y1, x2 - x1, y2 - y1);
        };
        var clamp = function(rect, clampRect, fixedSize) {
          var x1 = rect.x;
          var y1 = rect.y;
          var x2 = rect.x + rect.w;
          var y2 = rect.y + rect.h;
          var cx2 = clampRect.x + clampRect.w;
          var cy2 = clampRect.y + clampRect.h;
          var underflowX1 = max$1(0, clampRect.x - x1);
          var underflowY1 = max$1(0, clampRect.y - y1);
          var overflowX2 = max$1(0, x2 - cx2);
          var overflowY2 = max$1(0, y2 - cy2);
          x1 += underflowX1;
          y1 += underflowY1;
          if (fixedSize) {
            x2 += underflowX1;
            y2 += underflowY1;
            x1 -= overflowX2;
            y1 -= overflowY2;
          }
          x2 -= overflowX2;
          y2 -= overflowY2;
          return create$2(x1, y1, x2 - x1, y2 - y1);
        };
        var create$2 = function(x2, y2, w2, h3) {
          return {
            x: x2,
            y: y2,
            w: w2,
            h: h3
          };
        };
        var fromClientRect = function(clientRect) {
          return create$2(clientRect.left, clientRect.top, clientRect.width, clientRect.height);
        };
        var Rect = {
          inflate,
          relativePosition,
          findBestRelativePosition,
          intersect,
          clamp,
          create: create$2,
          fromClientRect
        };
        var awaiter = function(resolveCb, rejectCb, timeout) {
          if (timeout === void 0) {
            timeout = 1e3;
          }
          var done2 = false;
          var timer = null;
          var complete = function(completer) {
            return function() {
              var args = [];
              for (var _i2 = 0; _i2 < arguments.length; _i2++) {
                args[_i2] = arguments[_i2];
              }
              if (!done2) {
                done2 = true;
                if (timer !== null) {
                  clearTimeout(timer);
                  timer = null;
                }
                completer.apply(null, args);
              }
            };
          };
          var resolve3 = complete(resolveCb);
          var reject = complete(rejectCb);
          var start5 = function() {
            var args = [];
            for (var _i2 = 0; _i2 < arguments.length; _i2++) {
              args[_i2] = arguments[_i2];
            }
            if (!done2 && timer === null) {
              timer = setTimeout(function() {
                return reject.apply(null, args);
              }, timeout);
            }
          };
          return {
            start: start5,
            resolve: resolve3,
            reject
          };
        };
        var create$1 = function() {
          var tasks = {};
          var resultFns = {};
          var load = function(id2, url) {
            var loadErrMsg = 'Script at URL "' + url + '" failed to load';
            var runErrMsg = 'Script at URL "' + url + "\" did not call `tinymce.Resource.add('" + id2 + "', data)` within 1 second";
            if (tasks[id2] !== void 0) {
              return tasks[id2];
            } else {
              var task = new promiseObj(function(resolve3, reject) {
                var waiter = awaiter(resolve3, reject);
                resultFns[id2] = waiter.resolve;
                ScriptLoader.ScriptLoader.loadScript(url, function() {
                  return waiter.start(runErrMsg);
                }, function() {
                  return waiter.reject(loadErrMsg);
                });
              });
              tasks[id2] = task;
              return task;
            }
          };
          var add4 = function(id2, data2) {
            if (resultFns[id2] !== void 0) {
              resultFns[id2](data2);
              delete resultFns[id2];
            }
            tasks[id2] = promiseObj.resolve(data2);
          };
          return {
            load,
            add: add4
          };
        };
        var Resource = create$1();
        var each2 = Tools.each, extend$1 = Tools.extend;
        var extendClass, initializing;
        var Class = function() {
        };
        Class.extend = extendClass = function(props) {
          var self2 = this;
          var _super = self2.prototype;
          var Class2 = function() {
            var i2, mixins, mixin;
            var self3 = this;
            if (!initializing) {
              if (self3.init) {
                self3.init.apply(self3, arguments);
              }
              mixins = self3.Mixins;
              if (mixins) {
                i2 = mixins.length;
                while (i2--) {
                  mixin = mixins[i2];
                  if (mixin.init) {
                    mixin.init.apply(self3, arguments);
                  }
                }
              }
            }
          };
          var dummy = function() {
            return this;
          };
          var createMethod = function(name2, fn3) {
            return function() {
              var self3 = this;
              var tmp = self3._super;
              self3._super = _super[name2];
              var ret = fn3.apply(self3, arguments);
              self3._super = tmp;
              return ret;
            };
          };
          initializing = true;
          var prototype = new self2();
          initializing = false;
          if (props.Mixins) {
            each2(props.Mixins, function(mixin) {
              for (var name_1 in mixin) {
                if (name_1 !== "init") {
                  props[name_1] = mixin[name_1];
                }
              }
            });
            if (_super.Mixins) {
              props.Mixins = _super.Mixins.concat(props.Mixins);
            }
          }
          if (props.Methods) {
            each2(props.Methods.split(","), function(name2) {
              props[name2] = dummy;
            });
          }
          if (props.Properties) {
            each2(props.Properties.split(","), function(name2) {
              var fieldName = "_" + name2;
              props[name2] = function(value2) {
                var self3 = this;
                if (value2 !== void 0) {
                  self3[fieldName] = value2;
                  return self3;
                }
                return self3[fieldName];
              };
            });
          }
          if (props.Statics) {
            each2(props.Statics, function(func, name2) {
              Class2[name2] = func;
            });
          }
          if (props.Defaults && _super.Defaults) {
            props.Defaults = extend$1({}, _super.Defaults, props.Defaults);
          }
          each$j(props, function(member, name2) {
            if (typeof member === "function" && _super[name2]) {
              prototype[name2] = createMethod(name2, member);
            } else {
              prototype[name2] = member;
            }
          });
          Class2.prototype = prototype;
          Class2.constructor = Class2;
          Class2.extend = extendClass;
          return Class2;
        };
        var min2 = Math.min, max2 = Math.max, round3 = Math.round;
        var Color2 = function(value2) {
          var self2 = {};
          var r3 = 0, g2 = 0, b2 = 0;
          var rgb2hsv = function(r4, g3, b3) {
            var h3, s2, v2;
            h3 = 0;
            s2 = 0;
            v2 = 0;
            r4 = r4 / 255;
            g3 = g3 / 255;
            b3 = b3 / 255;
            var minRGB = min2(r4, min2(g3, b3));
            var maxRGB = max2(r4, max2(g3, b3));
            if (minRGB === maxRGB) {
              v2 = minRGB;
              return {
                h: 0,
                s: 0,
                v: v2 * 100
              };
            }
            var d2 = r4 === minRGB ? g3 - b3 : b3 === minRGB ? r4 - g3 : b3 - r4;
            h3 = r4 === minRGB ? 3 : b3 === minRGB ? 1 : 5;
            h3 = 60 * (h3 - d2 / (maxRGB - minRGB));
            s2 = (maxRGB - minRGB) / maxRGB;
            v2 = maxRGB;
            return {
              h: round3(h3),
              s: round3(s2 * 100),
              v: round3(v2 * 100)
            };
          };
          var hsvToRgb = function(hue2, saturation, brightness) {
            hue2 = (parseInt(hue2, 10) || 0) % 360;
            saturation = parseInt(saturation, 10) / 100;
            brightness = parseInt(brightness, 10) / 100;
            saturation = max2(0, min2(saturation, 1));
            brightness = max2(0, min2(brightness, 1));
            if (saturation === 0) {
              r3 = g2 = b2 = round3(255 * brightness);
              return;
            }
            var side = hue2 / 60;
            var chroma = brightness * saturation;
            var x2 = chroma * (1 - Math.abs(side % 2 - 1));
            var match3 = brightness - chroma;
            switch (Math.floor(side)) {
              case 0:
                r3 = chroma;
                g2 = x2;
                b2 = 0;
                break;
              case 1:
                r3 = x2;
                g2 = chroma;
                b2 = 0;
                break;
              case 2:
                r3 = 0;
                g2 = chroma;
                b2 = x2;
                break;
              case 3:
                r3 = 0;
                g2 = x2;
                b2 = chroma;
                break;
              case 4:
                r3 = x2;
                g2 = 0;
                b2 = chroma;
                break;
              case 5:
                r3 = chroma;
                g2 = 0;
                b2 = x2;
                break;
              default:
                r3 = g2 = b2 = 0;
            }
            r3 = round3(255 * (r3 + match3));
            g2 = round3(255 * (g2 + match3));
            b2 = round3(255 * (b2 + match3));
          };
          var toHex2 = function() {
            var hex2 = function(val) {
              val = parseInt(val, 10).toString(16);
              return val.length > 1 ? val : "0" + val;
            };
            return "#" + hex2(r3) + hex2(g2) + hex2(b2);
          };
          var toRgb = function() {
            return {
              r: r3,
              g: g2,
              b: b2
            };
          };
          var toHsv = function() {
            return rgb2hsv(r3, g2, b2);
          };
          var parse3 = function(value3) {
            var matches2;
            if (typeof value3 === "object") {
              if ("r" in value3) {
                r3 = value3.r;
                g2 = value3.g;
                b2 = value3.b;
              } else if ("v" in value3) {
                hsvToRgb(value3.h, value3.s, value3.v);
              }
            } else {
              if (matches2 = /rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)[^\)]*\)/gi.exec(value3)) {
                r3 = parseInt(matches2[1], 10);
                g2 = parseInt(matches2[2], 10);
                b2 = parseInt(matches2[3], 10);
              } else if (matches2 = /#([0-F]{2})([0-F]{2})([0-F]{2})/gi.exec(value3)) {
                r3 = parseInt(matches2[1], 16);
                g2 = parseInt(matches2[2], 16);
                b2 = parseInt(matches2[3], 16);
              } else if (matches2 = /#([0-F])([0-F])([0-F])/gi.exec(value3)) {
                r3 = parseInt(matches2[1] + matches2[1], 16);
                g2 = parseInt(matches2[2] + matches2[2], 16);
                b2 = parseInt(matches2[3] + matches2[3], 16);
              }
            }
            r3 = r3 < 0 ? 0 : r3 > 255 ? 255 : r3;
            g2 = g2 < 0 ? 0 : g2 > 255 ? 255 : g2;
            b2 = b2 < 0 ? 0 : b2 > 255 ? 255 : b2;
            return self2;
          };
          if (value2) {
            parse3(value2);
          }
          self2.toRgb = toRgb;
          self2.toHsv = toHsv;
          self2.toHex = toHex2;
          self2.parse = parse3;
          return self2;
        };
        var serialize = function(obj) {
          var data2 = JSON.stringify(obj);
          if (!isString$1(data2)) {
            return data2;
          }
          return data2.replace(/[\u0080-\uFFFF]/g, function(match3) {
            var hexCode = match3.charCodeAt(0).toString(16);
            return "\\u" + "0000".substring(hexCode.length) + hexCode;
          });
        };
        var JSONUtils = {
          serialize,
          parse: function(text) {
            try {
              return JSON.parse(text);
            } catch (ex) {
            }
          }
        };
        var JSONP = {
          callbacks: {},
          count: 0,
          send: function(settings) {
            var self2 = this, dom2 = DOMUtils.DOM, count2 = settings.count !== void 0 ? settings.count : self2.count;
            var id2 = "tinymce_jsonp_" + count2;
            self2.callbacks[count2] = function(json) {
              dom2.remove(id2);
              delete self2.callbacks[count2];
              settings.callback(json);
            };
            dom2.add(dom2.doc.body, "script", {
              id: id2,
              src: settings.url,
              type: "text/javascript"
            });
            self2.count++;
          }
        };
        var XHR = __assign(__assign({}, Observable), {
          send: function(settings) {
            var xhr, count2 = 0;
            var ready = function() {
              if (!settings.async || xhr.readyState === 4 || count2++ > 1e4) {
                if (settings.success && count2 < 1e4 && xhr.status === 200) {
                  settings.success.call(settings.success_scope, "" + xhr.responseText, xhr, settings);
                } else if (settings.error) {
                  settings.error.call(settings.error_scope, count2 > 1e4 ? "TIMED_OUT" : "GENERAL", xhr, settings);
                }
                xhr = null;
              } else {
                Delay.setTimeout(ready, 10);
              }
            };
            settings.scope = settings.scope || this;
            settings.success_scope = settings.success_scope || settings.scope;
            settings.error_scope = settings.error_scope || settings.scope;
            settings.async = settings.async !== false;
            settings.data = settings.data || "";
            XHR.fire("beforeInitialize", { settings });
            xhr = new XMLHttpRequest();
            if (xhr.overrideMimeType) {
              xhr.overrideMimeType(settings.content_type);
            }
            xhr.open(settings.type || (settings.data ? "POST" : "GET"), settings.url, settings.async);
            if (settings.crossDomain) {
              xhr.withCredentials = true;
            }
            if (settings.content_type) {
              xhr.setRequestHeader("Content-Type", settings.content_type);
            }
            if (settings.requestheaders) {
              Tools.each(settings.requestheaders, function(header) {
                xhr.setRequestHeader(header.key, header.value);
              });
            }
            xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
            xhr = XHR.fire("beforeSend", {
              xhr,
              settings
            }).xhr;
            xhr.send(settings.data);
            if (!settings.async) {
              return ready();
            }
            Delay.setTimeout(ready, 10);
          }
        });
        var extend4 = Tools.extend;
        var JSONRequest = function() {
          function JSONRequest2(settings) {
            this.settings = extend4({}, settings);
            this.count = 0;
          }
          JSONRequest2.sendRPC = function(o2) {
            return new JSONRequest2().send(o2);
          };
          JSONRequest2.prototype.send = function(args) {
            var ecb = args.error, scb = args.success;
            var xhrArgs = extend4(this.settings, args);
            xhrArgs.success = function(c2, x2) {
              c2 = JSONUtils.parse(c2);
              if (typeof c2 === "undefined") {
                c2 = { error: "JSON Parse error." };
              }
              if (c2.error) {
                ecb.call(xhrArgs.error_scope || xhrArgs.scope, c2.error, x2);
              } else {
                scb.call(xhrArgs.success_scope || xhrArgs.scope, c2.result);
              }
            };
            xhrArgs.error = function(ty, x2) {
              if (ecb) {
                ecb.call(xhrArgs.error_scope || xhrArgs.scope, ty, x2);
              }
            };
            xhrArgs.data = JSONUtils.serialize({
              id: args.id || "c" + this.count++,
              method: args.method,
              params: args.params
            });
            xhrArgs.content_type = "application/json";
            XHR.send(xhrArgs);
          };
          return JSONRequest2;
        }();
        var create = function() {
          return function() {
            var data2 = {};
            var keys2 = [];
            var storage = {
              getItem: function(key) {
                var item = data2[key];
                return item ? item : null;
              },
              setItem: function(key, value2) {
                keys2.push(key);
                data2[key] = String(value2);
              },
              key: function(index) {
                return keys2[index];
              },
              removeItem: function(key) {
                keys2 = keys2.filter(function(k2) {
                  return k2 === key;
                });
                delete data2[key];
              },
              clear: function() {
                keys2 = [];
                data2 = {};
              },
              length: 0
            };
            Object.defineProperty(storage, "length", {
              get: function() {
                return keys2.length;
              },
              configurable: false,
              enumerable: false
            });
            return storage;
          }();
        };
        var localStorage;
        try {
          var test = "__storage_test__";
          localStorage = window.localStorage;
          localStorage.setItem(test, test);
          localStorage.removeItem(test);
        } catch (e2) {
          localStorage = create();
        }
        var LocalStorage = localStorage;
        var publicApi = {
          geom: { Rect },
          util: {
            Promise: promiseObj,
            Delay,
            Tools,
            VK,
            URI,
            Class,
            EventDispatcher,
            Observable,
            I18n,
            XHR,
            JSON: JSONUtils,
            JSONRequest,
            JSONP,
            LocalStorage,
            Color: Color2,
            ImageUploader
          },
          dom: {
            EventUtils,
            Sizzle,
            DomQuery,
            TreeWalker: DomTreeWalker,
            TextSeeker,
            DOMUtils,
            ScriptLoader,
            RangeUtils,
            Serializer: DomSerializer,
            StyleSheetLoader,
            ControlSelection,
            BookmarkManager,
            Selection: EditorSelection,
            Event: EventUtils.Event
          },
          html: {
            Styles,
            Entities,
            Node: AstNode,
            Schema,
            SaxParser,
            DomParser,
            Writer,
            Serializer: HtmlSerializer
          },
          Env,
          AddOnManager,
          Annotator,
          Formatter,
          UndoManager,
          EditorCommands,
          WindowManager,
          NotificationManager,
          EditorObservable,
          Shortcuts,
          Editor,
          FocusManager,
          EditorManager,
          DOM: DOMUtils.DOM,
          ScriptLoader: ScriptLoader.ScriptLoader,
          PluginManager,
          ThemeManager,
          IconManager,
          Resource,
          trim: Tools.trim,
          isArray: Tools.isArray,
          is: Tools.is,
          toArray: Tools.toArray,
          makeMap: Tools.makeMap,
          each: Tools.each,
          map: Tools.map,
          grep: Tools.grep,
          inArray: Tools.inArray,
          extend: Tools.extend,
          create: Tools.create,
          walk: Tools.walk,
          createNS: Tools.createNS,
          resolve: Tools.resolve,
          explode: Tools.explode,
          _addCacheSuffix: Tools._addCacheSuffix,
          isOpera: Env.opera,
          isWebKit: Env.webkit,
          isIE: Env.ie,
          isGecko: Env.gecko,
          isMac: Env.mac
        };
        var tinymce3 = Tools.extend(EditorManager, publicApi);
        var exportToModuleLoaders = function(tinymce4) {
          if (typeof module === "object") {
            try {
              module.exports = tinymce4;
            } catch (_2) {
            }
          }
        };
        var exportToWindowGlobal = function(tinymce4) {
          window.tinymce = tinymce4;
          window.tinyMCE = tinymce4;
        };
        exportToWindowGlobal(tinymce3);
        exportToModuleLoaders(tinymce3);
      })();
    }
  });

  // ../../node_modules/tinymce/plugins/print/plugin.js
  var require_plugin = __commonJS({
    "../../node_modules/tinymce/plugins/print/plugin.js"() {
      (function() {
        "use strict";
        var global$1 = tinymce.util.Tools.resolve("tinymce.PluginManager");
        var global2 = tinymce.util.Tools.resolve("tinymce.Env");
        var register$1 = function(editor) {
          editor.addCommand("mcePrint", function() {
            if (global2.browser.isIE()) {
              editor.getDoc().execCommand("print", false, null);
            } else {
              editor.getWin().print();
            }
          });
        };
        var register = function(editor) {
          var onAction = function() {
            return editor.execCommand("mcePrint");
          };
          editor.ui.registry.addButton("print", {
            icon: "print",
            tooltip: "Print",
            onAction
          });
          editor.ui.registry.addMenuItem("print", {
            text: "Print...",
            icon: "print",
            onAction
          });
        };
        function Plugin() {
          global$1.add("print", function(editor) {
            register$1(editor);
            register(editor);
            editor.addShortcut("Meta+P", "", "mcePrint");
          });
        }
        Plugin();
      })();
    }
  });

  // ../../node_modules/tinymce/plugins/preview/plugin.js
  var require_plugin2 = __commonJS({
    "../../node_modules/tinymce/plugins/preview/plugin.js"() {
      (function() {
        "use strict";
        var global$2 = tinymce.util.Tools.resolve("tinymce.PluginManager");
        var global$1 = tinymce.util.Tools.resolve("tinymce.Env");
        var global2 = tinymce.util.Tools.resolve("tinymce.util.Tools");
        var getContentStyle = function(editor) {
          return editor.getParam("content_style", "", "string");
        };
        var shouldUseContentCssCors = function(editor) {
          return editor.getParam("content_css_cors", false, "boolean");
        };
        var getBodyClassByHash = function(editor) {
          var bodyClass = editor.getParam("body_class", "", "hash");
          return bodyClass[editor.id] || "";
        };
        var getBodyClass = function(editor) {
          var bodyClass = editor.getParam("body_class", "", "string");
          if (bodyClass.indexOf("=") === -1) {
            return bodyClass;
          } else {
            return getBodyClassByHash(editor);
          }
        };
        var getBodyIdByHash = function(editor) {
          var bodyId = editor.getParam("body_id", "", "hash");
          return bodyId[editor.id] || bodyId;
        };
        var getBodyId = function(editor) {
          var bodyId = editor.getParam("body_id", "tinymce", "string");
          if (bodyId.indexOf("=") === -1) {
            return bodyId;
          } else {
            return getBodyIdByHash(editor);
          }
        };
        var getPreviewHtml = function(editor) {
          var headHtml = "";
          var encode = editor.dom.encode;
          var contentStyle = getContentStyle(editor);
          headHtml += '<base href="' + encode(editor.documentBaseURI.getURI()) + '">';
          var cors = shouldUseContentCssCors(editor) ? ' crossorigin="anonymous"' : "";
          global2.each(editor.contentCSS, function(url) {
            headHtml += '<link type="text/css" rel="stylesheet" href="' + encode(editor.documentBaseURI.toAbsolute(url)) + '"' + cors + ">";
          });
          if (contentStyle) {
            headHtml += '<style type="text/css">' + contentStyle + "</style>";
          }
          var bodyId = getBodyId(editor);
          var bodyClass = getBodyClass(editor);
          var isMetaKeyPressed = global$1.mac ? "e.metaKey" : "e.ctrlKey && !e.altKey";
          var preventClicksOnLinksScript = '<script>document.addEventListener && document.addEventListener("click", function(e) {for (var elm = e.target; elm; elm = elm.parentNode) {if (elm.nodeName === "A" && !(' + isMetaKeyPressed + ")) {e.preventDefault();}}}, false);<\/script> ";
          var directionality = editor.getBody().dir;
          var dirAttr = directionality ? ' dir="' + encode(directionality) + '"' : "";
          var previewHtml = "<!DOCTYPE html><html><head>" + headHtml + '</head><body id="' + encode(bodyId) + '" class="mce-content-body ' + encode(bodyClass) + '"' + dirAttr + ">" + editor.getContent() + preventClicksOnLinksScript + "</body></html>";
          return previewHtml;
        };
        var open = function(editor) {
          var content = getPreviewHtml(editor);
          var dataApi = editor.windowManager.open({
            title: "Preview",
            size: "large",
            body: {
              type: "panel",
              items: [{
                name: "preview",
                type: "iframe",
                sandboxed: true
              }]
            },
            buttons: [{
              type: "cancel",
              name: "close",
              text: "Close",
              primary: true
            }],
            initialData: { preview: content }
          });
          dataApi.focus("close");
        };
        var register$1 = function(editor) {
          editor.addCommand("mcePreview", function() {
            open(editor);
          });
        };
        var register = function(editor) {
          var onAction = function() {
            return editor.execCommand("mcePreview");
          };
          editor.ui.registry.addButton("preview", {
            icon: "preview",
            tooltip: "Preview",
            onAction
          });
          editor.ui.registry.addMenuItem("preview", {
            icon: "preview",
            text: "Preview",
            onAction
          });
        };
        function Plugin() {
          global$2.add("preview", function(editor) {
            register$1(editor);
            register(editor);
          });
        }
        Plugin();
      })();
    }
  });

  // ../../node_modules/tinymce/plugins/paste/plugin.js
  var require_plugin3 = __commonJS({
    "../../node_modules/tinymce/plugins/paste/plugin.js"() {
      (function() {
        "use strict";
        var Cell = function(initial) {
          var value2 = initial;
          var get2 = function() {
            return value2;
          };
          var set2 = function(v2) {
            value2 = v2;
          };
          return {
            get: get2,
            set: set2
          };
        };
        var global$b = tinymce.util.Tools.resolve("tinymce.PluginManager");
        var hasProPlugin = function(editor) {
          if (editor.hasPlugin("powerpaste", true)) {
            if (typeof window.console !== "undefined" && window.console.log) {
              window.console.log("PowerPaste is incompatible with Paste plugin! Remove 'paste' from the 'plugins' option.");
            }
            return true;
          } else {
            return false;
          }
        };
        var get = function(clipboard) {
          return { clipboard };
        };
        var typeOf = function(x2) {
          var t2 = typeof x2;
          if (x2 === null) {
            return "null";
          } else if (t2 === "object" && (Array.prototype.isPrototypeOf(x2) || x2.constructor && x2.constructor.name === "Array")) {
            return "array";
          } else if (t2 === "object" && (String.prototype.isPrototypeOf(x2) || x2.constructor && x2.constructor.name === "String")) {
            return "string";
          } else {
            return t2;
          }
        };
        var isType = function(type) {
          return function(value2) {
            return typeOf(value2) === type;
          };
        };
        var isSimpleType = function(type) {
          return function(value2) {
            return typeof value2 === type;
          };
        };
        var isArray2 = isType("array");
        var isNullable = function(a2) {
          return a2 === null || a2 === void 0;
        };
        var isNonNullable = function(a2) {
          return !isNullable(a2);
        };
        var isFunction2 = isSimpleType("function");
        var noop3 = function() {
        };
        var constant = function(value2) {
          return function() {
            return value2;
          };
        };
        var identity = function(x2) {
          return x2;
        };
        var never = constant(false);
        var always = constant(true);
        var none = function() {
          return NONE;
        };
        var NONE = function() {
          var call = function(thunk) {
            return thunk();
          };
          var id2 = identity;
          var me2 = {
            fold: function(n2, _s) {
              return n2();
            },
            isSome: never,
            isNone: always,
            getOr: id2,
            getOrThunk: call,
            getOrDie: function(msg) {
              throw new Error(msg || "error: getOrDie called on none.");
            },
            getOrNull: constant(null),
            getOrUndefined: constant(void 0),
            or: id2,
            orThunk: call,
            map: none,
            each: noop3,
            bind: none,
            exists: never,
            forall: always,
            filter: function() {
              return none();
            },
            toArray: function() {
              return [];
            },
            toString: constant("none()")
          };
          return me2;
        }();
        var some = function(a2) {
          var constant_a = constant(a2);
          var self2 = function() {
            return me2;
          };
          var bind2 = function(f2) {
            return f2(a2);
          };
          var me2 = {
            fold: function(n2, s2) {
              return s2(a2);
            },
            isSome: always,
            isNone: never,
            getOr: constant_a,
            getOrThunk: constant_a,
            getOrDie: constant_a,
            getOrNull: constant_a,
            getOrUndefined: constant_a,
            or: self2,
            orThunk: self2,
            map: function(f2) {
              return some(f2(a2));
            },
            each: function(f2) {
              f2(a2);
            },
            bind: bind2,
            exists: bind2,
            forall: bind2,
            filter: function(f2) {
              return f2(a2) ? me2 : NONE;
            },
            toArray: function() {
              return [a2];
            },
            toString: function() {
              return "some(" + a2 + ")";
            }
          };
          return me2;
        };
        var from$1 = function(value2) {
          return value2 === null || value2 === void 0 ? NONE : some(value2);
        };
        var Optional = {
          some,
          none,
          from: from$1
        };
        var nativeSlice = Array.prototype.slice;
        var nativePush = Array.prototype.push;
        var exists = function(xs, pred) {
          for (var i2 = 0, len = xs.length; i2 < len; i2++) {
            var x2 = xs[i2];
            if (pred(x2, i2)) {
              return true;
            }
          }
          return false;
        };
        var map3 = function(xs, f2) {
          var len = xs.length;
          var r2 = new Array(len);
          for (var i2 = 0; i2 < len; i2++) {
            var x2 = xs[i2];
            r2[i2] = f2(x2, i2);
          }
          return r2;
        };
        var each2 = function(xs, f2) {
          for (var i2 = 0, len = xs.length; i2 < len; i2++) {
            var x2 = xs[i2];
            f2(x2, i2);
          }
        };
        var filter$1 = function(xs, pred) {
          var r2 = [];
          for (var i2 = 0, len = xs.length; i2 < len; i2++) {
            var x2 = xs[i2];
            if (pred(x2, i2)) {
              r2.push(x2);
            }
          }
          return r2;
        };
        var foldl = function(xs, f2, acc) {
          each2(xs, function(x2, i2) {
            acc = f2(acc, x2, i2);
          });
          return acc;
        };
        var flatten = function(xs) {
          var r2 = [];
          for (var i2 = 0, len = xs.length; i2 < len; ++i2) {
            if (!isArray2(xs[i2])) {
              throw new Error("Arr.flatten item " + i2 + " was not an array, input: " + xs);
            }
            nativePush.apply(r2, xs[i2]);
          }
          return r2;
        };
        var bind = function(xs, f2) {
          return flatten(map3(xs, f2));
        };
        var from = isFunction2(Array.from) ? Array.from : function(x2) {
          return nativeSlice.call(x2);
        };
        var __assign = function() {
          __assign = Object.assign || function __assign2(t2) {
            for (var s2, i2 = 1, n2 = arguments.length; i2 < n2; i2++) {
              s2 = arguments[i2];
              for (var p2 in s2)
                if (Object.prototype.hasOwnProperty.call(s2, p2))
                  t2[p2] = s2[p2];
            }
            return t2;
          };
          return __assign.apply(this, arguments);
        };
        var singleton = function(doRevoke) {
          var subject = Cell(Optional.none());
          var revoke = function() {
            return subject.get().each(doRevoke);
          };
          var clear = function() {
            revoke();
            subject.set(Optional.none());
          };
          var isSet = function() {
            return subject.get().isSome();
          };
          var get2 = function() {
            return subject.get();
          };
          var set2 = function(s2) {
            revoke();
            subject.set(Optional.some(s2));
          };
          return {
            clear,
            isSet,
            get: get2,
            set: set2
          };
        };
        var value = function() {
          var subject = singleton(noop3);
          var on2 = function(f2) {
            return subject.get().each(f2);
          };
          return __assign(__assign({}, subject), { on: on2 });
        };
        var checkRange = function(str, substr, start4) {
          return substr === "" || str.length >= substr.length && str.substr(start4, start4 + substr.length) === substr;
        };
        var startsWith = function(str, prefix) {
          return checkRange(str, prefix, 0);
        };
        var endsWith = function(str, suffix) {
          return checkRange(str, suffix, str.length - suffix.length);
        };
        var repeat = function(s2, count) {
          return count <= 0 ? "" : new Array(count + 1).join(s2);
        };
        var global$a = tinymce.util.Tools.resolve("tinymce.Env");
        var global$9 = tinymce.util.Tools.resolve("tinymce.util.Delay");
        var global$8 = tinymce.util.Tools.resolve("tinymce.util.Promise");
        var global$7 = tinymce.util.Tools.resolve("tinymce.util.VK");
        var firePastePreProcess = function(editor, html, internal, isWordHtml) {
          return editor.fire("PastePreProcess", {
            content: html,
            internal,
            wordContent: isWordHtml
          });
        };
        var firePastePostProcess = function(editor, node, internal, isWordHtml) {
          return editor.fire("PastePostProcess", {
            node,
            internal,
            wordContent: isWordHtml
          });
        };
        var firePastePlainTextToggle = function(editor, state) {
          return editor.fire("PastePlainTextToggle", { state });
        };
        var firePaste = function(editor, ieFake) {
          return editor.fire("paste", { ieFake });
        };
        var global$6 = tinymce.util.Tools.resolve("tinymce.util.Tools");
        var shouldBlockDrop = function(editor) {
          return editor.getParam("paste_block_drop", false);
        };
        var shouldPasteDataImages = function(editor) {
          return editor.getParam("paste_data_images", false);
        };
        var shouldFilterDrop = function(editor) {
          return editor.getParam("paste_filter_drop", true);
        };
        var getPreProcess = function(editor) {
          return editor.getParam("paste_preprocess");
        };
        var getPostProcess = function(editor) {
          return editor.getParam("paste_postprocess");
        };
        var getWebkitStyles = function(editor) {
          return editor.getParam("paste_webkit_styles");
        };
        var shouldRemoveWebKitStyles = function(editor) {
          return editor.getParam("paste_remove_styles_if_webkit", true);
        };
        var shouldMergeFormats = function(editor) {
          return editor.getParam("paste_merge_formats", true);
        };
        var isSmartPasteEnabled = function(editor) {
          return editor.getParam("smart_paste", true);
        };
        var isPasteAsTextEnabled = function(editor) {
          return editor.getParam("paste_as_text", false);
        };
        var getRetainStyleProps = function(editor) {
          return editor.getParam("paste_retain_style_properties");
        };
        var getWordValidElements = function(editor) {
          var defaultValidElements = "-strong/b,-em/i,-u,-span,-p,-ol,-ul,-li,-h1,-h2,-h3,-h4,-h5,-h6,-p/div,-a[href|name],sub,sup,strike,br,del,table[width],tr,td[colspan|rowspan|width],th[colspan|rowspan|width],thead,tfoot,tbody";
          return editor.getParam("paste_word_valid_elements", defaultValidElements);
        };
        var shouldConvertWordFakeLists = function(editor) {
          return editor.getParam("paste_convert_word_fake_lists", true);
        };
        var shouldUseDefaultFilters = function(editor) {
          return editor.getParam("paste_enable_default_filters", true);
        };
        var getValidate = function(editor) {
          return editor.getParam("validate");
        };
        var getAllowHtmlDataUrls = function(editor) {
          return editor.getParam("allow_html_data_urls", false, "boolean");
        };
        var getPasteDataImages = function(editor) {
          return editor.getParam("paste_data_images", false, "boolean");
        };
        var getImagesDataImgFilter = function(editor) {
          return editor.getParam("images_dataimg_filter");
        };
        var getImagesReuseFilename = function(editor) {
          return editor.getParam("images_reuse_filename");
        };
        var getForcedRootBlock = function(editor) {
          return editor.getParam("forced_root_block");
        };
        var getForcedRootBlockAttrs = function(editor) {
          return editor.getParam("forced_root_block_attrs");
        };
        var getTabSpaces = function(editor) {
          return editor.getParam("paste_tab_spaces", 4, "number");
        };
        var getAllowedImageFileTypes = function(editor) {
          var defaultImageFileTypes = "jpeg,jpg,jpe,jfi,jif,jfif,png,gif,bmp,webp";
          return global$6.explode(editor.getParam("images_file_types", defaultImageFileTypes, "string"));
        };
        var internalMimeType = "x-tinymce/html";
        var internalMark = "<!-- " + internalMimeType + " -->";
        var mark = function(html) {
          return internalMark + html;
        };
        var unmark = function(html) {
          return html.replace(internalMark, "");
        };
        var isMarked = function(html) {
          return html.indexOf(internalMark) !== -1;
        };
        var internalHtmlMime = constant(internalMimeType);
        var hasOwnProperty = Object.hasOwnProperty;
        var has = function(obj, key) {
          return hasOwnProperty.call(obj, key);
        };
        var global$5 = tinymce.util.Tools.resolve("tinymce.html.Entities");
        var isPlainText = function(text) {
          return !/<(?:\/?(?!(?:div|p|br|span)>)\w+|(?:(?!(?:span style="white-space:\s?pre;?">)|br\s?\/>))\w+\s[^>]+)>/i.test(text);
        };
        var toBRs = function(text) {
          return text.replace(/\r?\n/g, "<br>");
        };
        var openContainer = function(rootTag, rootAttrs) {
          var attrs = [];
          var tag = "<" + rootTag;
          if (typeof rootAttrs === "object") {
            for (var key in rootAttrs) {
              if (has(rootAttrs, key)) {
                attrs.push(key + '="' + global$5.encodeAllRaw(rootAttrs[key]) + '"');
              }
            }
            if (attrs.length) {
              tag += " " + attrs.join(" ");
            }
          }
          return tag + ">";
        };
        var toBlockElements = function(text, rootTag, rootAttrs) {
          var blocks = text.split(/\n\n/);
          var tagOpen = openContainer(rootTag, rootAttrs);
          var tagClose = "</" + rootTag + ">";
          var paragraphs = global$6.map(blocks, function(p2) {
            return p2.split(/\n/).join("<br />");
          });
          var stitch = function(p2) {
            return tagOpen + p2 + tagClose;
          };
          return paragraphs.length === 1 ? paragraphs[0] : global$6.map(paragraphs, stitch).join("");
        };
        var convert = function(text, rootTag, rootAttrs) {
          return rootTag ? toBlockElements(text, rootTag === true ? "p" : rootTag, rootAttrs) : toBRs(text);
        };
        var global$4 = tinymce.util.Tools.resolve("tinymce.html.DomParser");
        var global$3 = tinymce.util.Tools.resolve("tinymce.html.Serializer");
        var nbsp = "\xA0";
        var global$2 = tinymce.util.Tools.resolve("tinymce.html.Node");
        var global$1 = tinymce.util.Tools.resolve("tinymce.html.Schema");
        var isRegExp = function(val) {
          return val.constructor === RegExp;
        };
        var filter = function(content, items) {
          global$6.each(items, function(v2) {
            if (isRegExp(v2)) {
              content = content.replace(v2, "");
            } else {
              content = content.replace(v2[0], v2[1]);
            }
          });
          return content;
        };
        var innerText = function(html) {
          var schema = global$1();
          var domParser = global$4({}, schema);
          var text = "";
          var shortEndedElements = schema.getShortEndedElements();
          var ignoreElements = global$6.makeMap("script noscript style textarea video audio iframe object", " ");
          var blockElements = schema.getBlockElements();
          var walk2 = function(node) {
            var name = node.name, currentNode = node;
            if (name === "br") {
              text += "\n";
              return;
            }
            if (name === "wbr") {
              return;
            }
            if (shortEndedElements[name]) {
              text += " ";
            }
            if (ignoreElements[name]) {
              text += " ";
              return;
            }
            if (node.type === 3) {
              text += node.value;
            }
            if (!node.shortEnded) {
              if (node = node.firstChild) {
                do {
                  walk2(node);
                } while (node = node.next);
              }
            }
            if (blockElements[name] && currentNode.next) {
              text += "\n";
              if (name === "p") {
                text += "\n";
              }
            }
          };
          html = filter(html, [/<!\[[^\]]+\]>/g]);
          walk2(domParser.parse(html));
          return text;
        };
        var trimHtml = function(html) {
          var trimSpaces = function(all, s1, s2) {
            if (!s1 && !s2) {
              return " ";
            }
            return nbsp;
          };
          html = filter(html, [
            /^[\s\S]*<body[^>]*>\s*|\s*<\/body[^>]*>[\s\S]*$/ig,
            /<!--StartFragment-->|<!--EndFragment-->/g,
            [
              /( ?)<span class="Apple-converted-space">\u00a0<\/span>( ?)/g,
              trimSpaces
            ],
            /<br class="Apple-interchange-newline">/g,
            /<br>$/i
          ]);
          return html;
        };
        var createIdGenerator = function(prefix) {
          var count = 0;
          return function() {
            return prefix + count++;
          };
        };
        var getImageMimeType = function(ext) {
          var lowerExt = ext.toLowerCase();
          var mimeOverrides = {
            jpg: "jpeg",
            jpe: "jpeg",
            jfi: "jpeg",
            jif: "jpeg",
            jfif: "jpeg",
            pjpeg: "jpeg",
            pjp: "jpeg",
            svg: "svg+xml"
          };
          return global$6.hasOwn(mimeOverrides, lowerExt) ? "image/" + mimeOverrides[lowerExt] : "image/" + lowerExt;
        };
        var isWordContent = function(content) {
          return /<font face="Times New Roman"|class="?Mso|style="[^"]*\bmso-|style='[^']*\bmso-|w:WordDocument/i.test(content) || /class="OutlineElement/.test(content) || /id="?docs\-internal\-guid\-/.test(content);
        };
        var isNumericList = function(text) {
          var found = false;
          var patterns2 = [
            /^[IVXLMCD]+\.[ \u00a0]/,
            /^[ivxlmcd]+\.[ \u00a0]/,
            /^[a-z]{1,2}[\.\)][ \u00a0]/,
            /^[A-Z]{1,2}[\.\)][ \u00a0]/,
            /^[0-9]+\.[ \u00a0]/,
            /^[\u3007\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d]+\.[ \u00a0]/,
            /^[\u58f1\u5f10\u53c2\u56db\u4f0d\u516d\u4e03\u516b\u4e5d\u62fe]+\.[ \u00a0]/
          ];
          text = text.replace(/^[\u00a0 ]+/, "");
          global$6.each(patterns2, function(pattern) {
            if (pattern.test(text)) {
              found = true;
              return false;
            }
          });
          return found;
        };
        var isBulletList = function(text) {
          return /^[\s\u00a0]*[\u2022\u00b7\u00a7\u25CF]\s*/.test(text);
        };
        var convertFakeListsToProperLists = function(node) {
          var currentListNode, prevListNode, lastLevel = 1;
          var getText = function(node2) {
            var txt = "";
            if (node2.type === 3) {
              return node2.value;
            }
            if (node2 = node2.firstChild) {
              do {
                txt += getText(node2);
              } while (node2 = node2.next);
            }
            return txt;
          };
          var trimListStart = function(node2, regExp) {
            if (node2.type === 3) {
              if (regExp.test(node2.value)) {
                node2.value = node2.value.replace(regExp, "");
                return false;
              }
            }
            if (node2 = node2.firstChild) {
              do {
                if (!trimListStart(node2, regExp)) {
                  return false;
                }
              } while (node2 = node2.next);
            }
            return true;
          };
          var removeIgnoredNodes = function(node2) {
            if (node2._listIgnore) {
              node2.remove();
              return;
            }
            if (node2 = node2.firstChild) {
              do {
                removeIgnoredNodes(node2);
              } while (node2 = node2.next);
            }
          };
          var convertParagraphToLi = function(paragraphNode, listName, start5) {
            var level = paragraphNode._listLevel || lastLevel;
            if (level !== lastLevel) {
              if (level < lastLevel) {
                if (currentListNode) {
                  currentListNode = currentListNode.parent.parent;
                }
              } else {
                prevListNode = currentListNode;
                currentListNode = null;
              }
            }
            if (!currentListNode || currentListNode.name !== listName) {
              prevListNode = prevListNode || currentListNode;
              currentListNode = new global$2(listName, 1);
              if (start5 > 1) {
                currentListNode.attr("start", "" + start5);
              }
              paragraphNode.wrap(currentListNode);
            } else {
              currentListNode.append(paragraphNode);
            }
            paragraphNode.name = "li";
            if (level > lastLevel && prevListNode) {
              prevListNode.lastChild.append(currentListNode);
            }
            lastLevel = level;
            removeIgnoredNodes(paragraphNode);
            trimListStart(paragraphNode, /^\u00a0+/);
            trimListStart(paragraphNode, /^\s*([\u2022\u00b7\u00a7\u25CF]|\w+\.)/);
            trimListStart(paragraphNode, /^\u00a0+/);
          };
          var elements2 = [];
          var child = node.firstChild;
          while (typeof child !== "undefined" && child !== null) {
            elements2.push(child);
            child = child.walk();
            if (child !== null) {
              while (typeof child !== "undefined" && child.parent !== node) {
                child = child.walk();
              }
            }
          }
          for (var i2 = 0; i2 < elements2.length; i2++) {
            node = elements2[i2];
            if (node.name === "p" && node.firstChild) {
              var nodeText = getText(node);
              if (isBulletList(nodeText)) {
                convertParagraphToLi(node, "ul");
                continue;
              }
              if (isNumericList(nodeText)) {
                var matches = /([0-9]+)\./.exec(nodeText);
                var start4 = 1;
                if (matches) {
                  start4 = parseInt(matches[1], 10);
                }
                convertParagraphToLi(node, "ol", start4);
                continue;
              }
              if (node._listLevel) {
                convertParagraphToLi(node, "ul", 1);
                continue;
              }
              currentListNode = null;
            } else {
              prevListNode = currentListNode;
              currentListNode = null;
            }
          }
        };
        var filterStyles = function(editor, validStyles, node, styleValue) {
          var outputStyles = {};
          var styles = editor.dom.parseStyle(styleValue);
          global$6.each(styles, function(value2, name) {
            switch (name) {
              case "mso-list":
                var matches = /\w+ \w+([0-9]+)/i.exec(styleValue);
                if (matches) {
                  node._listLevel = parseInt(matches[1], 10);
                }
                if (/Ignore/i.test(value2) && node.firstChild) {
                  node._listIgnore = true;
                  node.firstChild._listIgnore = true;
                }
                break;
              case "horiz-align":
                name = "text-align";
                break;
              case "vert-align":
                name = "vertical-align";
                break;
              case "font-color":
              case "mso-foreground":
                name = "color";
                break;
              case "mso-background":
              case "mso-highlight":
                name = "background";
                break;
              case "font-weight":
              case "font-style":
                if (value2 !== "normal") {
                  outputStyles[name] = value2;
                }
                return;
              case "mso-element":
                if (/^(comment|comment-list)$/i.test(value2)) {
                  node.remove();
                  return;
                }
                break;
            }
            if (name.indexOf("mso-comment") === 0) {
              node.remove();
              return;
            }
            if (name.indexOf("mso-") === 0) {
              return;
            }
            if (getRetainStyleProps(editor) === "all" || validStyles && validStyles[name]) {
              outputStyles[name] = value2;
            }
          });
          if (/(bold)/i.test(outputStyles["font-weight"])) {
            delete outputStyles["font-weight"];
            node.wrap(new global$2("b", 1));
          }
          if (/(italic)/i.test(outputStyles["font-style"])) {
            delete outputStyles["font-style"];
            node.wrap(new global$2("i", 1));
          }
          var outputStyle = editor.dom.serializeStyle(outputStyles, node.name);
          if (outputStyle) {
            return outputStyle;
          }
          return null;
        };
        var filterWordContent = function(editor, content) {
          var validStyles;
          var retainStyleProperties = getRetainStyleProps(editor);
          if (retainStyleProperties) {
            validStyles = global$6.makeMap(retainStyleProperties.split(/[, ]/));
          }
          content = filter(content, [
            /<br class="?Apple-interchange-newline"?>/gi,
            /<b[^>]+id="?docs-internal-[^>]*>/gi,
            /<!--[\s\S]+?-->/gi,
            /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|img|meta|link|style|\w:\w+)(?=[\s\/>]))[^>]*>/gi,
            [
              /<(\/?)s>/gi,
              "<$1strike>"
            ],
            [
              /&nbsp;/gi,
              nbsp
            ],
            [
              /<span\s+style\s*=\s*"\s*mso-spacerun\s*:\s*yes\s*;?\s*"\s*>([\s\u00a0]*)<\/span>/gi,
              function(str, spaces) {
                return spaces.length > 0 ? spaces.replace(/./, " ").slice(Math.floor(spaces.length / 2)).split("").join(nbsp) : "";
              }
            ]
          ]);
          var validElements = getWordValidElements(editor);
          var schema = global$1({
            valid_elements: validElements,
            valid_children: "-li[p]"
          });
          global$6.each(schema.elements, function(rule) {
            if (!rule.attributes.class) {
              rule.attributes.class = {};
              rule.attributesOrder.push("class");
            }
            if (!rule.attributes.style) {
              rule.attributes.style = {};
              rule.attributesOrder.push("style");
            }
          });
          var domParser = global$4({}, schema);
          domParser.addAttributeFilter("style", function(nodes) {
            var i2 = nodes.length, node;
            while (i2--) {
              node = nodes[i2];
              node.attr("style", filterStyles(editor, validStyles, node, node.attr("style")));
              if (node.name === "span" && node.parent && !node.attributes.length) {
                node.unwrap();
              }
            }
          });
          domParser.addAttributeFilter("class", function(nodes) {
            var i2 = nodes.length, node, className;
            while (i2--) {
              node = nodes[i2];
              className = node.attr("class");
              if (/^(MsoCommentReference|MsoCommentText|msoDel)$/i.test(className)) {
                node.remove();
              }
              node.attr("class", null);
            }
          });
          domParser.addNodeFilter("del", function(nodes) {
            var i2 = nodes.length;
            while (i2--) {
              nodes[i2].remove();
            }
          });
          domParser.addNodeFilter("a", function(nodes) {
            var i2 = nodes.length, node, href, name;
            while (i2--) {
              node = nodes[i2];
              href = node.attr("href");
              name = node.attr("name");
              if (href && href.indexOf("#_msocom_") !== -1) {
                node.remove();
                continue;
              }
              if (href && href.indexOf("file://") === 0) {
                href = href.split("#")[1];
                if (href) {
                  href = "#" + href;
                }
              }
              if (!href && !name) {
                node.unwrap();
              } else {
                if (name && !/^_?(?:toc|edn|ftn)/i.test(name)) {
                  node.unwrap();
                  continue;
                }
                node.attr({
                  href,
                  name
                });
              }
            }
          });
          var rootNode = domParser.parse(content);
          if (shouldConvertWordFakeLists(editor)) {
            convertFakeListsToProperLists(rootNode);
          }
          content = global$3({ validate: getValidate(editor) }, schema).serialize(rootNode);
          return content;
        };
        var preProcess$1 = function(editor, content) {
          return shouldUseDefaultFilters(editor) ? filterWordContent(editor, content) : content;
        };
        var preProcess = function(editor, html) {
          var parser = global$4({}, editor.schema);
          parser.addNodeFilter("meta", function(nodes) {
            global$6.each(nodes, function(node) {
              node.remove();
            });
          });
          var fragment = parser.parse(html, {
            forced_root_block: false,
            isRootContent: true
          });
          return global$3({ validate: getValidate(editor) }, editor.schema).serialize(fragment);
        };
        var processResult = function(content, cancelled) {
          return {
            content,
            cancelled
          };
        };
        var postProcessFilter = function(editor, html, internal, isWordHtml) {
          var tempBody = editor.dom.create("div", { style: "display:none" }, html);
          var postProcessArgs = firePastePostProcess(editor, tempBody, internal, isWordHtml);
          return processResult(postProcessArgs.node.innerHTML, postProcessArgs.isDefaultPrevented());
        };
        var filterContent = function(editor, content, internal, isWordHtml) {
          var preProcessArgs = firePastePreProcess(editor, content, internal, isWordHtml);
          var filteredContent = preProcess(editor, preProcessArgs.content);
          if (editor.hasEventListeners("PastePostProcess") && !preProcessArgs.isDefaultPrevented()) {
            return postProcessFilter(editor, filteredContent, internal, isWordHtml);
          } else {
            return processResult(filteredContent, preProcessArgs.isDefaultPrevented());
          }
        };
        var process2 = function(editor, html, internal) {
          var isWordHtml = isWordContent(html);
          var content = isWordHtml ? preProcess$1(editor, html) : html;
          return filterContent(editor, content, internal, isWordHtml);
        };
        var pasteHtml$1 = function(editor, html) {
          editor.insertContent(html, {
            merge: shouldMergeFormats(editor),
            paste: true
          });
          return true;
        };
        var isAbsoluteUrl = function(url) {
          return /^https?:\/\/[\w\?\-\/+=.&%@~#]+$/i.test(url);
        };
        var isImageUrl = function(editor, url) {
          return isAbsoluteUrl(url) && exists(getAllowedImageFileTypes(editor), function(type) {
            return endsWith(url.toLowerCase(), "." + type.toLowerCase());
          });
        };
        var createImage = function(editor, url, pasteHtmlFn) {
          editor.undoManager.extra(function() {
            pasteHtmlFn(editor, url);
          }, function() {
            editor.insertContent('<img src="' + url + '">');
          });
          return true;
        };
        var createLink = function(editor, url, pasteHtmlFn) {
          editor.undoManager.extra(function() {
            pasteHtmlFn(editor, url);
          }, function() {
            editor.execCommand("mceInsertLink", false, url);
          });
          return true;
        };
        var linkSelection = function(editor, html, pasteHtmlFn) {
          return editor.selection.isCollapsed() === false && isAbsoluteUrl(html) ? createLink(editor, html, pasteHtmlFn) : false;
        };
        var insertImage = function(editor, html, pasteHtmlFn) {
          return isImageUrl(editor, html) ? createImage(editor, html, pasteHtmlFn) : false;
        };
        var smartInsertContent = function(editor, html) {
          global$6.each([
            linkSelection,
            insertImage,
            pasteHtml$1
          ], function(action) {
            return action(editor, html, pasteHtml$1) !== true;
          });
        };
        var insertContent = function(editor, html, pasteAsText) {
          if (pasteAsText || isSmartPasteEnabled(editor) === false) {
            pasteHtml$1(editor, html);
          } else {
            smartInsertContent(editor, html);
          }
        };
        var isCollapsibleWhitespace = function(c2) {
          return " \f	\v".indexOf(c2) !== -1;
        };
        var isNewLineChar = function(c2) {
          return c2 === "\n" || c2 === "\r";
        };
        var isNewline = function(text, idx) {
          return idx < text.length && idx >= 0 ? isNewLineChar(text[idx]) : false;
        };
        var normalizeWhitespace = function(editor, text) {
          var tabSpace = repeat(" ", getTabSpaces(editor));
          var normalizedText = text.replace(/\t/g, tabSpace);
          var result = foldl(normalizedText, function(acc, c2) {
            if (isCollapsibleWhitespace(c2) || c2 === nbsp) {
              if (acc.pcIsSpace || acc.str === "" || acc.str.length === normalizedText.length - 1 || isNewline(normalizedText, acc.str.length + 1)) {
                return {
                  pcIsSpace: false,
                  str: acc.str + nbsp
                };
              } else {
                return {
                  pcIsSpace: true,
                  str: acc.str + " "
                };
              }
            } else {
              return {
                pcIsSpace: isNewLineChar(c2),
                str: acc.str + c2
              };
            }
          }, {
            pcIsSpace: false,
            str: ""
          });
          return result.str;
        };
        var doPaste = function(editor, content, internal, pasteAsText) {
          var args = process2(editor, content, internal);
          if (args.cancelled === false) {
            insertContent(editor, args.content, pasteAsText);
          }
        };
        var pasteHtml = function(editor, html, internalFlag) {
          var internal = internalFlag ? internalFlag : isMarked(html);
          doPaste(editor, unmark(html), internal, false);
        };
        var pasteText = function(editor, text) {
          var encodedText = editor.dom.encode(text).replace(/\r\n/g, "\n");
          var normalizedText = normalizeWhitespace(editor, encodedText);
          var html = convert(normalizedText, getForcedRootBlock(editor), getForcedRootBlockAttrs(editor));
          doPaste(editor, html, false, true);
        };
        var getDataTransferItems = function(dataTransfer) {
          var items = {};
          var mceInternalUrlPrefix = "data:text/mce-internal,";
          if (dataTransfer) {
            if (dataTransfer.getData) {
              var legacyText = dataTransfer.getData("Text");
              if (legacyText && legacyText.length > 0) {
                if (legacyText.indexOf(mceInternalUrlPrefix) === -1) {
                  items["text/plain"] = legacyText;
                }
              }
            }
            if (dataTransfer.types) {
              for (var i2 = 0; i2 < dataTransfer.types.length; i2++) {
                var contentType = dataTransfer.types[i2];
                try {
                  items[contentType] = dataTransfer.getData(contentType);
                } catch (ex) {
                  items[contentType] = "";
                }
              }
            }
          }
          return items;
        };
        var getClipboardContent = function(editor, clipboardEvent) {
          return getDataTransferItems(clipboardEvent.clipboardData || editor.getDoc().dataTransfer);
        };
        var hasContentType = function(clipboardContent, mimeType) {
          return mimeType in clipboardContent && clipboardContent[mimeType].length > 0;
        };
        var hasHtmlOrText = function(content) {
          return hasContentType(content, "text/html") || hasContentType(content, "text/plain");
        };
        var parseDataUri = function(uri) {
          var matches = /data:([^;]+);base64,([a-z0-9\+\/=]+)/i.exec(uri);
          if (matches) {
            return {
              type: matches[1],
              data: decodeURIComponent(matches[2])
            };
          } else {
            return {
              type: null,
              data: null
            };
          }
        };
        var isValidDataUriImage = function(editor, imgElm) {
          var filter2 = getImagesDataImgFilter(editor);
          return filter2 ? filter2(imgElm) : true;
        };
        var extractFilename = function(editor, str) {
          var m2 = str.match(/([\s\S]+?)(?:\.[a-z0-9.]+)$/i);
          return isNonNullable(m2) ? editor.dom.encode(m2[1]) : null;
        };
        var uniqueId = createIdGenerator("mceclip");
        var pasteImage = function(editor, imageItem) {
          var _a = parseDataUri(imageItem.uri), base64 = _a.data, type = _a.type;
          var id2 = uniqueId();
          var file = imageItem.blob;
          var img = new Image();
          img.src = imageItem.uri;
          if (isValidDataUriImage(editor, img)) {
            var blobCache = editor.editorUpload.blobCache;
            var blobInfo = void 0;
            var existingBlobInfo = blobCache.getByData(base64, type);
            if (!existingBlobInfo) {
              var useFileName = getImagesReuseFilename(editor) && isNonNullable(file.name);
              var name_1 = useFileName ? extractFilename(editor, file.name) : id2;
              var filename = useFileName ? file.name : void 0;
              blobInfo = blobCache.create(id2, file, base64, name_1, filename);
              blobCache.add(blobInfo);
            } else {
              blobInfo = existingBlobInfo;
            }
            pasteHtml(editor, '<img src="' + blobInfo.blobUri() + '">', false);
          } else {
            pasteHtml(editor, '<img src="' + imageItem.uri + '">', false);
          }
        };
        var isClipboardEvent = function(event) {
          return event.type === "paste";
        };
        var isDataTransferItem = function(item) {
          return isNonNullable(item.getAsFile);
        };
        var readFilesAsDataUris = function(items) {
          return global$8.all(map3(items, function(item) {
            return new global$8(function(resolve2) {
              var blob = isDataTransferItem(item) ? item.getAsFile() : item;
              var reader = new window.FileReader();
              reader.onload = function() {
                resolve2({
                  blob,
                  uri: reader.result
                });
              };
              reader.readAsDataURL(blob);
            });
          }));
        };
        var isImage = function(editor) {
          var allowedExtensions = getAllowedImageFileTypes(editor);
          return function(file) {
            return startsWith(file.type, "image/") && exists(allowedExtensions, function(extension) {
              return getImageMimeType(extension) === file.type;
            });
          };
        };
        var getImagesFromDataTransfer = function(editor, dataTransfer) {
          var items = dataTransfer.items ? bind(from(dataTransfer.items), function(item) {
            return item.kind === "file" ? [item.getAsFile()] : [];
          }) : [];
          var files = dataTransfer.files ? from(dataTransfer.files) : [];
          return filter$1(items.length > 0 ? items : files, isImage(editor));
        };
        var pasteImageData = function(editor, e2, rng) {
          var dataTransfer = isClipboardEvent(e2) ? e2.clipboardData : e2.dataTransfer;
          if (getPasteDataImages(editor) && dataTransfer) {
            var images = getImagesFromDataTransfer(editor, dataTransfer);
            if (images.length > 0) {
              e2.preventDefault();
              readFilesAsDataUris(images).then(function(fileResults) {
                if (rng) {
                  editor.selection.setRng(rng);
                }
                each2(fileResults, function(result) {
                  pasteImage(editor, result);
                });
              });
              return true;
            }
          }
          return false;
        };
        var isBrokenAndroidClipboardEvent = function(e2) {
          var clipboardData = e2.clipboardData;
          return navigator.userAgent.indexOf("Android") !== -1 && clipboardData && clipboardData.items && clipboardData.items.length === 0;
        };
        var isKeyboardPasteEvent = function(e2) {
          return global$7.metaKeyPressed(e2) && e2.keyCode === 86 || e2.shiftKey && e2.keyCode === 45;
        };
        var registerEventHandlers = function(editor, pasteBin, pasteFormat) {
          var keyboardPasteEvent = value();
          var keyboardPastePressed = value();
          var keyboardPastePlainTextState;
          editor.on("keyup", keyboardPastePressed.clear);
          editor.on("keydown", function(e2) {
            var removePasteBinOnKeyUp = function(e3) {
              if (isKeyboardPasteEvent(e3) && !e3.isDefaultPrevented()) {
                pasteBin.remove();
              }
            };
            if (isKeyboardPasteEvent(e2) && !e2.isDefaultPrevented()) {
              keyboardPastePlainTextState = e2.shiftKey && e2.keyCode === 86;
              if (keyboardPastePlainTextState && global$a.webkit && navigator.userAgent.indexOf("Version/") !== -1) {
                return;
              }
              e2.stopImmediatePropagation();
              keyboardPasteEvent.set(e2);
              keyboardPastePressed.set(true);
              if (global$a.ie && keyboardPastePlainTextState) {
                e2.preventDefault();
                firePaste(editor, true);
                return;
              }
              pasteBin.remove();
              pasteBin.create();
              editor.once("keyup", removePasteBinOnKeyUp);
              editor.once("paste", function() {
                editor.off("keyup", removePasteBinOnKeyUp);
              });
            }
          });
          var insertClipboardContent = function(editor2, clipboardContent, isKeyBoardPaste, plainTextMode, internal) {
            var content;
            if (hasContentType(clipboardContent, "text/html")) {
              content = clipboardContent["text/html"];
            } else {
              content = pasteBin.getHtml();
              internal = internal ? internal : isMarked(content);
              if (pasteBin.isDefaultContent(content)) {
                plainTextMode = true;
              }
            }
            content = trimHtml(content);
            pasteBin.remove();
            var isPlainTextHtml = internal === false && isPlainText(content);
            var isAbsoluteUrl$1 = isAbsoluteUrl(content);
            if (!content.length || isPlainTextHtml && !isAbsoluteUrl$1) {
              plainTextMode = true;
            }
            if (plainTextMode || isAbsoluteUrl$1) {
              if (hasContentType(clipboardContent, "text/plain") && isPlainTextHtml) {
                content = clipboardContent["text/plain"];
              } else {
                content = innerText(content);
              }
            }
            if (pasteBin.isDefaultContent(content)) {
              if (!isKeyBoardPaste) {
                editor2.windowManager.alert("Please use Ctrl+V/Cmd+V keyboard shortcuts to paste contents.");
              }
              return;
            }
            if (plainTextMode) {
              pasteText(editor2, content);
            } else {
              pasteHtml(editor2, content, internal);
            }
          };
          var getLastRng = function() {
            return pasteBin.getLastRng() || editor.selection.getRng();
          };
          editor.on("paste", function(e2) {
            var isKeyboardPaste = keyboardPasteEvent.isSet() || keyboardPastePressed.isSet();
            if (isKeyboardPaste) {
              keyboardPasteEvent.clear();
            }
            var clipboardContent = getClipboardContent(editor, e2);
            var plainTextMode = pasteFormat.get() === "text" || keyboardPastePlainTextState;
            var internal = hasContentType(clipboardContent, internalHtmlMime());
            keyboardPastePlainTextState = false;
            if (e2.isDefaultPrevented() || isBrokenAndroidClipboardEvent(e2)) {
              pasteBin.remove();
              return;
            }
            if (!hasHtmlOrText(clipboardContent) && pasteImageData(editor, e2, getLastRng())) {
              pasteBin.remove();
              return;
            }
            if (!isKeyboardPaste) {
              e2.preventDefault();
            }
            if (global$a.ie && (!isKeyboardPaste || e2.ieFake) && !hasContentType(clipboardContent, "text/html")) {
              pasteBin.create();
              editor.dom.bind(pasteBin.getEl(), "paste", function(e3) {
                e3.stopPropagation();
              });
              editor.getDoc().execCommand("Paste", false, null);
              clipboardContent["text/html"] = pasteBin.getHtml();
            }
            if (hasContentType(clipboardContent, "text/html")) {
              e2.preventDefault();
              if (!internal) {
                internal = isMarked(clipboardContent["text/html"]);
              }
              insertClipboardContent(editor, clipboardContent, isKeyboardPaste, plainTextMode, internal);
            } else {
              global$9.setEditorTimeout(editor, function() {
                insertClipboardContent(editor, clipboardContent, isKeyboardPaste, plainTextMode, internal);
              }, 0);
            }
          });
        };
        var registerEventsAndFilters = function(editor, pasteBin, pasteFormat) {
          registerEventHandlers(editor, pasteBin, pasteFormat);
          var src;
          editor.parser.addNodeFilter("img", function(nodes, name, args) {
            var isPasteInsert = function(args2) {
              return args2.data && args2.data.paste === true;
            };
            var remove2 = function(node) {
              if (!node.attr("data-mce-object") && src !== global$a.transparentSrc) {
                node.remove();
              }
            };
            var isWebKitFakeUrl = function(src2) {
              return src2.indexOf("webkit-fake-url") === 0;
            };
            var isDataUri = function(src2) {
              return src2.indexOf("data:") === 0;
            };
            if (!getPasteDataImages(editor) && isPasteInsert(args)) {
              var i2 = nodes.length;
              while (i2--) {
                src = nodes[i2].attr("src");
                if (!src) {
                  continue;
                }
                if (isWebKitFakeUrl(src)) {
                  remove2(nodes[i2]);
                } else if (!getAllowHtmlDataUrls(editor) && isDataUri(src)) {
                  remove2(nodes[i2]);
                }
              }
            }
          });
        };
        var getPasteBinParent = function(editor) {
          return global$a.ie && editor.inline ? document.body : editor.getBody();
        };
        var isExternalPasteBin = function(editor) {
          return getPasteBinParent(editor) !== editor.getBody();
        };
        var delegatePasteEvents = function(editor, pasteBinElm, pasteBinDefaultContent) {
          if (isExternalPasteBin(editor)) {
            editor.dom.bind(pasteBinElm, "paste keyup", function(_e2) {
              if (!isDefault(editor, pasteBinDefaultContent)) {
                editor.fire("paste");
              }
            });
          }
        };
        var create = function(editor, lastRngCell, pasteBinDefaultContent) {
          var dom = editor.dom, body = editor.getBody();
          lastRngCell.set(editor.selection.getRng());
          var pasteBinElm = editor.dom.add(getPasteBinParent(editor), "div", {
            "id": "mcepastebin",
            "class": "mce-pastebin",
            "contentEditable": true,
            "data-mce-bogus": "all",
            "style": "position: fixed; top: 50%; width: 10px; height: 10px; overflow: hidden; opacity: 0"
          }, pasteBinDefaultContent);
          if (global$a.ie || global$a.gecko) {
            dom.setStyle(pasteBinElm, "left", dom.getStyle(body, "direction", true) === "rtl" ? 65535 : -65535);
          }
          dom.bind(pasteBinElm, "beforedeactivate focusin focusout", function(e2) {
            e2.stopPropagation();
          });
          delegatePasteEvents(editor, pasteBinElm, pasteBinDefaultContent);
          pasteBinElm.focus();
          editor.selection.select(pasteBinElm, true);
        };
        var remove = function(editor, lastRngCell) {
          if (getEl(editor)) {
            var pasteBinClone = void 0;
            var lastRng = lastRngCell.get();
            while (pasteBinClone = editor.dom.get("mcepastebin")) {
              editor.dom.remove(pasteBinClone);
              editor.dom.unbind(pasteBinClone);
            }
            if (lastRng) {
              editor.selection.setRng(lastRng);
            }
          }
          lastRngCell.set(null);
        };
        var getEl = function(editor) {
          return editor.dom.get("mcepastebin");
        };
        var getHtml = function(editor) {
          var copyAndRemove = function(toElm, fromElm) {
            toElm.appendChild(fromElm);
            editor.dom.remove(fromElm, true);
          };
          var pasteBinClones = global$6.grep(getPasteBinParent(editor).childNodes, function(elm) {
            return elm.id === "mcepastebin";
          });
          var pasteBinElm = pasteBinClones.shift();
          global$6.each(pasteBinClones, function(pasteBinClone) {
            copyAndRemove(pasteBinElm, pasteBinClone);
          });
          var dirtyWrappers = editor.dom.select("div[id=mcepastebin]", pasteBinElm);
          for (var i2 = dirtyWrappers.length - 1; i2 >= 0; i2--) {
            var cleanWrapper = editor.dom.create("div");
            pasteBinElm.insertBefore(cleanWrapper, dirtyWrappers[i2]);
            copyAndRemove(cleanWrapper, dirtyWrappers[i2]);
          }
          return pasteBinElm ? pasteBinElm.innerHTML : "";
        };
        var isDefaultContent = function(pasteBinDefaultContent, content) {
          return content === pasteBinDefaultContent;
        };
        var isPasteBin = function(elm) {
          return elm && elm.id === "mcepastebin";
        };
        var isDefault = function(editor, pasteBinDefaultContent) {
          var pasteBinElm = getEl(editor);
          return isPasteBin(pasteBinElm) && isDefaultContent(pasteBinDefaultContent, pasteBinElm.innerHTML);
        };
        var PasteBin = function(editor) {
          var lastRng = Cell(null);
          var pasteBinDefaultContent = "%MCEPASTEBIN%";
          return {
            create: function() {
              return create(editor, lastRng, pasteBinDefaultContent);
            },
            remove: function() {
              return remove(editor, lastRng);
            },
            getEl: function() {
              return getEl(editor);
            },
            getHtml: function() {
              return getHtml(editor);
            },
            getLastRng: lastRng.get,
            isDefault: function() {
              return isDefault(editor, pasteBinDefaultContent);
            },
            isDefaultContent: function(content) {
              return isDefaultContent(pasteBinDefaultContent, content);
            }
          };
        };
        var Clipboard = function(editor, pasteFormat) {
          var pasteBin = PasteBin(editor);
          editor.on("PreInit", function() {
            return registerEventsAndFilters(editor, pasteBin, pasteFormat);
          });
          return {
            pasteFormat,
            pasteHtml: function(html, internalFlag) {
              return pasteHtml(editor, html, internalFlag);
            },
            pasteText: function(text) {
              return pasteText(editor, text);
            },
            pasteImageData: function(e2, rng) {
              return pasteImageData(editor, e2, rng);
            },
            getDataTransferItems,
            hasHtmlOrText,
            hasContentType
          };
        };
        var togglePlainTextPaste = function(editor, clipboard) {
          if (clipboard.pasteFormat.get() === "text") {
            clipboard.pasteFormat.set("html");
            firePastePlainTextToggle(editor, false);
          } else {
            clipboard.pasteFormat.set("text");
            firePastePlainTextToggle(editor, true);
          }
          editor.focus();
        };
        var register$2 = function(editor, clipboard) {
          editor.addCommand("mceTogglePlainTextPaste", function() {
            togglePlainTextPaste(editor, clipboard);
          });
          editor.addCommand("mceInsertClipboardContent", function(ui2, value2) {
            if (value2.content) {
              clipboard.pasteHtml(value2.content, value2.internal);
            }
            if (value2.text) {
              clipboard.pasteText(value2.text);
            }
          });
        };
        var hasWorkingClipboardApi = function(clipboardData) {
          return global$a.iOS === false && typeof (clipboardData === null || clipboardData === void 0 ? void 0 : clipboardData.setData) === "function";
        };
        var setHtml5Clipboard = function(clipboardData, html, text) {
          if (hasWorkingClipboardApi(clipboardData)) {
            try {
              clipboardData.clearData();
              clipboardData.setData("text/html", html);
              clipboardData.setData("text/plain", text);
              clipboardData.setData(internalHtmlMime(), html);
              return true;
            } catch (e2) {
              return false;
            }
          } else {
            return false;
          }
        };
        var setClipboardData = function(evt, data, fallback2, done) {
          if (setHtml5Clipboard(evt.clipboardData, data.html, data.text)) {
            evt.preventDefault();
            done();
          } else {
            fallback2(data.html, done);
          }
        };
        var fallback = function(editor) {
          return function(html, done) {
            var markedHtml = mark(html);
            var outer = editor.dom.create("div", {
              "contenteditable": "false",
              "data-mce-bogus": "all"
            });
            var inner = editor.dom.create("div", { contenteditable: "true" }, markedHtml);
            editor.dom.setStyles(outer, {
              position: "fixed",
              top: "0",
              left: "-3000px",
              width: "1000px",
              overflow: "hidden"
            });
            outer.appendChild(inner);
            editor.dom.add(editor.getBody(), outer);
            var range = editor.selection.getRng();
            inner.focus();
            var offscreenRange = editor.dom.createRng();
            offscreenRange.selectNodeContents(inner);
            editor.selection.setRng(offscreenRange);
            global$9.setTimeout(function() {
              editor.selection.setRng(range);
              outer.parentNode.removeChild(outer);
              done();
            }, 0);
          };
        };
        var getData = function(editor) {
          return {
            html: editor.selection.getContent({ contextual: true }),
            text: editor.selection.getContent({ format: "text" })
          };
        };
        var isTableSelection = function(editor) {
          return !!editor.dom.getParent(editor.selection.getStart(), "td[data-mce-selected],th[data-mce-selected]", editor.getBody());
        };
        var hasSelectedContent = function(editor) {
          return !editor.selection.isCollapsed() || isTableSelection(editor);
        };
        var cut = function(editor) {
          return function(evt) {
            if (hasSelectedContent(editor)) {
              setClipboardData(evt, getData(editor), fallback(editor), function() {
                if (global$a.browser.isChrome() || global$a.browser.isFirefox()) {
                  var rng_1 = editor.selection.getRng();
                  global$9.setEditorTimeout(editor, function() {
                    editor.selection.setRng(rng_1);
                    editor.execCommand("Delete");
                  }, 0);
                } else {
                  editor.execCommand("Delete");
                }
              });
            }
          };
        };
        var copy = function(editor) {
          return function(evt) {
            if (hasSelectedContent(editor)) {
              setClipboardData(evt, getData(editor), fallback(editor), noop3);
            }
          };
        };
        var register$1 = function(editor) {
          editor.on("cut", cut(editor));
          editor.on("copy", copy(editor));
        };
        var global2 = tinymce.util.Tools.resolve("tinymce.dom.RangeUtils");
        var getCaretRangeFromEvent = function(editor, e2) {
          return global2.getCaretRangeFromPoint(e2.clientX, e2.clientY, editor.getDoc());
        };
        var isPlainTextFileUrl = function(content) {
          var plainTextContent = content["text/plain"];
          return plainTextContent ? plainTextContent.indexOf("file://") === 0 : false;
        };
        var setFocusedRange = function(editor, rng) {
          editor.focus();
          editor.selection.setRng(rng);
        };
        var setup$2 = function(editor, clipboard, draggingInternallyState) {
          if (shouldBlockDrop(editor)) {
            editor.on("dragend dragover draggesture dragdrop drop drag", function(e2) {
              e2.preventDefault();
              e2.stopPropagation();
            });
          }
          if (!shouldPasteDataImages(editor)) {
            editor.on("drop", function(e2) {
              var dataTransfer = e2.dataTransfer;
              if (dataTransfer && dataTransfer.files && dataTransfer.files.length > 0) {
                e2.preventDefault();
              }
            });
          }
          editor.on("drop", function(e2) {
            var rng = getCaretRangeFromEvent(editor, e2);
            if (e2.isDefaultPrevented() || draggingInternallyState.get()) {
              return;
            }
            var dropContent = clipboard.getDataTransferItems(e2.dataTransfer);
            var internal = clipboard.hasContentType(dropContent, internalHtmlMime());
            if ((!clipboard.hasHtmlOrText(dropContent) || isPlainTextFileUrl(dropContent)) && clipboard.pasteImageData(e2, rng)) {
              return;
            }
            if (rng && shouldFilterDrop(editor)) {
              var content_1 = dropContent["mce-internal"] || dropContent["text/html"] || dropContent["text/plain"];
              if (content_1) {
                e2.preventDefault();
                global$9.setEditorTimeout(editor, function() {
                  editor.undoManager.transact(function() {
                    if (dropContent["mce-internal"]) {
                      editor.execCommand("Delete");
                    }
                    setFocusedRange(editor, rng);
                    content_1 = trimHtml(content_1);
                    if (!dropContent["text/html"]) {
                      clipboard.pasteText(content_1);
                    } else {
                      clipboard.pasteHtml(content_1, internal);
                    }
                  });
                });
              }
            }
          });
          editor.on("dragstart", function(_e2) {
            draggingInternallyState.set(true);
          });
          editor.on("dragover dragend", function(e2) {
            if (shouldPasteDataImages(editor) && draggingInternallyState.get() === false) {
              e2.preventDefault();
              setFocusedRange(editor, getCaretRangeFromEvent(editor, e2));
            }
            if (e2.type === "dragend") {
              draggingInternallyState.set(false);
            }
          });
        };
        var setup$1 = function(editor) {
          var plugin = editor.plugins.paste;
          var preProcess2 = getPreProcess(editor);
          if (preProcess2) {
            editor.on("PastePreProcess", function(e2) {
              preProcess2.call(plugin, plugin, e2);
            });
          }
          var postProcess = getPostProcess(editor);
          if (postProcess) {
            editor.on("PastePostProcess", function(e2) {
              postProcess.call(plugin, plugin, e2);
            });
          }
        };
        var addPreProcessFilter = function(editor, filterFunc) {
          editor.on("PastePreProcess", function(e2) {
            e2.content = filterFunc(editor, e2.content, e2.internal, e2.wordContent);
          });
        };
        var addPostProcessFilter = function(editor, filterFunc) {
          editor.on("PastePostProcess", function(e2) {
            filterFunc(editor, e2.node);
          });
        };
        var removeExplorerBrElementsAfterBlocks = function(editor, html) {
          if (!isWordContent(html)) {
            return html;
          }
          var blockElements = [];
          global$6.each(editor.schema.getBlockElements(), function(block, blockName) {
            blockElements.push(blockName);
          });
          var explorerBlocksRegExp = new RegExp("(?:<br>&nbsp;[\\s\\r\\n]+|<br>)*(<\\/?(" + blockElements.join("|") + ")[^>]*>)(?:<br>&nbsp;[\\s\\r\\n]+|<br>)*", "g");
          html = filter(html, [[
            explorerBlocksRegExp,
            "$1"
          ]]);
          html = filter(html, [
            [
              /<br><br>/g,
              "<BR><BR>"
            ],
            [
              /<br>/g,
              " "
            ],
            [
              /<BR><BR>/g,
              "<br>"
            ]
          ]);
          return html;
        };
        var removeWebKitStyles = function(editor, content, internal, isWordHtml) {
          if (isWordHtml || internal) {
            return content;
          }
          var webKitStylesSetting = getWebkitStyles(editor);
          var webKitStyles;
          if (shouldRemoveWebKitStyles(editor) === false || webKitStylesSetting === "all") {
            return content;
          }
          if (webKitStylesSetting) {
            webKitStyles = webKitStylesSetting.split(/[, ]/);
          }
          if (webKitStyles) {
            var dom_1 = editor.dom, node_1 = editor.selection.getNode();
            content = content.replace(/(<[^>]+) style="([^"]*)"([^>]*>)/gi, function(all, before, value2, after) {
              var inputStyles = dom_1.parseStyle(dom_1.decode(value2));
              var outputStyles = {};
              if (webKitStyles === "none") {
                return before + after;
              }
              for (var i2 = 0; i2 < webKitStyles.length; i2++) {
                var inputValue = inputStyles[webKitStyles[i2]], currentValue = dom_1.getStyle(node_1, webKitStyles[i2], true);
                if (/color/.test(webKitStyles[i2])) {
                  inputValue = dom_1.toHex(inputValue);
                  currentValue = dom_1.toHex(currentValue);
                }
                if (currentValue !== inputValue) {
                  outputStyles[webKitStyles[i2]] = inputValue;
                }
              }
              var outputStyle = dom_1.serializeStyle(outputStyles, "span");
              if (outputStyle) {
                return before + ' style="' + outputStyle + '"' + after;
              }
              return before + after;
            });
          } else {
            content = content.replace(/(<[^>]+) style="([^"]*)"([^>]*>)/gi, "$1$3");
          }
          content = content.replace(/(<[^>]+) data-mce-style="([^"]+)"([^>]*>)/gi, function(all, before, value2, after) {
            return before + ' style="' + value2 + '"' + after;
          });
          return content;
        };
        var removeUnderlineAndFontInAnchor = function(editor, root) {
          editor.$("a", root).find("font,u").each(function(i2, node) {
            editor.dom.remove(node, true);
          });
        };
        var setup = function(editor) {
          if (global$a.webkit) {
            addPreProcessFilter(editor, removeWebKitStyles);
          }
          if (global$a.ie) {
            addPreProcessFilter(editor, removeExplorerBrElementsAfterBlocks);
            addPostProcessFilter(editor, removeUnderlineAndFontInAnchor);
          }
        };
        var makeSetupHandler = function(editor, clipboard) {
          return function(api) {
            api.setActive(clipboard.pasteFormat.get() === "text");
            var pastePlainTextToggleHandler = function(e2) {
              return api.setActive(e2.state);
            };
            editor.on("PastePlainTextToggle", pastePlainTextToggleHandler);
            return function() {
              return editor.off("PastePlainTextToggle", pastePlainTextToggleHandler);
            };
          };
        };
        var register = function(editor, clipboard) {
          var onAction = function() {
            return editor.execCommand("mceTogglePlainTextPaste");
          };
          editor.ui.registry.addToggleButton("pastetext", {
            active: false,
            icon: "paste-text",
            tooltip: "Paste as text",
            onAction,
            onSetup: makeSetupHandler(editor, clipboard)
          });
          editor.ui.registry.addToggleMenuItem("pastetext", {
            text: "Paste as text",
            icon: "paste-text",
            onAction,
            onSetup: makeSetupHandler(editor, clipboard)
          });
        };
        function Plugin() {
          global$b.add("paste", function(editor) {
            if (hasProPlugin(editor) === false) {
              var draggingInternallyState = Cell(false);
              var pasteFormat = Cell(isPasteAsTextEnabled(editor) ? "text" : "html");
              var clipboard = Clipboard(editor, pasteFormat);
              setup(editor);
              register(editor, clipboard);
              register$2(editor, clipboard);
              setup$1(editor);
              register$1(editor);
              setup$2(editor, clipboard, draggingInternallyState);
              return get(clipboard);
            }
          });
        }
        Plugin();
      })();
    }
  });

  // ../../node_modules/tinymce/plugins/importcss/plugin.js
  var require_plugin4 = __commonJS({
    "../../node_modules/tinymce/plugins/importcss/plugin.js"() {
      (function() {
        "use strict";
        var global$4 = tinymce.util.Tools.resolve("tinymce.PluginManager");
        var typeOf = function(x2) {
          var t2 = typeof x2;
          if (x2 === null) {
            return "null";
          } else if (t2 === "object" && (Array.prototype.isPrototypeOf(x2) || x2.constructor && x2.constructor.name === "Array")) {
            return "array";
          } else if (t2 === "object" && (String.prototype.isPrototypeOf(x2) || x2.constructor && x2.constructor.name === "String")) {
            return "string";
          } else {
            return t2;
          }
        };
        var isType = function(type) {
          return function(value) {
            return typeOf(value) === type;
          };
        };
        var isString = isType("string");
        var isArray2 = isType("array");
        var global$3 = tinymce.util.Tools.resolve("tinymce.dom.DOMUtils");
        var global$2 = tinymce.util.Tools.resolve("tinymce.EditorManager");
        var global$1 = tinymce.util.Tools.resolve("tinymce.Env");
        var global2 = tinymce.util.Tools.resolve("tinymce.util.Tools");
        var shouldMergeClasses = function(editor) {
          return editor.getParam("importcss_merge_classes");
        };
        var shouldImportExclusive = function(editor) {
          return editor.getParam("importcss_exclusive");
        };
        var getSelectorConverter = function(editor) {
          return editor.getParam("importcss_selector_converter");
        };
        var getSelectorFilter = function(editor) {
          return editor.getParam("importcss_selector_filter");
        };
        var getCssGroups = function(editor) {
          return editor.getParam("importcss_groups");
        };
        var shouldAppend = function(editor) {
          return editor.getParam("importcss_append");
        };
        var getFileFilter = function(editor) {
          return editor.getParam("importcss_file_filter");
        };
        var getSkin = function(editor) {
          var skin = editor.getParam("skin");
          return skin !== false ? skin || "oxide" : false;
        };
        var getSkinUrl = function(editor) {
          return editor.getParam("skin_url");
        };
        var nativePush = Array.prototype.push;
        var map3 = function(xs, f2) {
          var len = xs.length;
          var r2 = new Array(len);
          for (var i2 = 0; i2 < len; i2++) {
            var x2 = xs[i2];
            r2[i2] = f2(x2, i2);
          }
          return r2;
        };
        var flatten = function(xs) {
          var r2 = [];
          for (var i2 = 0, len = xs.length; i2 < len; ++i2) {
            if (!isArray2(xs[i2])) {
              throw new Error("Arr.flatten item " + i2 + " was not an array, input: " + xs);
            }
            nativePush.apply(r2, xs[i2]);
          }
          return r2;
        };
        var bind = function(xs, f2) {
          return flatten(map3(xs, f2));
        };
        var generate = function() {
          var ungroupedOrder = [];
          var groupOrder = [];
          var groups = {};
          var addItemToGroup = function(groupTitle, itemInfo) {
            if (groups[groupTitle]) {
              groups[groupTitle].push(itemInfo);
            } else {
              groupOrder.push(groupTitle);
              groups[groupTitle] = [itemInfo];
            }
          };
          var addItem = function(itemInfo) {
            ungroupedOrder.push(itemInfo);
          };
          var toFormats = function() {
            var groupItems = bind(groupOrder, function(g2) {
              var items = groups[g2];
              return items.length === 0 ? [] : [{
                title: g2,
                items
              }];
            });
            return groupItems.concat(ungroupedOrder);
          };
          return {
            addItemToGroup,
            addItem,
            toFormats
          };
        };
        var internalEditorStyle = /^\.(?:ephox|tiny-pageembed|mce)(?:[.-]+\w+)+$/;
        var removeCacheSuffix = function(url) {
          var cacheSuffix = global$1.cacheSuffix;
          if (isString(url)) {
            url = url.replace("?" + cacheSuffix, "").replace("&" + cacheSuffix, "");
          }
          return url;
        };
        var isSkinContentCss = function(editor, href) {
          var skin = getSkin(editor);
          if (skin) {
            var skinUrlBase = getSkinUrl(editor);
            var skinUrl = skinUrlBase ? editor.documentBaseURI.toAbsolute(skinUrlBase) : global$2.baseURL + "/skins/ui/" + skin;
            var contentSkinUrlPart = global$2.baseURL + "/skins/content/";
            return href === skinUrl + "/content" + (editor.inline ? ".inline" : "") + ".min.css" || href.indexOf(contentSkinUrlPart) !== -1;
          }
          return false;
        };
        var compileFilter = function(filter) {
          if (isString(filter)) {
            return function(value) {
              return value.indexOf(filter) !== -1;
            };
          } else if (filter instanceof RegExp) {
            return function(value) {
              return filter.test(value);
            };
          }
          return filter;
        };
        var isCssImportRule = function(rule) {
          return rule.styleSheet;
        };
        var isCssPageRule = function(rule) {
          return rule.selectorText;
        };
        var getSelectors = function(editor, doc, fileFilter) {
          var selectors = [];
          var contentCSSUrls = {};
          var append = function(styleSheet, imported) {
            var href = styleSheet.href, rules;
            href = removeCacheSuffix(href);
            if (!href || !fileFilter(href, imported) || isSkinContentCss(editor, href)) {
              return;
            }
            global2.each(styleSheet.imports, function(styleSheet2) {
              append(styleSheet2, true);
            });
            try {
              rules = styleSheet.cssRules || styleSheet.rules;
            } catch (e2) {
            }
            global2.each(rules, function(cssRule) {
              if (isCssImportRule(cssRule)) {
                append(cssRule.styleSheet, true);
              } else if (isCssPageRule(cssRule)) {
                global2.each(cssRule.selectorText.split(","), function(selector) {
                  selectors.push(global2.trim(selector));
                });
              }
            });
          };
          global2.each(editor.contentCSS, function(url) {
            contentCSSUrls[url] = true;
          });
          if (!fileFilter) {
            fileFilter = function(href, imported) {
              return imported || contentCSSUrls[href];
            };
          }
          try {
            global2.each(doc.styleSheets, function(styleSheet) {
              append(styleSheet);
            });
          } catch (e2) {
          }
          return selectors;
        };
        var defaultConvertSelectorToFormat = function(editor, selectorText) {
          var format3;
          var selector = /^(?:([a-z0-9\-_]+))?(\.[a-z0-9_\-\.]+)$/i.exec(selectorText);
          if (!selector) {
            return;
          }
          var elementName = selector[1];
          var classes = selector[2].substr(1).split(".").join(" ");
          var inlineSelectorElements = global2.makeMap("a,img");
          if (selector[1]) {
            format3 = { title: selectorText };
            if (editor.schema.getTextBlockElements()[elementName]) {
              format3.block = elementName;
            } else if (editor.schema.getBlockElements()[elementName] || inlineSelectorElements[elementName.toLowerCase()]) {
              format3.selector = elementName;
            } else {
              format3.inline = elementName;
            }
          } else if (selector[2]) {
            format3 = {
              inline: "span",
              title: selectorText.substr(1),
              classes
            };
          }
          if (shouldMergeClasses(editor) !== false) {
            format3.classes = classes;
          } else {
            format3.attributes = { class: classes };
          }
          return format3;
        };
        var getGroupsBySelector = function(groups, selector) {
          return global2.grep(groups, function(group) {
            return !group.filter || group.filter(selector);
          });
        };
        var compileUserDefinedGroups = function(groups) {
          return global2.map(groups, function(group) {
            return global2.extend({}, group, {
              original: group,
              selectors: {},
              filter: compileFilter(group.filter)
            });
          });
        };
        var isExclusiveMode = function(editor, group) {
          return group === null || shouldImportExclusive(editor) !== false;
        };
        var isUniqueSelector = function(editor, selector, group, globallyUniqueSelectors) {
          return !(isExclusiveMode(editor, group) ? selector in globallyUniqueSelectors : selector in group.selectors);
        };
        var markUniqueSelector = function(editor, selector, group, globallyUniqueSelectors) {
          if (isExclusiveMode(editor, group)) {
            globallyUniqueSelectors[selector] = true;
          } else {
            group.selectors[selector] = true;
          }
        };
        var convertSelectorToFormat = function(editor, plugin, selector, group) {
          var selectorConverter;
          if (group && group.selector_converter) {
            selectorConverter = group.selector_converter;
          } else if (getSelectorConverter(editor)) {
            selectorConverter = getSelectorConverter(editor);
          } else {
            selectorConverter = function() {
              return defaultConvertSelectorToFormat(editor, selector);
            };
          }
          return selectorConverter.call(plugin, selector, group);
        };
        var setup = function(editor) {
          editor.on("init", function() {
            var model = generate();
            var globallyUniqueSelectors = {};
            var selectorFilter = compileFilter(getSelectorFilter(editor));
            var groups = compileUserDefinedGroups(getCssGroups(editor));
            var processSelector = function(selector, group) {
              if (isUniqueSelector(editor, selector, group, globallyUniqueSelectors)) {
                markUniqueSelector(editor, selector, group, globallyUniqueSelectors);
                var format3 = convertSelectorToFormat(editor, editor.plugins.importcss, selector, group);
                if (format3) {
                  var formatName = format3.name || global$3.DOM.uniqueId();
                  editor.formatter.register(formatName, format3);
                  return {
                    title: format3.title,
                    format: formatName
                  };
                }
              }
              return null;
            };
            global2.each(getSelectors(editor, editor.getDoc(), compileFilter(getFileFilter(editor))), function(selector) {
              if (!internalEditorStyle.test(selector)) {
                if (!selectorFilter || selectorFilter(selector)) {
                  var selectorGroups = getGroupsBySelector(groups, selector);
                  if (selectorGroups.length > 0) {
                    global2.each(selectorGroups, function(group) {
                      var menuItem2 = processSelector(selector, group);
                      if (menuItem2) {
                        model.addItemToGroup(group.title, menuItem2);
                      }
                    });
                  } else {
                    var menuItem = processSelector(selector, null);
                    if (menuItem) {
                      model.addItem(menuItem);
                    }
                  }
                }
              }
            });
            var items = model.toFormats();
            editor.fire("addStyleModifications", {
              items,
              replace: !shouldAppend(editor)
            });
          });
        };
        var get = function(editor) {
          var convertSelectorToFormat2 = function(selectorText) {
            return defaultConvertSelectorToFormat(editor, selectorText);
          };
          return { convertSelectorToFormat: convertSelectorToFormat2 };
        };
        function Plugin() {
          global$4.add("importcss", function(editor) {
            setup(editor);
            return get(editor);
          });
        }
        Plugin();
      })();
    }
  });

  // ../../node_modules/tinymce/plugins/autolink/plugin.js
  var require_plugin5 = __commonJS({
    "../../node_modules/tinymce/plugins/autolink/plugin.js"() {
      (function() {
        "use strict";
        var global$1 = tinymce.util.Tools.resolve("tinymce.PluginManager");
        var checkRange = function(str, substr, start4) {
          return substr === "" || str.length >= substr.length && str.substr(start4, start4 + substr.length) === substr;
        };
        var contains2 = function(str, substr) {
          return str.indexOf(substr) !== -1;
        };
        var startsWith = function(str, prefix) {
          return checkRange(str, prefix, 0);
        };
        var global2 = tinymce.util.Tools.resolve("tinymce.Env");
        var link = function() {
          return /(?:[A-Za-z][A-Za-z\d.+-]{0,14}:\/\/(?:[-.~*+=!&;:'%@?^${}(),\w]+@)?|www\.|[-;:&=+$,.\w]+@)[A-Za-z\d-]+(?:\.[A-Za-z\d-]+)*(?::\d+)?(?:\/(?:[-+~=.,%()\/\w]*[-+~=%()\/\w])?)?(?:\?(?:[-.~*+=!&;:'%@?^${}(),\/\w]+))?(?:#(?:[-.~*+=!&;:'%@?^${}(),\/\w]+))?/g;
        };
        var defaultLinkPattern = new RegExp("^" + link().source + "$", "i");
        var getAutoLinkPattern = function(editor) {
          return editor.getParam("autolink_pattern", defaultLinkPattern);
        };
        var getDefaultLinkTarget = function(editor) {
          return editor.getParam("default_link_target", false);
        };
        var getDefaultLinkProtocol = function(editor) {
          return editor.getParam("link_default_protocol", "http", "string");
        };
        var rangeEqualsBracketOrSpace = function(rangeString) {
          return /^[(\[{ \u00a0]$/.test(rangeString);
        };
        var isTextNode = function(node) {
          return node.nodeType === 3;
        };
        var isElement3 = function(node) {
          return node.nodeType === 1;
        };
        var handleBracket = function(editor) {
          return parseCurrentLine(editor, -1);
        };
        var handleSpacebar = function(editor) {
          return parseCurrentLine(editor, 0);
        };
        var handleEnter = function(editor) {
          return parseCurrentLine(editor, -1);
        };
        var scopeIndex = function(container, index) {
          if (index < 0) {
            index = 0;
          }
          if (isTextNode(container)) {
            var len = container.data.length;
            if (index > len) {
              index = len;
            }
          }
          return index;
        };
        var setStart = function(rng, container, offset2) {
          if (!isElement3(container) || container.hasChildNodes()) {
            rng.setStart(container, scopeIndex(container, offset2));
          } else {
            rng.setStartBefore(container);
          }
        };
        var setEnd = function(rng, container, offset2) {
          if (!isElement3(container) || container.hasChildNodes()) {
            rng.setEnd(container, scopeIndex(container, offset2));
          } else {
            rng.setEndAfter(container);
          }
        };
        var hasProtocol = function(url) {
          return /^([A-Za-z][A-Za-z\d.+-]*:\/\/)|mailto:/.test(url);
        };
        var isPunctuation = function(char) {
          return /[?!,.;:]/.test(char);
        };
        var parseCurrentLine = function(editor, endOffset) {
          var end2, endContainer, bookmark, text, prev, len, rngText;
          var autoLinkPattern = getAutoLinkPattern(editor);
          var defaultLinkTarget = getDefaultLinkTarget(editor);
          if (editor.dom.getParent(editor.selection.getNode(), "a[href]") !== null) {
            return;
          }
          var rng = editor.selection.getRng().cloneRange();
          if (rng.startOffset < 5) {
            prev = rng.endContainer.previousSibling;
            if (!prev) {
              if (!rng.endContainer.firstChild || !rng.endContainer.firstChild.nextSibling) {
                return;
              }
              prev = rng.endContainer.firstChild.nextSibling;
            }
            len = prev.length;
            setStart(rng, prev, len);
            setEnd(rng, prev, len);
            if (rng.endOffset < 5) {
              return;
            }
            end2 = rng.endOffset;
            endContainer = prev;
          } else {
            endContainer = rng.endContainer;
            if (!isTextNode(endContainer) && endContainer.firstChild) {
              while (!isTextNode(endContainer) && endContainer.firstChild) {
                endContainer = endContainer.firstChild;
              }
              if (isTextNode(endContainer)) {
                setStart(rng, endContainer, 0);
                setEnd(rng, endContainer, endContainer.nodeValue.length);
              }
            }
            if (rng.endOffset === 1) {
              end2 = 2;
            } else {
              end2 = rng.endOffset - 1 - endOffset;
            }
          }
          var start4 = end2;
          do {
            setStart(rng, endContainer, end2 >= 2 ? end2 - 2 : 0);
            setEnd(rng, endContainer, end2 >= 1 ? end2 - 1 : 0);
            end2 -= 1;
            rngText = rng.toString();
          } while (!rangeEqualsBracketOrSpace(rngText) && end2 - 2 >= 0);
          if (rangeEqualsBracketOrSpace(rng.toString())) {
            setStart(rng, endContainer, end2);
            setEnd(rng, endContainer, start4);
            end2 += 1;
          } else if (rng.startOffset === 0) {
            setStart(rng, endContainer, 0);
            setEnd(rng, endContainer, start4);
          } else {
            setStart(rng, endContainer, end2);
            setEnd(rng, endContainer, start4);
          }
          text = rng.toString();
          if (isPunctuation(text.charAt(text.length - 1))) {
            setEnd(rng, endContainer, start4 - 1);
          }
          text = rng.toString().trim();
          var matches = text.match(autoLinkPattern);
          var protocol = getDefaultLinkProtocol(editor);
          if (matches) {
            var url = matches[0];
            if (startsWith(url, "www.")) {
              url = protocol + "://" + url;
            } else if (contains2(url, "@") && !hasProtocol(url)) {
              url = "mailto:" + url;
            }
            bookmark = editor.selection.getBookmark();
            editor.selection.setRng(rng);
            editor.execCommand("createlink", false, url);
            if (defaultLinkTarget !== false) {
              editor.dom.setAttrib(editor.selection.getNode(), "target", defaultLinkTarget);
            }
            editor.selection.moveToBookmark(bookmark);
            editor.nodeChanged();
          }
        };
        var setup = function(editor) {
          var autoUrlDetectState;
          editor.on("keydown", function(e2) {
            if (e2.keyCode === 13) {
              return handleEnter(editor);
            }
          });
          if (global2.browser.isIE()) {
            editor.on("focus", function() {
              if (!autoUrlDetectState) {
                autoUrlDetectState = true;
                try {
                  editor.execCommand("AutoUrlDetect", false, true);
                } catch (ex) {
                }
              }
            });
            return;
          }
          editor.on("keypress", function(e2) {
            if (e2.keyCode === 41 || e2.keyCode === 93 || e2.keyCode === 125) {
              return handleBracket(editor);
            }
          });
          editor.on("keyup", function(e2) {
            if (e2.keyCode === 32) {
              return handleSpacebar(editor);
            }
          });
        };
        function Plugin() {
          global$1.add("autolink", function(editor) {
            setup(editor);
          });
        }
        Plugin();
      })();
    }
  });

  // ../../node_modules/tinymce/plugins/autosave/plugin.js
  var require_plugin6 = __commonJS({
    "../../node_modules/tinymce/plugins/autosave/plugin.js"() {
      (function() {
        "use strict";
        var global$4 = tinymce.util.Tools.resolve("tinymce.PluginManager");
        var eq2 = function(t2) {
          return function(a2) {
            return t2 === a2;
          };
        };
        var isUndefined = eq2(void 0);
        var global$3 = tinymce.util.Tools.resolve("tinymce.util.Delay");
        var global$2 = tinymce.util.Tools.resolve("tinymce.util.LocalStorage");
        var global$1 = tinymce.util.Tools.resolve("tinymce.util.Tools");
        var fireRestoreDraft = function(editor) {
          return editor.fire("RestoreDraft");
        };
        var fireStoreDraft = function(editor) {
          return editor.fire("StoreDraft");
        };
        var fireRemoveDraft = function(editor) {
          return editor.fire("RemoveDraft");
        };
        var parse3 = function(timeString, defaultTime) {
          var multiples = {
            s: 1e3,
            m: 6e4
          };
          var toParse = timeString || defaultTime;
          var parsedTime = /^(\d+)([ms]?)$/.exec("" + toParse);
          return (parsedTime[2] ? multiples[parsedTime[2]] : 1) * parseInt(toParse, 10);
        };
        var shouldAskBeforeUnload = function(editor) {
          return editor.getParam("autosave_ask_before_unload", true);
        };
        var getAutoSavePrefix = function(editor) {
          var location2 = document.location;
          return editor.getParam("autosave_prefix", "tinymce-autosave-{path}{query}{hash}-{id}-").replace(/{path}/g, location2.pathname).replace(/{query}/g, location2.search).replace(/{hash}/g, location2.hash).replace(/{id}/g, editor.id);
        };
        var shouldRestoreWhenEmpty = function(editor) {
          return editor.getParam("autosave_restore_when_empty", false);
        };
        var getAutoSaveInterval = function(editor) {
          return parse3(editor.getParam("autosave_interval"), "30s");
        };
        var getAutoSaveRetention = function(editor) {
          return parse3(editor.getParam("autosave_retention"), "20m");
        };
        var isEmpty = function(editor, html) {
          if (isUndefined(html)) {
            return editor.dom.isEmpty(editor.getBody());
          } else {
            var trimmedHtml = global$1.trim(html);
            if (trimmedHtml === "") {
              return true;
            } else {
              var fragment = new DOMParser().parseFromString(trimmedHtml, "text/html");
              return editor.dom.isEmpty(fragment);
            }
          }
        };
        var hasDraft = function(editor) {
          var time = parseInt(global$2.getItem(getAutoSavePrefix(editor) + "time"), 10) || 0;
          if (new Date().getTime() - time > getAutoSaveRetention(editor)) {
            removeDraft(editor, false);
            return false;
          }
          return true;
        };
        var removeDraft = function(editor, fire) {
          var prefix = getAutoSavePrefix(editor);
          global$2.removeItem(prefix + "draft");
          global$2.removeItem(prefix + "time");
          if (fire !== false) {
            fireRemoveDraft(editor);
          }
        };
        var storeDraft = function(editor) {
          var prefix = getAutoSavePrefix(editor);
          if (!isEmpty(editor) && editor.isDirty()) {
            global$2.setItem(prefix + "draft", editor.getContent({
              format: "raw",
              no_events: true
            }));
            global$2.setItem(prefix + "time", new Date().getTime().toString());
            fireStoreDraft(editor);
          }
        };
        var restoreDraft = function(editor) {
          var prefix = getAutoSavePrefix(editor);
          if (hasDraft(editor)) {
            editor.setContent(global$2.getItem(prefix + "draft"), { format: "raw" });
            fireRestoreDraft(editor);
          }
        };
        var startStoreDraft = function(editor) {
          var interval = getAutoSaveInterval(editor);
          global$3.setEditorInterval(editor, function() {
            storeDraft(editor);
          }, interval);
        };
        var restoreLastDraft = function(editor) {
          editor.undoManager.transact(function() {
            restoreDraft(editor);
            removeDraft(editor);
          });
          editor.focus();
        };
        var get = function(editor) {
          return {
            hasDraft: function() {
              return hasDraft(editor);
            },
            storeDraft: function() {
              return storeDraft(editor);
            },
            restoreDraft: function() {
              return restoreDraft(editor);
            },
            removeDraft: function(fire) {
              return removeDraft(editor, fire);
            },
            isEmpty: function(html) {
              return isEmpty(editor, html);
            }
          };
        };
        var global2 = tinymce.util.Tools.resolve("tinymce.EditorManager");
        var setup = function(editor) {
          editor.editorManager.on("BeforeUnload", function(e2) {
            var msg;
            global$1.each(global2.get(), function(editor2) {
              if (editor2.plugins.autosave) {
                editor2.plugins.autosave.storeDraft();
              }
              if (!msg && editor2.isDirty() && shouldAskBeforeUnload(editor2)) {
                msg = editor2.translate("You have unsaved changes are you sure you want to navigate away?");
              }
            });
            if (msg) {
              e2.preventDefault();
              e2.returnValue = msg;
            }
          });
        };
        var makeSetupHandler = function(editor) {
          return function(api) {
            api.setDisabled(!hasDraft(editor));
            var editorEventCallback = function() {
              return api.setDisabled(!hasDraft(editor));
            };
            editor.on("StoreDraft RestoreDraft RemoveDraft", editorEventCallback);
            return function() {
              return editor.off("StoreDraft RestoreDraft RemoveDraft", editorEventCallback);
            };
          };
        };
        var register = function(editor) {
          startStoreDraft(editor);
          editor.ui.registry.addButton("restoredraft", {
            tooltip: "Restore last draft",
            icon: "restore-draft",
            onAction: function() {
              restoreLastDraft(editor);
            },
            onSetup: makeSetupHandler(editor)
          });
          editor.ui.registry.addMenuItem("restoredraft", {
            text: "Restore last draft",
            icon: "restore-draft",
            onAction: function() {
              restoreLastDraft(editor);
            },
            onSetup: makeSetupHandler(editor)
          });
        };
        function Plugin() {
          global$4.add("autosave", function(editor) {
            setup(editor);
            register(editor);
            editor.on("init", function() {
              if (shouldRestoreWhenEmpty(editor) && editor.dom.isEmpty(editor.getBody())) {
                restoreDraft(editor);
              }
            });
            return get(editor);
          });
        }
        Plugin();
      })();
    }
  });

  // ../../node_modules/tinymce/plugins/save/plugin.js
  var require_plugin7 = __commonJS({
    "../../node_modules/tinymce/plugins/save/plugin.js"() {
      (function() {
        "use strict";
        var global$2 = tinymce.util.Tools.resolve("tinymce.PluginManager");
        var global$1 = tinymce.util.Tools.resolve("tinymce.dom.DOMUtils");
        var global2 = tinymce.util.Tools.resolve("tinymce.util.Tools");
        var enableWhenDirty = function(editor) {
          return editor.getParam("save_enablewhendirty", true);
        };
        var hasOnSaveCallback = function(editor) {
          return !!editor.getParam("save_onsavecallback");
        };
        var hasOnCancelCallback = function(editor) {
          return !!editor.getParam("save_oncancelcallback");
        };
        var displayErrorMessage = function(editor, message) {
          editor.notificationManager.open({
            text: message,
            type: "error"
          });
        };
        var save = function(editor) {
          var formObj = global$1.DOM.getParent(editor.id, "form");
          if (enableWhenDirty(editor) && !editor.isDirty()) {
            return;
          }
          editor.save();
          if (hasOnSaveCallback(editor)) {
            editor.execCallback("save_onsavecallback", editor);
            editor.nodeChanged();
            return;
          }
          if (formObj) {
            editor.setDirty(false);
            if (!formObj.onsubmit || formObj.onsubmit()) {
              if (typeof formObj.submit === "function") {
                formObj.submit();
              } else {
                displayErrorMessage(editor, "Error: Form submit field collision.");
              }
            }
            editor.nodeChanged();
          } else {
            displayErrorMessage(editor, "Error: No form element found.");
          }
        };
        var cancel = function(editor) {
          var h3 = global2.trim(editor.startContent);
          if (hasOnCancelCallback(editor)) {
            editor.execCallback("save_oncancelcallback", editor);
            return;
          }
          editor.resetContent(h3);
        };
        var register$1 = function(editor) {
          editor.addCommand("mceSave", function() {
            save(editor);
          });
          editor.addCommand("mceCancel", function() {
            cancel(editor);
          });
        };
        var stateToggle = function(editor) {
          return function(api) {
            var handler = function() {
              api.setDisabled(enableWhenDirty(editor) && !editor.isDirty());
            };
            handler();
            editor.on("NodeChange dirty", handler);
            return function() {
              return editor.off("NodeChange dirty", handler);
            };
          };
        };
        var register = function(editor) {
          editor.ui.registry.addButton("save", {
            icon: "save",
            tooltip: "Save",
            disabled: true,
            onAction: function() {
              return editor.execCommand("mceSave");
            },
            onSetup: stateToggle(editor)
          });
          editor.ui.registry.addButton("cancel", {
            icon: "cancel",
            tooltip: "Cancel",
            disabled: true,
            onAction: function() {
              return editor.execCommand("mceCancel");
            },
            onSetup: stateToggle(editor)
          });
          editor.addShortcut("Meta+S", "", "mceSave");
        };
        function Plugin() {
          global$2.add("save", function(editor) {
            register(editor);
            register$1(editor);
          });
        }
        Plugin();
      })();
    }
  });

  // ../../node_modules/tinymce/plugins/directionality/plugin.js
  var require_plugin8 = __commonJS({
    "../../node_modules/tinymce/plugins/directionality/plugin.js"() {
      (function() {
        "use strict";
        var global2 = tinymce.util.Tools.resolve("tinymce.PluginManager");
        var typeOf = function(x2) {
          var t2 = typeof x2;
          if (x2 === null) {
            return "null";
          } else if (t2 === "object" && (Array.prototype.isPrototypeOf(x2) || x2.constructor && x2.constructor.name === "Array")) {
            return "array";
          } else if (t2 === "object" && (String.prototype.isPrototypeOf(x2) || x2.constructor && x2.constructor.name === "String")) {
            return "string";
          } else {
            return t2;
          }
        };
        var isType$1 = function(type2) {
          return function(value) {
            return typeOf(value) === type2;
          };
        };
        var isSimpleType = function(type2) {
          return function(value) {
            return typeof value === type2;
          };
        };
        var isString = isType$1("string");
        var isBoolean = isSimpleType("boolean");
        var isNullable = function(a2) {
          return a2 === null || a2 === void 0;
        };
        var isNonNullable = function(a2) {
          return !isNullable(a2);
        };
        var isFunction2 = isSimpleType("function");
        var isNumber2 = isSimpleType("number");
        var noop3 = function() {
        };
        var compose1 = function(fbc, fab) {
          return function(a2) {
            return fbc(fab(a2));
          };
        };
        var constant = function(value) {
          return function() {
            return value;
          };
        };
        var identity = function(x2) {
          return x2;
        };
        var never = constant(false);
        var always = constant(true);
        var none = function() {
          return NONE;
        };
        var NONE = function() {
          var call = function(thunk) {
            return thunk();
          };
          var id2 = identity;
          var me2 = {
            fold: function(n2, _s) {
              return n2();
            },
            isSome: never,
            isNone: always,
            getOr: id2,
            getOrThunk: call,
            getOrDie: function(msg) {
              throw new Error(msg || "error: getOrDie called on none.");
            },
            getOrNull: constant(null),
            getOrUndefined: constant(void 0),
            or: id2,
            orThunk: call,
            map: none,
            each: noop3,
            bind: none,
            exists: never,
            forall: always,
            filter: function() {
              return none();
            },
            toArray: function() {
              return [];
            },
            toString: constant("none()")
          };
          return me2;
        }();
        var some = function(a2) {
          var constant_a = constant(a2);
          var self2 = function() {
            return me2;
          };
          var bind = function(f2) {
            return f2(a2);
          };
          var me2 = {
            fold: function(n2, s2) {
              return s2(a2);
            },
            isSome: always,
            isNone: never,
            getOr: constant_a,
            getOrThunk: constant_a,
            getOrDie: constant_a,
            getOrNull: constant_a,
            getOrUndefined: constant_a,
            or: self2,
            orThunk: self2,
            map: function(f2) {
              return some(f2(a2));
            },
            each: function(f2) {
              f2(a2);
            },
            bind,
            exists: bind,
            forall: bind,
            filter: function(f2) {
              return f2(a2) ? me2 : NONE;
            },
            toArray: function() {
              return [a2];
            },
            toString: function() {
              return "some(" + a2 + ")";
            }
          };
          return me2;
        };
        var from = function(value) {
          return value === null || value === void 0 ? NONE : some(value);
        };
        var Optional = {
          some,
          none,
          from
        };
        var map3 = function(xs, f2) {
          var len = xs.length;
          var r2 = new Array(len);
          for (var i2 = 0; i2 < len; i2++) {
            var x2 = xs[i2];
            r2[i2] = f2(x2, i2);
          }
          return r2;
        };
        var each2 = function(xs, f2) {
          for (var i2 = 0, len = xs.length; i2 < len; i2++) {
            var x2 = xs[i2];
            f2(x2, i2);
          }
        };
        var filter = function(xs, pred) {
          var r2 = [];
          for (var i2 = 0, len = xs.length; i2 < len; i2++) {
            var x2 = xs[i2];
            if (pred(x2, i2)) {
              r2.push(x2);
            }
          }
          return r2;
        };
        var DOCUMENT = 9;
        var DOCUMENT_FRAGMENT = 11;
        var ELEMENT = 1;
        var TEXT = 3;
        var fromHtml = function(html, scope) {
          var doc = scope || document;
          var div = doc.createElement("div");
          div.innerHTML = html;
          if (!div.hasChildNodes() || div.childNodes.length > 1) {
            console.error("HTML does not have a single root node", html);
            throw new Error("HTML must have a single root node");
          }
          return fromDom(div.childNodes[0]);
        };
        var fromTag = function(tag, scope) {
          var doc = scope || document;
          var node = doc.createElement(tag);
          return fromDom(node);
        };
        var fromText = function(text, scope) {
          var doc = scope || document;
          var node = doc.createTextNode(text);
          return fromDom(node);
        };
        var fromDom = function(node) {
          if (node === null || node === void 0) {
            throw new Error("Node cannot be null or undefined");
          }
          return { dom: node };
        };
        var fromPoint = function(docElm, x2, y2) {
          return Optional.from(docElm.dom.elementFromPoint(x2, y2)).map(fromDom);
        };
        var SugarElement = {
          fromHtml,
          fromTag,
          fromText,
          fromDom,
          fromPoint
        };
        var is = function(element, selector) {
          var dom = element.dom;
          if (dom.nodeType !== ELEMENT) {
            return false;
          } else {
            var elem = dom;
            if (elem.matches !== void 0) {
              return elem.matches(selector);
            } else if (elem.msMatchesSelector !== void 0) {
              return elem.msMatchesSelector(selector);
            } else if (elem.webkitMatchesSelector !== void 0) {
              return elem.webkitMatchesSelector(selector);
            } else if (elem.mozMatchesSelector !== void 0) {
              return elem.mozMatchesSelector(selector);
            } else {
              throw new Error("Browser lacks native selectors");
            }
          }
        };
        typeof window !== "undefined" ? window : Function("return this;")();
        var name = function(element) {
          var r2 = element.dom.nodeName;
          return r2.toLowerCase();
        };
        var type = function(element) {
          return element.dom.nodeType;
        };
        var isType = function(t2) {
          return function(element) {
            return type(element) === t2;
          };
        };
        var isElement3 = isType(ELEMENT);
        var isText = isType(TEXT);
        var isDocument = isType(DOCUMENT);
        var isDocumentFragment = isType(DOCUMENT_FRAGMENT);
        var isTag = function(tag) {
          return function(e2) {
            return isElement3(e2) && name(e2) === tag;
          };
        };
        var owner = function(element) {
          return SugarElement.fromDom(element.dom.ownerDocument);
        };
        var documentOrOwner = function(dos) {
          return isDocument(dos) ? dos : owner(dos);
        };
        var parent = function(element) {
          return Optional.from(element.dom.parentNode).map(SugarElement.fromDom);
        };
        var children$2 = function(element) {
          return map3(element.dom.childNodes, SugarElement.fromDom);
        };
        var rawSet = function(dom, key, value) {
          if (isString(value) || isBoolean(value) || isNumber2(value)) {
            dom.setAttribute(key, value + "");
          } else {
            console.error("Invalid call to Attribute.set. Key ", key, ":: Value ", value, ":: Element ", dom);
            throw new Error("Attribute value was not simple");
          }
        };
        var set2 = function(element, key, value) {
          rawSet(element.dom, key, value);
        };
        var remove = function(element, key) {
          element.dom.removeAttribute(key);
        };
        var isShadowRoot2 = function(dos) {
          return isDocumentFragment(dos) && isNonNullable(dos.dom.host);
        };
        var supported = isFunction2(Element.prototype.attachShadow) && isFunction2(Node.prototype.getRootNode);
        var getRootNode = supported ? function(e2) {
          return SugarElement.fromDom(e2.dom.getRootNode());
        } : documentOrOwner;
        var getShadowRoot = function(e2) {
          var r2 = getRootNode(e2);
          return isShadowRoot2(r2) ? Optional.some(r2) : Optional.none();
        };
        var getShadowHost = function(e2) {
          return SugarElement.fromDom(e2.dom.host);
        };
        var inBody = function(element) {
          var dom = isText(element) ? element.dom.parentNode : element.dom;
          if (dom === void 0 || dom === null || dom.ownerDocument === null) {
            return false;
          }
          var doc = dom.ownerDocument;
          return getShadowRoot(SugarElement.fromDom(dom)).fold(function() {
            return doc.body.contains(dom);
          }, compose1(inBody, getShadowHost));
        };
        var ancestor$1 = function(scope, predicate, isRoot) {
          var element = scope.dom;
          var stop = isFunction2(isRoot) ? isRoot : never;
          while (element.parentNode) {
            element = element.parentNode;
            var el = SugarElement.fromDom(element);
            if (predicate(el)) {
              return Optional.some(el);
            } else if (stop(el)) {
              break;
            }
          }
          return Optional.none();
        };
        var ancestor = function(scope, selector, isRoot) {
          return ancestor$1(scope, function(e2) {
            return is(e2, selector);
          }, isRoot);
        };
        var isSupported = function(dom) {
          return dom.style !== void 0 && isFunction2(dom.style.getPropertyValue);
        };
        var get = function(element, property) {
          var dom = element.dom;
          var styles = window.getComputedStyle(dom);
          var r2 = styles.getPropertyValue(property);
          return r2 === "" && !inBody(element) ? getUnsafeProperty(dom, property) : r2;
        };
        var getUnsafeProperty = function(dom, property) {
          return isSupported(dom) ? dom.style.getPropertyValue(property) : "";
        };
        var getDirection = function(element) {
          return get(element, "direction") === "rtl" ? "rtl" : "ltr";
        };
        var children$1 = function(scope, predicate) {
          return filter(children$2(scope), predicate);
        };
        var children = function(scope, selector) {
          return children$1(scope, function(e2) {
            return is(e2, selector);
          });
        };
        var getParentElement = function(element) {
          return parent(element).filter(isElement3);
        };
        var getNormalizedBlock = function(element, isListItem2) {
          var normalizedElement = isListItem2 ? ancestor(element, "ol,ul") : Optional.some(element);
          return normalizedElement.getOr(element);
        };
        var isListItem = isTag("li");
        var setDir = function(editor, dir) {
          var selectedBlocks = editor.selection.getSelectedBlocks();
          if (selectedBlocks.length > 0) {
            each2(selectedBlocks, function(block) {
              var blockElement = SugarElement.fromDom(block);
              var isBlockElementListItem = isListItem(blockElement);
              var normalizedBlock = getNormalizedBlock(blockElement, isBlockElementListItem);
              var normalizedBlockParent = getParentElement(normalizedBlock);
              normalizedBlockParent.each(function(parent2) {
                var parentDirection = getDirection(parent2);
                if (parentDirection !== dir) {
                  set2(normalizedBlock, "dir", dir);
                } else if (getDirection(normalizedBlock) !== dir) {
                  remove(normalizedBlock, "dir");
                }
                if (isBlockElementListItem) {
                  var listItems = children(normalizedBlock, "li[dir]");
                  each2(listItems, function(listItem) {
                    return remove(listItem, "dir");
                  });
                }
              });
            });
            editor.nodeChanged();
          }
        };
        var register$1 = function(editor) {
          editor.addCommand("mceDirectionLTR", function() {
            setDir(editor, "ltr");
          });
          editor.addCommand("mceDirectionRTL", function() {
            setDir(editor, "rtl");
          });
        };
        var getNodeChangeHandler = function(editor, dir) {
          return function(api) {
            var nodeChangeHandler = function(e2) {
              var element = SugarElement.fromDom(e2.element);
              api.setActive(getDirection(element) === dir);
            };
            editor.on("NodeChange", nodeChangeHandler);
            return function() {
              return editor.off("NodeChange", nodeChangeHandler);
            };
          };
        };
        var register = function(editor) {
          editor.ui.registry.addToggleButton("ltr", {
            tooltip: "Left to right",
            icon: "ltr",
            onAction: function() {
              return editor.execCommand("mceDirectionLTR");
            },
            onSetup: getNodeChangeHandler(editor, "ltr")
          });
          editor.ui.registry.addToggleButton("rtl", {
            tooltip: "Right to left",
            icon: "rtl",
            onAction: function() {
              return editor.execCommand("mceDirectionRTL");
            },
            onSetup: getNodeChangeHandler(editor, "rtl")
          });
        };
        function Plugin() {
          global2.add("directionality", function(editor) {
            register$1(editor);
            register(editor);
          });
        }
        Plugin();
      })();
    }
  });

  // ../../node_modules/tinymce/plugins/code/plugin.js
  var require_plugin9 = __commonJS({
    "../../node_modules/tinymce/plugins/code/plugin.js"() {
      (function() {
        "use strict";
        var global2 = tinymce.util.Tools.resolve("tinymce.PluginManager");
        var setContent = function(editor, html) {
          editor.focus();
          editor.undoManager.transact(function() {
            editor.setContent(html);
          });
          editor.selection.setCursorLocation();
          editor.nodeChanged();
        };
        var getContent = function(editor) {
          return editor.getContent({ source_view: true });
        };
        var open = function(editor) {
          var editorContent = getContent(editor);
          editor.windowManager.open({
            title: "Source Code",
            size: "large",
            body: {
              type: "panel",
              items: [{
                type: "textarea",
                name: "code"
              }]
            },
            buttons: [
              {
                type: "cancel",
                name: "cancel",
                text: "Cancel"
              },
              {
                type: "submit",
                name: "save",
                text: "Save",
                primary: true
              }
            ],
            initialData: { code: editorContent },
            onSubmit: function(api) {
              setContent(editor, api.getData().code);
              api.close();
            }
          });
        };
        var register$1 = function(editor) {
          editor.addCommand("mceCodeEditor", function() {
            open(editor);
          });
        };
        var register = function(editor) {
          var onAction = function() {
            return editor.execCommand("mceCodeEditor");
          };
          editor.ui.registry.addButton("code", {
            icon: "sourcecode",
            tooltip: "Source code",
            onAction
          });
          editor.ui.registry.addMenuItem("code", {
            icon: "sourcecode",
            text: "Source code",
            onAction
          });
        };
        function Plugin() {
          global2.add("code", function(editor) {
            register$1(editor);
            register(editor);
            return {};
          });
        }
        Plugin();
      })();
    }
  });

  // ../../node_modules/tinymce/plugins/visualblocks/plugin.js
  var require_plugin10 = __commonJS({
    "../../node_modules/tinymce/plugins/visualblocks/plugin.js"() {
      (function() {
        "use strict";
        var Cell = function(initial) {
          var value = initial;
          var get = function() {
            return value;
          };
          var set2 = function(v2) {
            value = v2;
          };
          return {
            get,
            set: set2
          };
        };
        var global2 = tinymce.util.Tools.resolve("tinymce.PluginManager");
        var fireVisualBlocks = function(editor, state) {
          editor.fire("VisualBlocks", { state });
        };
        var toggleVisualBlocks = function(editor, pluginUrl, enabledState) {
          var dom = editor.dom;
          dom.toggleClass(editor.getBody(), "mce-visualblocks");
          enabledState.set(!enabledState.get());
          fireVisualBlocks(editor, enabledState.get());
        };
        var register$1 = function(editor, pluginUrl, enabledState) {
          editor.addCommand("mceVisualBlocks", function() {
            toggleVisualBlocks(editor, pluginUrl, enabledState);
          });
        };
        var isEnabledByDefault = function(editor) {
          return editor.getParam("visualblocks_default_state", false, "boolean");
        };
        var setup = function(editor, pluginUrl, enabledState) {
          editor.on("PreviewFormats AfterPreviewFormats", function(e2) {
            if (enabledState.get()) {
              editor.dom.toggleClass(editor.getBody(), "mce-visualblocks", e2.type === "afterpreviewformats");
            }
          });
          editor.on("init", function() {
            if (isEnabledByDefault(editor)) {
              toggleVisualBlocks(editor, pluginUrl, enabledState);
            }
          });
        };
        var toggleActiveState = function(editor, enabledState) {
          return function(api) {
            api.setActive(enabledState.get());
            var editorEventCallback = function(e2) {
              return api.setActive(e2.state);
            };
            editor.on("VisualBlocks", editorEventCallback);
            return function() {
              return editor.off("VisualBlocks", editorEventCallback);
            };
          };
        };
        var register = function(editor, enabledState) {
          var onAction = function() {
            return editor.execCommand("mceVisualBlocks");
          };
          editor.ui.registry.addToggleButton("visualblocks", {
            icon: "visualblocks",
            tooltip: "Show blocks",
            onAction,
            onSetup: toggleActiveState(editor, enabledState)
          });
          editor.ui.registry.addToggleMenuItem("visualblocks", {
            text: "Show blocks",
            icon: "visualblocks",
            onAction,
            onSetup: toggleActiveState(editor, enabledState)
          });
        };
        function Plugin() {
          global2.add("visualblocks", function(editor, pluginUrl) {
            var enabledState = Cell(false);
            register$1(editor, pluginUrl, enabledState);
            register(editor, enabledState);
            setup(editor, pluginUrl, enabledState);
          });
        }
        Plugin();
      })();
    }
  });

  // ../../node_modules/tinymce/plugins/visualchars/plugin.js
  var require_plugin11 = __commonJS({
    "../../node_modules/tinymce/plugins/visualchars/plugin.js"() {
      (function() {
        "use strict";
        var Cell = function(initial) {
          var value2 = initial;
          var get2 = function() {
            return value2;
          };
          var set3 = function(v2) {
            value2 = v2;
          };
          return {
            get: get2,
            set: set3
          };
        };
        var global$1 = tinymce.util.Tools.resolve("tinymce.PluginManager");
        var get$2 = function(toggleState) {
          var isEnabled = function() {
            return toggleState.get();
          };
          return { isEnabled };
        };
        var fireVisualChars = function(editor, state) {
          return editor.fire("VisualChars", { state });
        };
        var typeOf = function(x2) {
          var t2 = typeof x2;
          if (x2 === null) {
            return "null";
          } else if (t2 === "object" && (Array.prototype.isPrototypeOf(x2) || x2.constructor && x2.constructor.name === "Array")) {
            return "array";
          } else if (t2 === "object" && (String.prototype.isPrototypeOf(x2) || x2.constructor && x2.constructor.name === "String")) {
            return "string";
          } else {
            return t2;
          }
        };
        var isType$1 = function(type2) {
          return function(value2) {
            return typeOf(value2) === type2;
          };
        };
        var isSimpleType = function(type2) {
          return function(value2) {
            return typeof value2 === type2;
          };
        };
        var isString = isType$1("string");
        var isBoolean = isSimpleType("boolean");
        var isNumber2 = isSimpleType("number");
        var noop3 = function() {
        };
        var constant = function(value2) {
          return function() {
            return value2;
          };
        };
        var identity = function(x2) {
          return x2;
        };
        var never = constant(false);
        var always = constant(true);
        var none = function() {
          return NONE;
        };
        var NONE = function() {
          var call = function(thunk) {
            return thunk();
          };
          var id2 = identity;
          var me2 = {
            fold: function(n2, _s) {
              return n2();
            },
            isSome: never,
            isNone: always,
            getOr: id2,
            getOrThunk: call,
            getOrDie: function(msg) {
              throw new Error(msg || "error: getOrDie called on none.");
            },
            getOrNull: constant(null),
            getOrUndefined: constant(void 0),
            or: id2,
            orThunk: call,
            map: none,
            each: noop3,
            bind: none,
            exists: never,
            forall: always,
            filter: function() {
              return none();
            },
            toArray: function() {
              return [];
            },
            toString: constant("none()")
          };
          return me2;
        }();
        var some = function(a2) {
          var constant_a = constant(a2);
          var self2 = function() {
            return me2;
          };
          var bind = function(f2) {
            return f2(a2);
          };
          var me2 = {
            fold: function(n2, s2) {
              return s2(a2);
            },
            isSome: always,
            isNone: never,
            getOr: constant_a,
            getOrThunk: constant_a,
            getOrDie: constant_a,
            getOrNull: constant_a,
            getOrUndefined: constant_a,
            or: self2,
            orThunk: self2,
            map: function(f2) {
              return some(f2(a2));
            },
            each: function(f2) {
              f2(a2);
            },
            bind,
            exists: bind,
            forall: bind,
            filter: function(f2) {
              return f2(a2) ? me2 : NONE;
            },
            toArray: function() {
              return [a2];
            },
            toString: function() {
              return "some(" + a2 + ")";
            }
          };
          return me2;
        };
        var from = function(value2) {
          return value2 === null || value2 === void 0 ? NONE : some(value2);
        };
        var Optional = {
          some,
          none,
          from
        };
        var map3 = function(xs, f2) {
          var len = xs.length;
          var r2 = new Array(len);
          for (var i2 = 0; i2 < len; i2++) {
            var x2 = xs[i2];
            r2[i2] = f2(x2, i2);
          }
          return r2;
        };
        var each$1 = function(xs, f2) {
          for (var i2 = 0, len = xs.length; i2 < len; i2++) {
            var x2 = xs[i2];
            f2(x2, i2);
          }
        };
        var filter = function(xs, pred) {
          var r2 = [];
          for (var i2 = 0, len = xs.length; i2 < len; i2++) {
            var x2 = xs[i2];
            if (pred(x2, i2)) {
              r2.push(x2);
            }
          }
          return r2;
        };
        var keys = Object.keys;
        var each2 = function(obj, f2) {
          var props = keys(obj);
          for (var k2 = 0, len = props.length; k2 < len; k2++) {
            var i2 = props[k2];
            var x2 = obj[i2];
            f2(x2, i2);
          }
        };
        typeof window !== "undefined" ? window : Function("return this;")();
        var TEXT = 3;
        var type = function(element) {
          return element.dom.nodeType;
        };
        var value = function(element) {
          return element.dom.nodeValue;
        };
        var isType = function(t2) {
          return function(element) {
            return type(element) === t2;
          };
        };
        var isText = isType(TEXT);
        var rawSet = function(dom, key, value2) {
          if (isString(value2) || isBoolean(value2) || isNumber2(value2)) {
            dom.setAttribute(key, value2 + "");
          } else {
            console.error("Invalid call to Attribute.set. Key ", key, ":: Value ", value2, ":: Element ", dom);
            throw new Error("Attribute value was not simple");
          }
        };
        var set2 = function(element, key, value2) {
          rawSet(element.dom, key, value2);
        };
        var get$1 = function(element, key) {
          var v2 = element.dom.getAttribute(key);
          return v2 === null ? void 0 : v2;
        };
        var remove$3 = function(element, key) {
          element.dom.removeAttribute(key);
        };
        var read2 = function(element, attr) {
          var value2 = get$1(element, attr);
          return value2 === void 0 || value2 === "" ? [] : value2.split(" ");
        };
        var add$2 = function(element, attr, id2) {
          var old = read2(element, attr);
          var nu = old.concat([id2]);
          set2(element, attr, nu.join(" "));
          return true;
        };
        var remove$2 = function(element, attr, id2) {
          var nu = filter(read2(element, attr), function(v2) {
            return v2 !== id2;
          });
          if (nu.length > 0) {
            set2(element, attr, nu.join(" "));
          } else {
            remove$3(element, attr);
          }
          return false;
        };
        var supports = function(element) {
          return element.dom.classList !== void 0;
        };
        var get = function(element) {
          return read2(element, "class");
        };
        var add$1 = function(element, clazz) {
          return add$2(element, "class", clazz);
        };
        var remove$1 = function(element, clazz) {
          return remove$2(element, "class", clazz);
        };
        var add3 = function(element, clazz) {
          if (supports(element)) {
            element.dom.classList.add(clazz);
          } else {
            add$1(element, clazz);
          }
        };
        var cleanClass = function(element) {
          var classList = supports(element) ? element.dom.classList : get(element);
          if (classList.length === 0) {
            remove$3(element, "class");
          }
        };
        var remove = function(element, clazz) {
          if (supports(element)) {
            var classList = element.dom.classList;
            classList.remove(clazz);
          } else {
            remove$1(element, clazz);
          }
          cleanClass(element);
        };
        var fromHtml = function(html, scope) {
          var doc = scope || document;
          var div = doc.createElement("div");
          div.innerHTML = html;
          if (!div.hasChildNodes() || div.childNodes.length > 1) {
            console.error("HTML does not have a single root node", html);
            throw new Error("HTML must have a single root node");
          }
          return fromDom(div.childNodes[0]);
        };
        var fromTag = function(tag, scope) {
          var doc = scope || document;
          var node = doc.createElement(tag);
          return fromDom(node);
        };
        var fromText = function(text, scope) {
          var doc = scope || document;
          var node = doc.createTextNode(text);
          return fromDom(node);
        };
        var fromDom = function(node) {
          if (node === null || node === void 0) {
            throw new Error("Node cannot be null or undefined");
          }
          return { dom: node };
        };
        var fromPoint = function(docElm, x2, y2) {
          return Optional.from(docElm.dom.elementFromPoint(x2, y2)).map(fromDom);
        };
        var SugarElement = {
          fromHtml,
          fromTag,
          fromText,
          fromDom,
          fromPoint
        };
        var charMap = {
          "\xA0": "nbsp",
          "\xAD": "shy"
        };
        var charMapToRegExp = function(charMap2, global3) {
          var regExp2 = "";
          each2(charMap2, function(_value, key) {
            regExp2 += key;
          });
          return new RegExp("[" + regExp2 + "]", global3 ? "g" : "");
        };
        var charMapToSelector = function(charMap2) {
          var selector2 = "";
          each2(charMap2, function(value2) {
            if (selector2) {
              selector2 += ",";
            }
            selector2 += "span.mce-" + value2;
          });
          return selector2;
        };
        var regExp = charMapToRegExp(charMap);
        var regExpGlobal = charMapToRegExp(charMap, true);
        var selector = charMapToSelector(charMap);
        var nbspClass = "mce-nbsp";
        var wrapCharWithSpan = function(value2) {
          return '<span data-mce-bogus="1" class="mce-' + charMap[value2] + '">' + value2 + "</span>";
        };
        var isMatch = function(n2) {
          var value$1 = value(n2);
          return isText(n2) && value$1 !== void 0 && regExp.test(value$1);
        };
        var filterDescendants = function(scope, predicate) {
          var result = [];
          var dom = scope.dom;
          var children = map3(dom.childNodes, SugarElement.fromDom);
          each$1(children, function(x2) {
            if (predicate(x2)) {
              result = result.concat([x2]);
            }
            result = result.concat(filterDescendants(x2, predicate));
          });
          return result;
        };
        var findParentElm = function(elm, rootElm) {
          while (elm.parentNode) {
            if (elm.parentNode === rootElm) {
              return elm;
            }
            elm = elm.parentNode;
          }
        };
        var replaceWithSpans = function(text) {
          return text.replace(regExpGlobal, wrapCharWithSpan);
        };
        var isWrappedNbsp = function(node) {
          return node.nodeName.toLowerCase() === "span" && node.classList.contains("mce-nbsp-wrap");
        };
        var show = function(editor, rootElm) {
          var nodeList = filterDescendants(SugarElement.fromDom(rootElm), isMatch);
          each$1(nodeList, function(n2) {
            var parent = n2.dom.parentNode;
            if (isWrappedNbsp(parent)) {
              add3(SugarElement.fromDom(parent), nbspClass);
            } else {
              var withSpans = replaceWithSpans(editor.dom.encode(value(n2)));
              var div = editor.dom.create("div", null, withSpans);
              var node = void 0;
              while (node = div.lastChild) {
                editor.dom.insertAfter(node, n2.dom);
              }
              editor.dom.remove(n2.dom);
            }
          });
        };
        var hide2 = function(editor, rootElm) {
          var nodeList = editor.dom.select(selector, rootElm);
          each$1(nodeList, function(node) {
            if (isWrappedNbsp(node)) {
              remove(SugarElement.fromDom(node), nbspClass);
            } else {
              editor.dom.remove(node, true);
            }
          });
        };
        var toggle = function(editor) {
          var body = editor.getBody();
          var bookmark = editor.selection.getBookmark();
          var parentNode = findParentElm(editor.selection.getNode(), body);
          parentNode = parentNode !== void 0 ? parentNode : body;
          hide2(editor, parentNode);
          show(editor, parentNode);
          editor.selection.moveToBookmark(bookmark);
        };
        var applyVisualChars = function(editor, toggleState) {
          fireVisualChars(editor, toggleState.get());
          var body = editor.getBody();
          if (toggleState.get() === true) {
            show(editor, body);
          } else {
            hide2(editor, body);
          }
        };
        var toggleVisualChars = function(editor, toggleState) {
          toggleState.set(!toggleState.get());
          var bookmark = editor.selection.getBookmark();
          applyVisualChars(editor, toggleState);
          editor.selection.moveToBookmark(bookmark);
        };
        var register$1 = function(editor, toggleState) {
          editor.addCommand("mceVisualChars", function() {
            toggleVisualChars(editor, toggleState);
          });
        };
        var isEnabledByDefault = function(editor) {
          return editor.getParam("visualchars_default_state", false);
        };
        var hasForcedRootBlock = function(editor) {
          return editor.getParam("forced_root_block") !== false;
        };
        var setup$1 = function(editor, toggleState) {
          editor.on("init", function() {
            applyVisualChars(editor, toggleState);
          });
        };
        var global2 = tinymce.util.Tools.resolve("tinymce.util.Delay");
        var setup = function(editor, toggleState) {
          var debouncedToggle = global2.debounce(function() {
            toggle(editor);
          }, 300);
          if (hasForcedRootBlock(editor)) {
            editor.on("keydown", function(e2) {
              if (toggleState.get() === true) {
                e2.keyCode === 13 ? toggle(editor) : debouncedToggle();
              }
            });
          }
          editor.on("remove", debouncedToggle.stop);
        };
        var toggleActiveState = function(editor, enabledStated) {
          return function(api) {
            api.setActive(enabledStated.get());
            var editorEventCallback = function(e2) {
              return api.setActive(e2.state);
            };
            editor.on("VisualChars", editorEventCallback);
            return function() {
              return editor.off("VisualChars", editorEventCallback);
            };
          };
        };
        var register = function(editor, toggleState) {
          var onAction = function() {
            return editor.execCommand("mceVisualChars");
          };
          editor.ui.registry.addToggleButton("visualchars", {
            tooltip: "Show invisible characters",
            icon: "visualchars",
            onAction,
            onSetup: toggleActiveState(editor, toggleState)
          });
          editor.ui.registry.addToggleMenuItem("visualchars", {
            text: "Show invisible characters",
            icon: "visualchars",
            onAction,
            onSetup: toggleActiveState(editor, toggleState)
          });
        };
        function Plugin() {
          global$1.add("visualchars", function(editor) {
            var toggleState = Cell(isEnabledByDefault(editor));
            register$1(editor, toggleState);
            register(editor, toggleState);
            setup(editor, toggleState);
            setup$1(editor, toggleState);
            return get$2(toggleState);
          });
        }
        Plugin();
      })();
    }
  });

  // ../../node_modules/tinymce/plugins/fullscreen/plugin.js
  var require_plugin12 = __commonJS({
    "../../node_modules/tinymce/plugins/fullscreen/plugin.js"() {
      (function() {
        "use strict";
        var Cell = function(initial) {
          var value2 = initial;
          var get2 = function() {
            return value2;
          };
          var set3 = function(v2) {
            value2 = v2;
          };
          return {
            get: get2,
            set: set3
          };
        };
        var global$3 = tinymce.util.Tools.resolve("tinymce.PluginManager");
        var get$5 = function(fullscreenState) {
          return {
            isFullscreen: function() {
              return fullscreenState.get() !== null;
            }
          };
        };
        var typeOf = function(x2) {
          var t2 = typeof x2;
          if (x2 === null) {
            return "null";
          } else if (t2 === "object" && (Array.prototype.isPrototypeOf(x2) || x2.constructor && x2.constructor.name === "Array")) {
            return "array";
          } else if (t2 === "object" && (String.prototype.isPrototypeOf(x2) || x2.constructor && x2.constructor.name === "String")) {
            return "string";
          } else {
            return t2;
          }
        };
        var isType$1 = function(type2) {
          return function(value2) {
            return typeOf(value2) === type2;
          };
        };
        var isSimpleType = function(type2) {
          return function(value2) {
            return typeof value2 === type2;
          };
        };
        var isString = isType$1("string");
        var isArray2 = isType$1("array");
        var isBoolean = isSimpleType("boolean");
        var isNullable = function(a2) {
          return a2 === null || a2 === void 0;
        };
        var isNonNullable = function(a2) {
          return !isNullable(a2);
        };
        var isFunction2 = isSimpleType("function");
        var isNumber2 = isSimpleType("number");
        var noop3 = function() {
        };
        var compose = function(fa, fb) {
          return function() {
            var args = [];
            for (var _i2 = 0; _i2 < arguments.length; _i2++) {
              args[_i2] = arguments[_i2];
            }
            return fa(fb.apply(null, args));
          };
        };
        var compose1 = function(fbc, fab) {
          return function(a2) {
            return fbc(fab(a2));
          };
        };
        var constant = function(value2) {
          return function() {
            return value2;
          };
        };
        var identity = function(x2) {
          return x2;
        };
        function curry(fn3) {
          var initialArgs = [];
          for (var _i2 = 1; _i2 < arguments.length; _i2++) {
            initialArgs[_i2 - 1] = arguments[_i2];
          }
          return function() {
            var restArgs = [];
            for (var _i3 = 0; _i3 < arguments.length; _i3++) {
              restArgs[_i3] = arguments[_i3];
            }
            var all2 = initialArgs.concat(restArgs);
            return fn3.apply(null, all2);
          };
        }
        var never = constant(false);
        var always = constant(true);
        var none = function() {
          return NONE;
        };
        var NONE = function() {
          var call = function(thunk) {
            return thunk();
          };
          var id2 = identity;
          var me2 = {
            fold: function(n2, _s) {
              return n2();
            },
            isSome: never,
            isNone: always,
            getOr: id2,
            getOrThunk: call,
            getOrDie: function(msg) {
              throw new Error(msg || "error: getOrDie called on none.");
            },
            getOrNull: constant(null),
            getOrUndefined: constant(void 0),
            or: id2,
            orThunk: call,
            map: none,
            each: noop3,
            bind: none,
            exists: never,
            forall: always,
            filter: function() {
              return none();
            },
            toArray: function() {
              return [];
            },
            toString: constant("none()")
          };
          return me2;
        }();
        var some = function(a2) {
          var constant_a = constant(a2);
          var self2 = function() {
            return me2;
          };
          var bind2 = function(f2) {
            return f2(a2);
          };
          var me2 = {
            fold: function(n2, s2) {
              return s2(a2);
            },
            isSome: always,
            isNone: never,
            getOr: constant_a,
            getOrThunk: constant_a,
            getOrDie: constant_a,
            getOrNull: constant_a,
            getOrUndefined: constant_a,
            or: self2,
            orThunk: self2,
            map: function(f2) {
              return some(f2(a2));
            },
            each: function(f2) {
              f2(a2);
            },
            bind: bind2,
            exists: bind2,
            forall: bind2,
            filter: function(f2) {
              return f2(a2) ? me2 : NONE;
            },
            toArray: function() {
              return [a2];
            },
            toString: function() {
              return "some(" + a2 + ")";
            }
          };
          return me2;
        };
        var from = function(value2) {
          return value2 === null || value2 === void 0 ? NONE : some(value2);
        };
        var Optional = {
          some,
          none,
          from
        };
        var __assign = function() {
          __assign = Object.assign || function __assign2(t2) {
            for (var s2, i2 = 1, n2 = arguments.length; i2 < n2; i2++) {
              s2 = arguments[i2];
              for (var p2 in s2)
                if (Object.prototype.hasOwnProperty.call(s2, p2))
                  t2[p2] = s2[p2];
            }
            return t2;
          };
          return __assign.apply(this, arguments);
        };
        var singleton = function(doRevoke) {
          var subject = Cell(Optional.none());
          var revoke = function() {
            return subject.get().each(doRevoke);
          };
          var clear = function() {
            revoke();
            subject.set(Optional.none());
          };
          var isSet = function() {
            return subject.get().isSome();
          };
          var get2 = function() {
            return subject.get();
          };
          var set3 = function(s2) {
            revoke();
            subject.set(Optional.some(s2));
          };
          return {
            clear,
            isSet,
            get: get2,
            set: set3
          };
        };
        var unbindable = function() {
          return singleton(function(s2) {
            return s2.unbind();
          });
        };
        var value = function() {
          var subject = singleton(noop3);
          var on2 = function(f2) {
            return subject.get().each(f2);
          };
          return __assign(__assign({}, subject), { on: on2 });
        };
        var nativePush = Array.prototype.push;
        var map3 = function(xs, f2) {
          var len = xs.length;
          var r3 = new Array(len);
          for (var i2 = 0; i2 < len; i2++) {
            var x2 = xs[i2];
            r3[i2] = f2(x2, i2);
          }
          return r3;
        };
        var each$1 = function(xs, f2) {
          for (var i2 = 0, len = xs.length; i2 < len; i2++) {
            var x2 = xs[i2];
            f2(x2, i2);
          }
        };
        var filter$1 = function(xs, pred) {
          var r3 = [];
          for (var i2 = 0, len = xs.length; i2 < len; i2++) {
            var x2 = xs[i2];
            if (pred(x2, i2)) {
              r3.push(x2);
            }
          }
          return r3;
        };
        var findUntil = function(xs, pred, until) {
          for (var i2 = 0, len = xs.length; i2 < len; i2++) {
            var x2 = xs[i2];
            if (pred(x2, i2)) {
              return Optional.some(x2);
            } else if (until(x2, i2)) {
              break;
            }
          }
          return Optional.none();
        };
        var find$1 = function(xs, pred) {
          return findUntil(xs, pred, never);
        };
        var flatten = function(xs) {
          var r3 = [];
          for (var i2 = 0, len = xs.length; i2 < len; ++i2) {
            if (!isArray2(xs[i2])) {
              throw new Error("Arr.flatten item " + i2 + " was not an array, input: " + xs);
            }
            nativePush.apply(r3, xs[i2]);
          }
          return r3;
        };
        var bind$3 = function(xs, f2) {
          return flatten(map3(xs, f2));
        };
        var get$4 = function(xs, i2) {
          return i2 >= 0 && i2 < xs.length ? Optional.some(xs[i2]) : Optional.none();
        };
        var head = function(xs) {
          return get$4(xs, 0);
        };
        var findMap = function(arr, f2) {
          for (var i2 = 0; i2 < arr.length; i2++) {
            var r3 = f2(arr[i2], i2);
            if (r3.isSome()) {
              return r3;
            }
          }
          return Optional.none();
        };
        var keys = Object.keys;
        var each2 = function(obj, f2) {
          var props = keys(obj);
          for (var k2 = 0, len = props.length; k2 < len; k2++) {
            var i2 = props[k2];
            var x2 = obj[i2];
            f2(x2, i2);
          }
        };
        var contains2 = function(str, substr) {
          return str.indexOf(substr) !== -1;
        };
        var isSupported$1 = function(dom) {
          return dom.style !== void 0 && isFunction2(dom.style.getPropertyValue);
        };
        var fromHtml = function(html, scope) {
          var doc = scope || document;
          var div = doc.createElement("div");
          div.innerHTML = html;
          if (!div.hasChildNodes() || div.childNodes.length > 1) {
            console.error("HTML does not have a single root node", html);
            throw new Error("HTML must have a single root node");
          }
          return fromDom(div.childNodes[0]);
        };
        var fromTag = function(tag, scope) {
          var doc = scope || document;
          var node = doc.createElement(tag);
          return fromDom(node);
        };
        var fromText = function(text, scope) {
          var doc = scope || document;
          var node = doc.createTextNode(text);
          return fromDom(node);
        };
        var fromDom = function(node) {
          if (node === null || node === void 0) {
            throw new Error("Node cannot be null or undefined");
          }
          return { dom: node };
        };
        var fromPoint = function(docElm, x2, y2) {
          return Optional.from(docElm.dom.elementFromPoint(x2, y2)).map(fromDom);
        };
        var SugarElement = {
          fromHtml,
          fromTag,
          fromText,
          fromDom,
          fromPoint
        };
        typeof window !== "undefined" ? window : Function("return this;")();
        var DOCUMENT = 9;
        var DOCUMENT_FRAGMENT = 11;
        var ELEMENT = 1;
        var TEXT = 3;
        var type = function(element) {
          return element.dom.nodeType;
        };
        var isType = function(t2) {
          return function(element) {
            return type(element) === t2;
          };
        };
        var isElement3 = isType(ELEMENT);
        var isText = isType(TEXT);
        var isDocument = isType(DOCUMENT);
        var isDocumentFragment = isType(DOCUMENT_FRAGMENT);
        var cached = function(f2) {
          var called = false;
          var r3;
          return function() {
            var args = [];
            for (var _i2 = 0; _i2 < arguments.length; _i2++) {
              args[_i2] = arguments[_i2];
            }
            if (!called) {
              called = true;
              r3 = f2.apply(null, args);
            }
            return r3;
          };
        };
        var DeviceType = function(os, browser, userAgent, mediaMatch2) {
          var isiPad = os.isiOS() && /ipad/i.test(userAgent) === true;
          var isiPhone = os.isiOS() && !isiPad;
          var isMobile = os.isiOS() || os.isAndroid();
          var isTouch = isMobile || mediaMatch2("(pointer:coarse)");
          var isTablet = isiPad || !isiPhone && isMobile && mediaMatch2("(min-device-width:768px)");
          var isPhone = isiPhone || isMobile && !isTablet;
          var iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false;
          var isDesktop = !isPhone && !isTablet && !iOSwebview;
          return {
            isiPad: constant(isiPad),
            isiPhone: constant(isiPhone),
            isTablet: constant(isTablet),
            isPhone: constant(isPhone),
            isTouch: constant(isTouch),
            isAndroid: os.isAndroid,
            isiOS: os.isiOS,
            isWebView: constant(iOSwebview),
            isDesktop: constant(isDesktop)
          };
        };
        var firstMatch = function(regexes, s2) {
          for (var i2 = 0; i2 < regexes.length; i2++) {
            var x2 = regexes[i2];
            if (x2.test(s2)) {
              return x2;
            }
          }
          return void 0;
        };
        var find = function(regexes, agent) {
          var r3 = firstMatch(regexes, agent);
          if (!r3) {
            return {
              major: 0,
              minor: 0
            };
          }
          var group = function(i2) {
            return Number(agent.replace(r3, "$" + i2));
          };
          return nu$2(group(1), group(2));
        };
        var detect$3 = function(versionRegexes, agent) {
          var cleanedAgent = String(agent).toLowerCase();
          if (versionRegexes.length === 0) {
            return unknown$2();
          }
          return find(versionRegexes, cleanedAgent);
        };
        var unknown$2 = function() {
          return nu$2(0, 0);
        };
        var nu$2 = function(major, minor) {
          return {
            major,
            minor
          };
        };
        var Version = {
          nu: nu$2,
          detect: detect$3,
          unknown: unknown$2
        };
        var detectBrowser$1 = function(browsers2, userAgentData) {
          return findMap(userAgentData.brands, function(uaBrand) {
            var lcBrand = uaBrand.brand.toLowerCase();
            return find$1(browsers2, function(browser) {
              var _a;
              return lcBrand === ((_a = browser.brand) === null || _a === void 0 ? void 0 : _a.toLowerCase());
            }).map(function(info) {
              return {
                current: info.name,
                version: Version.nu(parseInt(uaBrand.version, 10), 0)
              };
            });
          });
        };
        var detect$2 = function(candidates, userAgent) {
          var agent = String(userAgent).toLowerCase();
          return find$1(candidates, function(candidate) {
            return candidate.search(agent);
          });
        };
        var detectBrowser = function(browsers2, userAgent) {
          return detect$2(browsers2, userAgent).map(function(browser) {
            var version2 = Version.detect(browser.versionRegexes, userAgent);
            return {
              current: browser.name,
              version: version2
            };
          });
        };
        var detectOs = function(oses2, userAgent) {
          return detect$2(oses2, userAgent).map(function(os) {
            var version2 = Version.detect(os.versionRegexes, userAgent);
            return {
              current: os.name,
              version: version2
            };
          });
        };
        var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/;
        var checkContains = function(target) {
          return function(uastring) {
            return contains2(uastring, target);
          };
        };
        var browsers = [
          {
            name: "Edge",
            versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],
            search: function(uastring) {
              return contains2(uastring, "edge/") && contains2(uastring, "chrome") && contains2(uastring, "safari") && contains2(uastring, "applewebkit");
            }
          },
          {
            name: "Chrome",
            brand: "Chromium",
            versionRegexes: [
              /.*?chrome\/([0-9]+)\.([0-9]+).*/,
              normalVersionRegex
            ],
            search: function(uastring) {
              return contains2(uastring, "chrome") && !contains2(uastring, "chromeframe");
            }
          },
          {
            name: "IE",
            versionRegexes: [
              /.*?msie\ ?([0-9]+)\.([0-9]+).*/,
              /.*?rv:([0-9]+)\.([0-9]+).*/
            ],
            search: function(uastring) {
              return contains2(uastring, "msie") || contains2(uastring, "trident");
            }
          },
          {
            name: "Opera",
            versionRegexes: [
              normalVersionRegex,
              /.*?opera\/([0-9]+)\.([0-9]+).*/
            ],
            search: checkContains("opera")
          },
          {
            name: "Firefox",
            versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],
            search: checkContains("firefox")
          },
          {
            name: "Safari",
            versionRegexes: [
              normalVersionRegex,
              /.*?cpu os ([0-9]+)_([0-9]+).*/
            ],
            search: function(uastring) {
              return (contains2(uastring, "safari") || contains2(uastring, "mobile/")) && contains2(uastring, "applewebkit");
            }
          }
        ];
        var oses = [
          {
            name: "Windows",
            search: checkContains("win"),
            versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]
          },
          {
            name: "iOS",
            search: function(uastring) {
              return contains2(uastring, "iphone") || contains2(uastring, "ipad");
            },
            versionRegexes: [
              /.*?version\/\ ?([0-9]+)\.([0-9]+).*/,
              /.*cpu os ([0-9]+)_([0-9]+).*/,
              /.*cpu iphone os ([0-9]+)_([0-9]+).*/
            ]
          },
          {
            name: "Android",
            search: checkContains("android"),
            versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/]
          },
          {
            name: "OSX",
            search: checkContains("mac os x"),
            versionRegexes: [/.*?mac\ os\ x\ ?([0-9]+)_([0-9]+).*/]
          },
          {
            name: "Linux",
            search: checkContains("linux"),
            versionRegexes: []
          },
          {
            name: "Solaris",
            search: checkContains("sunos"),
            versionRegexes: []
          },
          {
            name: "FreeBSD",
            search: checkContains("freebsd"),
            versionRegexes: []
          },
          {
            name: "ChromeOS",
            search: checkContains("cros"),
            versionRegexes: [/.*?chrome\/([0-9]+)\.([0-9]+).*/]
          }
        ];
        var PlatformInfo = {
          browsers: constant(browsers),
          oses: constant(oses)
        };
        var edge = "Edge";
        var chrome = "Chrome";
        var ie2 = "IE";
        var opera = "Opera";
        var firefox = "Firefox";
        var safari = "Safari";
        var unknown$1 = function() {
          return nu$1({
            current: void 0,
            version: Version.unknown()
          });
        };
        var nu$1 = function(info) {
          var current = info.current;
          var version2 = info.version;
          var isBrowser = function(name) {
            return function() {
              return current === name;
            };
          };
          return {
            current,
            version: version2,
            isEdge: isBrowser(edge),
            isChrome: isBrowser(chrome),
            isIE: isBrowser(ie2),
            isOpera: isBrowser(opera),
            isFirefox: isBrowser(firefox),
            isSafari: isBrowser(safari)
          };
        };
        var Browser = {
          unknown: unknown$1,
          nu: nu$1,
          edge: constant(edge),
          chrome: constant(chrome),
          ie: constant(ie2),
          opera: constant(opera),
          firefox: constant(firefox),
          safari: constant(safari)
        };
        var windows = "Windows";
        var ios = "iOS";
        var android = "Android";
        var linux = "Linux";
        var osx = "OSX";
        var solaris = "Solaris";
        var freebsd = "FreeBSD";
        var chromeos = "ChromeOS";
        var unknown = function() {
          return nu({
            current: void 0,
            version: Version.unknown()
          });
        };
        var nu = function(info) {
          var current = info.current;
          var version2 = info.version;
          var isOS = function(name) {
            return function() {
              return current === name;
            };
          };
          return {
            current,
            version: version2,
            isWindows: isOS(windows),
            isiOS: isOS(ios),
            isAndroid: isOS(android),
            isOSX: isOS(osx),
            isLinux: isOS(linux),
            isSolaris: isOS(solaris),
            isFreeBSD: isOS(freebsd),
            isChromeOS: isOS(chromeos)
          };
        };
        var OperatingSystem = {
          unknown,
          nu,
          windows: constant(windows),
          ios: constant(ios),
          android: constant(android),
          linux: constant(linux),
          osx: constant(osx),
          solaris: constant(solaris),
          freebsd: constant(freebsd),
          chromeos: constant(chromeos)
        };
        var detect$1 = function(userAgent, userAgentDataOpt, mediaMatch2) {
          var browsers2 = PlatformInfo.browsers();
          var oses2 = PlatformInfo.oses();
          var browser = userAgentDataOpt.bind(function(userAgentData) {
            return detectBrowser$1(browsers2, userAgentData);
          }).orThunk(function() {
            return detectBrowser(browsers2, userAgent);
          }).fold(Browser.unknown, Browser.nu);
          var os = detectOs(oses2, userAgent).fold(OperatingSystem.unknown, OperatingSystem.nu);
          var deviceType = DeviceType(os, browser, userAgent, mediaMatch2);
          return {
            browser,
            os,
            deviceType
          };
        };
        var PlatformDetection = { detect: detect$1 };
        var mediaMatch = function(query) {
          return window.matchMedia(query).matches;
        };
        var platform = cached(function() {
          return PlatformDetection.detect(navigator.userAgent, Optional.from(navigator.userAgentData), mediaMatch);
        });
        var detect = function() {
          return platform();
        };
        var is = function(element, selector) {
          var dom = element.dom;
          if (dom.nodeType !== ELEMENT) {
            return false;
          } else {
            var elem = dom;
            if (elem.matches !== void 0) {
              return elem.matches(selector);
            } else if (elem.msMatchesSelector !== void 0) {
              return elem.msMatchesSelector(selector);
            } else if (elem.webkitMatchesSelector !== void 0) {
              return elem.webkitMatchesSelector(selector);
            } else if (elem.mozMatchesSelector !== void 0) {
              return elem.mozMatchesSelector(selector);
            } else {
              throw new Error("Browser lacks native selectors");
            }
          }
        };
        var bypassSelector = function(dom) {
          return dom.nodeType !== ELEMENT && dom.nodeType !== DOCUMENT && dom.nodeType !== DOCUMENT_FRAGMENT || dom.childElementCount === 0;
        };
        var all$1 = function(selector, scope) {
          var base = scope === void 0 ? document : scope.dom;
          return bypassSelector(base) ? [] : map3(base.querySelectorAll(selector), SugarElement.fromDom);
        };
        var eq2 = function(e1, e2) {
          return e1.dom === e2.dom;
        };
        var owner = function(element) {
          return SugarElement.fromDom(element.dom.ownerDocument);
        };
        var documentOrOwner = function(dos) {
          return isDocument(dos) ? dos : owner(dos);
        };
        var parent = function(element) {
          return Optional.from(element.dom.parentNode).map(SugarElement.fromDom);
        };
        var parents = function(element, isRoot) {
          var stop = isFunction2(isRoot) ? isRoot : never;
          var dom = element.dom;
          var ret = [];
          while (dom.parentNode !== null && dom.parentNode !== void 0) {
            var rawParent = dom.parentNode;
            var p2 = SugarElement.fromDom(rawParent);
            ret.push(p2);
            if (stop(p2) === true) {
              break;
            } else {
              dom = rawParent;
            }
          }
          return ret;
        };
        var siblings$2 = function(element) {
          var filterSelf = function(elements2) {
            return filter$1(elements2, function(x2) {
              return !eq2(element, x2);
            });
          };
          return parent(element).map(children).map(filterSelf).getOr([]);
        };
        var children = function(element) {
          return map3(element.dom.childNodes, SugarElement.fromDom);
        };
        var isShadowRoot2 = function(dos) {
          return isDocumentFragment(dos) && isNonNullable(dos.dom.host);
        };
        var supported = isFunction2(Element.prototype.attachShadow) && isFunction2(Node.prototype.getRootNode);
        var isSupported = constant(supported);
        var getRootNode = supported ? function(e2) {
          return SugarElement.fromDom(e2.dom.getRootNode());
        } : documentOrOwner;
        var getShadowRoot = function(e2) {
          var r3 = getRootNode(e2);
          return isShadowRoot2(r3) ? Optional.some(r3) : Optional.none();
        };
        var getShadowHost = function(e2) {
          return SugarElement.fromDom(e2.dom.host);
        };
        var getOriginalEventTarget = function(event) {
          if (isSupported() && isNonNullable(event.target)) {
            var el = SugarElement.fromDom(event.target);
            if (isElement3(el) && isOpenShadowHost(el)) {
              if (event.composed && event.composedPath) {
                var composedPath = event.composedPath();
                if (composedPath) {
                  return head(composedPath);
                }
              }
            }
          }
          return Optional.from(event.target);
        };
        var isOpenShadowHost = function(element) {
          return isNonNullable(element.dom.shadowRoot);
        };
        var inBody = function(element) {
          var dom = isText(element) ? element.dom.parentNode : element.dom;
          if (dom === void 0 || dom === null || dom.ownerDocument === null) {
            return false;
          }
          var doc = dom.ownerDocument;
          return getShadowRoot(SugarElement.fromDom(dom)).fold(function() {
            return doc.body.contains(dom);
          }, compose1(inBody, getShadowHost));
        };
        var getBody = function(doc) {
          var b2 = doc.dom.body;
          if (b2 === null || b2 === void 0) {
            throw new Error("Body is not available yet");
          }
          return SugarElement.fromDom(b2);
        };
        var rawSet = function(dom, key, value2) {
          if (isString(value2) || isBoolean(value2) || isNumber2(value2)) {
            dom.setAttribute(key, value2 + "");
          } else {
            console.error("Invalid call to Attribute.set. Key ", key, ":: Value ", value2, ":: Element ", dom);
            throw new Error("Attribute value was not simple");
          }
        };
        var set2 = function(element, key, value2) {
          rawSet(element.dom, key, value2);
        };
        var get$3 = function(element, key) {
          var v2 = element.dom.getAttribute(key);
          return v2 === null ? void 0 : v2;
        };
        var remove = function(element, key) {
          element.dom.removeAttribute(key);
        };
        var internalSet = function(dom, property, value2) {
          if (!isString(value2)) {
            console.error("Invalid call to CSS.set. Property ", property, ":: Value ", value2, ":: Element ", dom);
            throw new Error("CSS value must be a string: " + value2);
          }
          if (isSupported$1(dom)) {
            dom.style.setProperty(property, value2);
          }
        };
        var setAll = function(element, css) {
          var dom = element.dom;
          each2(css, function(v2, k2) {
            internalSet(dom, k2, v2);
          });
        };
        var get$2 = function(element, property) {
          var dom = element.dom;
          var styles = window.getComputedStyle(dom);
          var r3 = styles.getPropertyValue(property);
          return r3 === "" && !inBody(element) ? getUnsafeProperty(dom, property) : r3;
        };
        var getUnsafeProperty = function(dom, property) {
          return isSupported$1(dom) ? dom.style.getPropertyValue(property) : "";
        };
        var mkEvent = function(target, x2, y2, stop, prevent, kill, raw) {
          return {
            target,
            x: x2,
            y: y2,
            stop,
            prevent,
            kill,
            raw
          };
        };
        var fromRawEvent = function(rawEvent) {
          var target = SugarElement.fromDom(getOriginalEventTarget(rawEvent).getOr(rawEvent.target));
          var stop = function() {
            return rawEvent.stopPropagation();
          };
          var prevent = function() {
            return rawEvent.preventDefault();
          };
          var kill = compose(prevent, stop);
          return mkEvent(target, rawEvent.clientX, rawEvent.clientY, stop, prevent, kill, rawEvent);
        };
        var handle = function(filter2, handler) {
          return function(rawEvent) {
            if (filter2(rawEvent)) {
              handler(fromRawEvent(rawEvent));
            }
          };
        };
        var binder = function(element, event, filter2, handler, useCapture) {
          var wrapped = handle(filter2, handler);
          element.dom.addEventListener(event, wrapped, useCapture);
          return { unbind: curry(unbind, element, event, wrapped, useCapture) };
        };
        var bind$2 = function(element, event, filter2, handler) {
          return binder(element, event, filter2, handler, false);
        };
        var unbind = function(element, event, handler, useCapture) {
          element.dom.removeEventListener(event, handler, useCapture);
        };
        var filter = always;
        var bind$1 = function(element, event, handler) {
          return bind$2(element, event, filter, handler);
        };
        var r2 = function(left2, top2) {
          var translate = function(x2, y2) {
            return r2(left2 + x2, top2 + y2);
          };
          return {
            left: left2,
            top: top2,
            translate
          };
        };
        var SugarPosition = r2;
        var get$1 = function(_DOC) {
          var doc = _DOC !== void 0 ? _DOC.dom : document;
          var x2 = doc.body.scrollLeft || doc.documentElement.scrollLeft;
          var y2 = doc.body.scrollTop || doc.documentElement.scrollTop;
          return SugarPosition(x2, y2);
        };
        var get = function(_win) {
          var win = _win === void 0 ? window : _win;
          if (detect().browser.isFirefox()) {
            return Optional.none();
          } else {
            return Optional.from(win["visualViewport"]);
          }
        };
        var bounds = function(x2, y2, width, height) {
          return {
            x: x2,
            y: y2,
            width,
            height,
            right: x2 + width,
            bottom: y2 + height
          };
        };
        var getBounds2 = function(_win) {
          var win = _win === void 0 ? window : _win;
          var doc = win.document;
          var scroll = get$1(SugarElement.fromDom(doc));
          return get(win).fold(function() {
            var html = win.document.documentElement;
            var width = html.clientWidth;
            var height = html.clientHeight;
            return bounds(scroll.left, scroll.top, width, height);
          }, function(visualViewport) {
            return bounds(Math.max(visualViewport.pageLeft, scroll.left), Math.max(visualViewport.pageTop, scroll.top), visualViewport.width, visualViewport.height);
          });
        };
        var bind = function(name, callback2, _win) {
          return get(_win).map(function(visualViewport) {
            var handler = function(e2) {
              return callback2(fromRawEvent(e2));
            };
            visualViewport.addEventListener(name, handler);
            return {
              unbind: function() {
                return visualViewport.removeEventListener(name, handler);
              }
            };
          }).getOrThunk(function() {
            return { unbind: noop3 };
          });
        };
        var global$2 = tinymce.util.Tools.resolve("tinymce.dom.DOMUtils");
        var global$1 = tinymce.util.Tools.resolve("tinymce.Env");
        var global2 = tinymce.util.Tools.resolve("tinymce.util.Delay");
        var fireFullscreenStateChanged = function(editor, state) {
          editor.fire("FullscreenStateChanged", { state });
        };
        var getFullscreenNative = function(editor) {
          return editor.getParam("fullscreen_native", false, "boolean");
        };
        var getFullscreenRoot = function(editor) {
          var elem = SugarElement.fromDom(editor.getElement());
          return getShadowRoot(elem).map(getShadowHost).getOrThunk(function() {
            return getBody(owner(elem));
          });
        };
        var getFullscreenElement = function(root) {
          if (root.fullscreenElement !== void 0) {
            return root.fullscreenElement;
          } else if (root.msFullscreenElement !== void 0) {
            return root.msFullscreenElement;
          } else if (root.webkitFullscreenElement !== void 0) {
            return root.webkitFullscreenElement;
          } else {
            return null;
          }
        };
        var getFullscreenchangeEventName = function() {
          if (document.fullscreenElement !== void 0) {
            return "fullscreenchange";
          } else if (document.msFullscreenElement !== void 0) {
            return "MSFullscreenChange";
          } else if (document.webkitFullscreenElement !== void 0) {
            return "webkitfullscreenchange";
          } else {
            return "fullscreenchange";
          }
        };
        var requestFullscreen = function(sugarElem) {
          var elem = sugarElem.dom;
          if (elem.requestFullscreen) {
            elem.requestFullscreen();
          } else if (elem.msRequestFullscreen) {
            elem.msRequestFullscreen();
          } else if (elem.webkitRequestFullScreen) {
            elem.webkitRequestFullScreen();
          }
        };
        var exitFullscreen = function(sugarDoc) {
          var doc = sugarDoc.dom;
          if (doc.exitFullscreen) {
            doc.exitFullscreen();
          } else if (doc.msExitFullscreen) {
            doc.msExitFullscreen();
          } else if (doc.webkitCancelFullScreen) {
            doc.webkitCancelFullScreen();
          }
        };
        var isFullscreenElement = function(elem) {
          return elem.dom === getFullscreenElement(owner(elem).dom);
        };
        var ancestors$1 = function(scope, predicate, isRoot) {
          return filter$1(parents(scope, isRoot), predicate);
        };
        var siblings$1 = function(scope, predicate) {
          return filter$1(siblings$2(scope), predicate);
        };
        var all = function(selector) {
          return all$1(selector);
        };
        var ancestors = function(scope, selector, isRoot) {
          return ancestors$1(scope, function(e2) {
            return is(e2, selector);
          }, isRoot);
        };
        var siblings = function(scope, selector) {
          return siblings$1(scope, function(e2) {
            return is(e2, selector);
          });
        };
        var attr = "data-ephox-mobile-fullscreen-style";
        var siblingStyles = "display:none!important;";
        var ancestorPosition = "position:absolute!important;";
        var ancestorStyles = "top:0!important;left:0!important;margin:0!important;padding:0!important;width:100%!important;height:100%!important;overflow:visible!important;";
        var bgFallback = "background-color:rgb(255,255,255)!important;";
        var isAndroid = global$1.os.isAndroid();
        var matchColor = function(editorBody) {
          var color2 = get$2(editorBody, "background-color");
          return color2 !== void 0 && color2 !== "" ? "background-color:" + color2 + "!important" : bgFallback;
        };
        var clobberStyles = function(dom, container, editorBody) {
          var gatherSiblings = function(element) {
            return siblings(element, "*:not(.tox-silver-sink)");
          };
          var clobber = function(clobberStyle) {
            return function(element) {
              var styles = get$3(element, "style");
              var backup = styles === void 0 ? "no-styles" : styles.trim();
              if (backup === clobberStyle) {
                return;
              } else {
                set2(element, attr, backup);
                setAll(element, dom.parseStyle(clobberStyle));
              }
            };
          };
          var ancestors$12 = ancestors(container, "*");
          var siblings$12 = bind$3(ancestors$12, gatherSiblings);
          var bgColor = matchColor(editorBody);
          each$1(siblings$12, clobber(siblingStyles));
          each$1(ancestors$12, clobber(ancestorPosition + ancestorStyles + bgColor));
          var containerStyles = isAndroid === true ? "" : ancestorPosition;
          clobber(containerStyles + ancestorStyles + bgColor)(container);
        };
        var restoreStyles = function(dom) {
          var clobberedEls = all("[" + attr + "]");
          each$1(clobberedEls, function(element) {
            var restore = get$3(element, attr);
            if (restore !== "no-styles") {
              setAll(element, dom.parseStyle(restore));
            } else {
              remove(element, "style");
            }
            remove(element, attr);
          });
        };
        var DOM = global$2.DOM;
        var getScrollPos = function() {
          return getBounds2(window);
        };
        var setScrollPos = function(pos) {
          return window.scrollTo(pos.x, pos.y);
        };
        var viewportUpdate = get().fold(function() {
          return {
            bind: noop3,
            unbind: noop3
          };
        }, function(visualViewport) {
          var editorContainer = value();
          var resizeBinder = unbindable();
          var scrollBinder = unbindable();
          var refreshScroll = function() {
            document.body.scrollTop = 0;
            document.documentElement.scrollTop = 0;
          };
          var refreshVisualViewport = function() {
            window.requestAnimationFrame(function() {
              editorContainer.on(function(container) {
                return setAll(container, {
                  top: visualViewport.offsetTop + "px",
                  left: visualViewport.offsetLeft + "px",
                  height: visualViewport.height + "px",
                  width: visualViewport.width + "px"
                });
              });
            });
          };
          var update = global2.throttle(function() {
            refreshScroll();
            refreshVisualViewport();
          }, 50);
          var bind$12 = function(element) {
            editorContainer.set(element);
            update();
            resizeBinder.set(bind("resize", update));
            scrollBinder.set(bind("scroll", update));
          };
          var unbind2 = function() {
            editorContainer.on(function() {
              resizeBinder.clear();
              scrollBinder.clear();
            });
            editorContainer.clear();
          };
          return {
            bind: bind$12,
            unbind: unbind2
          };
        });
        var toggleFullscreen = function(editor, fullscreenState) {
          var body = document.body;
          var documentElement = document.documentElement;
          var editorContainer = editor.getContainer();
          var editorContainerS = SugarElement.fromDom(editorContainer);
          var fullscreenRoot = getFullscreenRoot(editor);
          var fullscreenInfo = fullscreenState.get();
          var editorBody = SugarElement.fromDom(editor.getBody());
          var isTouch = global$1.deviceType.isTouch();
          var editorContainerStyle = editorContainer.style;
          var iframe = editor.iframeElement;
          var iframeStyle = iframe.style;
          var handleClasses = function(handler) {
            handler(body, "tox-fullscreen");
            handler(documentElement, "tox-fullscreen");
            handler(editorContainer, "tox-fullscreen");
            getShadowRoot(editorContainerS).map(function(root) {
              return getShadowHost(root).dom;
            }).each(function(host) {
              handler(host, "tox-fullscreen");
              handler(host, "tox-shadowhost");
            });
          };
          var cleanup = function() {
            if (isTouch) {
              restoreStyles(editor.dom);
            }
            handleClasses(DOM.removeClass);
            viewportUpdate.unbind();
            Optional.from(fullscreenState.get()).each(function(info) {
              return info.fullscreenChangeHandler.unbind();
            });
          };
          if (!fullscreenInfo) {
            var fullscreenChangeHandler = bind$1(owner(fullscreenRoot), getFullscreenchangeEventName(), function(_evt) {
              if (getFullscreenNative(editor)) {
                if (!isFullscreenElement(fullscreenRoot) && fullscreenState.get() !== null) {
                  toggleFullscreen(editor, fullscreenState);
                }
              }
            });
            var newFullScreenInfo = {
              scrollPos: getScrollPos(),
              containerWidth: editorContainerStyle.width,
              containerHeight: editorContainerStyle.height,
              containerTop: editorContainerStyle.top,
              containerLeft: editorContainerStyle.left,
              iframeWidth: iframeStyle.width,
              iframeHeight: iframeStyle.height,
              fullscreenChangeHandler
            };
            if (isTouch) {
              clobberStyles(editor.dom, editorContainerS, editorBody);
            }
            iframeStyle.width = iframeStyle.height = "100%";
            editorContainerStyle.width = editorContainerStyle.height = "";
            handleClasses(DOM.addClass);
            viewportUpdate.bind(editorContainerS);
            editor.on("remove", cleanup);
            fullscreenState.set(newFullScreenInfo);
            if (getFullscreenNative(editor)) {
              requestFullscreen(fullscreenRoot);
            }
            fireFullscreenStateChanged(editor, true);
          } else {
            fullscreenInfo.fullscreenChangeHandler.unbind();
            if (getFullscreenNative(editor) && isFullscreenElement(fullscreenRoot)) {
              exitFullscreen(owner(fullscreenRoot));
            }
            iframeStyle.width = fullscreenInfo.iframeWidth;
            iframeStyle.height = fullscreenInfo.iframeHeight;
            editorContainerStyle.width = fullscreenInfo.containerWidth;
            editorContainerStyle.height = fullscreenInfo.containerHeight;
            editorContainerStyle.top = fullscreenInfo.containerTop;
            editorContainerStyle.left = fullscreenInfo.containerLeft;
            setScrollPos(fullscreenInfo.scrollPos);
            fullscreenState.set(null);
            fireFullscreenStateChanged(editor, false);
            cleanup();
            editor.off("remove", cleanup);
          }
        };
        var register$1 = function(editor, fullscreenState) {
          editor.addCommand("mceFullScreen", function() {
            toggleFullscreen(editor, fullscreenState);
          });
        };
        var makeSetupHandler = function(editor, fullscreenState) {
          return function(api) {
            api.setActive(fullscreenState.get() !== null);
            var editorEventCallback = function(e2) {
              return api.setActive(e2.state);
            };
            editor.on("FullscreenStateChanged", editorEventCallback);
            return function() {
              return editor.off("FullscreenStateChanged", editorEventCallback);
            };
          };
        };
        var register = function(editor, fullscreenState) {
          var onAction = function() {
            return editor.execCommand("mceFullScreen");
          };
          editor.ui.registry.addToggleMenuItem("fullscreen", {
            text: "Fullscreen",
            icon: "fullscreen",
            shortcut: "Meta+Shift+F",
            onAction,
            onSetup: makeSetupHandler(editor, fullscreenState)
          });
          editor.ui.registry.addToggleButton("fullscreen", {
            tooltip: "Fullscreen",
            icon: "fullscreen",
            onAction,
            onSetup: makeSetupHandler(editor, fullscreenState)
          });
        };
        function Plugin() {
          global$3.add("fullscreen", function(editor) {
            var fullscreenState = Cell(null);
            if (editor.inline) {
              return get$5(fullscreenState);
            }
            register$1(editor, fullscreenState);
            register(editor, fullscreenState);
            editor.addShortcut("Meta+Shift+F", "", "mceFullScreen");
            return get$5(fullscreenState);
          });
        }
        Plugin();
      })();
    }
  });

  // ../../node_modules/tinymce/plugins/image/plugin.js
  var require_plugin13 = __commonJS({
    "../../node_modules/tinymce/plugins/image/plugin.js"() {
      (function() {
        "use strict";
        var global$6 = tinymce.util.Tools.resolve("tinymce.PluginManager");
        var __assign = function() {
          __assign = Object.assign || function __assign2(t2) {
            for (var s2, i2 = 1, n2 = arguments.length; i2 < n2; i2++) {
              s2 = arguments[i2];
              for (var p2 in s2)
                if (Object.prototype.hasOwnProperty.call(s2, p2))
                  t2[p2] = s2[p2];
            }
            return t2;
          };
          return __assign.apply(this, arguments);
        };
        var typeOf = function(x2) {
          var t2 = typeof x2;
          if (x2 === null) {
            return "null";
          } else if (t2 === "object" && (Array.prototype.isPrototypeOf(x2) || x2.constructor && x2.constructor.name === "Array")) {
            return "array";
          } else if (t2 === "object" && (String.prototype.isPrototypeOf(x2) || x2.constructor && x2.constructor.name === "String")) {
            return "string";
          } else {
            return t2;
          }
        };
        var isType = function(type) {
          return function(value) {
            return typeOf(value) === type;
          };
        };
        var isSimpleType = function(type) {
          return function(value) {
            return typeof value === type;
          };
        };
        var eq2 = function(t2) {
          return function(a2) {
            return t2 === a2;
          };
        };
        var isString = isType("string");
        var isObject2 = isType("object");
        var isArray2 = isType("array");
        var isNull = eq2(null);
        var isBoolean = isSimpleType("boolean");
        var isNullable = function(a2) {
          return a2 === null || a2 === void 0;
        };
        var isNonNullable = function(a2) {
          return !isNullable(a2);
        };
        var isFunction2 = isSimpleType("function");
        var isNumber2 = isSimpleType("number");
        var noop3 = function() {
        };
        var constant = function(value) {
          return function() {
            return value;
          };
        };
        var identity = function(x2) {
          return x2;
        };
        var never = constant(false);
        var always = constant(true);
        var none = function() {
          return NONE;
        };
        var NONE = function() {
          var call = function(thunk) {
            return thunk();
          };
          var id2 = identity;
          var me2 = {
            fold: function(n2, _s) {
              return n2();
            },
            isSome: never,
            isNone: always,
            getOr: id2,
            getOrThunk: call,
            getOrDie: function(msg) {
              throw new Error(msg || "error: getOrDie called on none.");
            },
            getOrNull: constant(null),
            getOrUndefined: constant(void 0),
            or: id2,
            orThunk: call,
            map: none,
            each: noop3,
            bind: none,
            exists: never,
            forall: always,
            filter: function() {
              return none();
            },
            toArray: function() {
              return [];
            },
            toString: constant("none()")
          };
          return me2;
        }();
        var some = function(a2) {
          var constant_a = constant(a2);
          var self2 = function() {
            return me2;
          };
          var bind = function(f2) {
            return f2(a2);
          };
          var me2 = {
            fold: function(n2, s2) {
              return s2(a2);
            },
            isSome: always,
            isNone: never,
            getOr: constant_a,
            getOrThunk: constant_a,
            getOrDie: constant_a,
            getOrNull: constant_a,
            getOrUndefined: constant_a,
            or: self2,
            orThunk: self2,
            map: function(f2) {
              return some(f2(a2));
            },
            each: function(f2) {
              f2(a2);
            },
            bind,
            exists: bind,
            forall: bind,
            filter: function(f2) {
              return f2(a2) ? me2 : NONE;
            },
            toArray: function() {
              return [a2];
            },
            toString: function() {
              return "some(" + a2 + ")";
            }
          };
          return me2;
        };
        var from = function(value) {
          return value === null || value === void 0 ? NONE : some(value);
        };
        var Optional = {
          some,
          none,
          from
        };
        var keys = Object.keys;
        var hasOwnProperty = Object.hasOwnProperty;
        var each2 = function(obj, f2) {
          var props = keys(obj);
          for (var k2 = 0, len = props.length; k2 < len; k2++) {
            var i2 = props[k2];
            var x2 = obj[i2];
            f2(x2, i2);
          }
        };
        var objAcc = function(r2) {
          return function(x2, i2) {
            r2[i2] = x2;
          };
        };
        var internalFilter = function(obj, pred, onTrue, onFalse) {
          var r2 = {};
          each2(obj, function(x2, i2) {
            (pred(x2, i2) ? onTrue : onFalse)(x2, i2);
          });
          return r2;
        };
        var filter = function(obj, pred) {
          var t2 = {};
          internalFilter(obj, pred, objAcc(t2), noop3);
          return t2;
        };
        var has = function(obj, key) {
          return hasOwnProperty.call(obj, key);
        };
        var hasNonNullableKey = function(obj, key) {
          return has(obj, key) && obj[key] !== void 0 && obj[key] !== null;
        };
        var nativePush = Array.prototype.push;
        var flatten = function(xs) {
          var r2 = [];
          for (var i2 = 0, len = xs.length; i2 < len; ++i2) {
            if (!isArray2(xs[i2])) {
              throw new Error("Arr.flatten item " + i2 + " was not an array, input: " + xs);
            }
            nativePush.apply(r2, xs[i2]);
          }
          return r2;
        };
        var get = function(xs, i2) {
          return i2 >= 0 && i2 < xs.length ? Optional.some(xs[i2]) : Optional.none();
        };
        var head = function(xs) {
          return get(xs, 0);
        };
        var findMap = function(arr, f2) {
          for (var i2 = 0; i2 < arr.length; i2++) {
            var r2 = f2(arr[i2], i2);
            if (r2.isSome()) {
              return r2;
            }
          }
          return Optional.none();
        };
        typeof window !== "undefined" ? window : Function("return this;")();
        var rawSet = function(dom, key, value) {
          if (isString(value) || isBoolean(value) || isNumber2(value)) {
            dom.setAttribute(key, value + "");
          } else {
            console.error("Invalid call to Attribute.set. Key ", key, ":: Value ", value, ":: Element ", dom);
            throw new Error("Attribute value was not simple");
          }
        };
        var set2 = function(element, key, value) {
          rawSet(element.dom, key, value);
        };
        var remove = function(element, key) {
          element.dom.removeAttribute(key);
        };
        var fromHtml = function(html, scope) {
          var doc = scope || document;
          var div = doc.createElement("div");
          div.innerHTML = html;
          if (!div.hasChildNodes() || div.childNodes.length > 1) {
            console.error("HTML does not have a single root node", html);
            throw new Error("HTML must have a single root node");
          }
          return fromDom(div.childNodes[0]);
        };
        var fromTag = function(tag, scope) {
          var doc = scope || document;
          var node = doc.createElement(tag);
          return fromDom(node);
        };
        var fromText = function(text, scope) {
          var doc = scope || document;
          var node = doc.createTextNode(text);
          return fromDom(node);
        };
        var fromDom = function(node) {
          if (node === null || node === void 0) {
            throw new Error("Node cannot be null or undefined");
          }
          return { dom: node };
        };
        var fromPoint = function(docElm, x2, y2) {
          return Optional.from(docElm.dom.elementFromPoint(x2, y2)).map(fromDom);
        };
        var SugarElement = {
          fromHtml,
          fromTag,
          fromText,
          fromDom,
          fromPoint
        };
        var global$5 = tinymce.util.Tools.resolve("tinymce.dom.DOMUtils");
        var global$4 = tinymce.util.Tools.resolve("tinymce.util.Promise");
        var global$3 = tinymce.util.Tools.resolve("tinymce.util.URI");
        var global$2 = tinymce.util.Tools.resolve("tinymce.util.XHR");
        var hasDimensions = function(editor) {
          return editor.getParam("image_dimensions", true, "boolean");
        };
        var hasAdvTab = function(editor) {
          return editor.getParam("image_advtab", false, "boolean");
        };
        var hasUploadTab = function(editor) {
          return editor.getParam("image_uploadtab", true, "boolean");
        };
        var getPrependUrl = function(editor) {
          return editor.getParam("image_prepend_url", "", "string");
        };
        var getClassList = function(editor) {
          return editor.getParam("image_class_list");
        };
        var hasDescription = function(editor) {
          return editor.getParam("image_description", true, "boolean");
        };
        var hasImageTitle = function(editor) {
          return editor.getParam("image_title", false, "boolean");
        };
        var hasImageCaption = function(editor) {
          return editor.getParam("image_caption", false, "boolean");
        };
        var getImageList = function(editor) {
          return editor.getParam("image_list", false);
        };
        var hasUploadUrl = function(editor) {
          return isNonNullable(editor.getParam("images_upload_url"));
        };
        var hasUploadHandler = function(editor) {
          return isNonNullable(editor.getParam("images_upload_handler"));
        };
        var showAccessibilityOptions = function(editor) {
          return editor.getParam("a11y_advanced_options", false, "boolean");
        };
        var isAutomaticUploadsEnabled = function(editor) {
          return editor.getParam("automatic_uploads", true, "boolean");
        };
        var parseIntAndGetMax = function(val1, val2) {
          return Math.max(parseInt(val1, 10), parseInt(val2, 10));
        };
        var getImageSize = function(url) {
          return new global$4(function(callback2) {
            var img = document.createElement("img");
            var done = function(dimensions) {
              img.onload = img.onerror = null;
              if (img.parentNode) {
                img.parentNode.removeChild(img);
              }
              callback2(dimensions);
            };
            img.onload = function() {
              var width = parseIntAndGetMax(img.width, img.clientWidth);
              var height = parseIntAndGetMax(img.height, img.clientHeight);
              var dimensions = {
                width,
                height
              };
              done(global$4.resolve(dimensions));
            };
            img.onerror = function() {
              done(global$4.reject("Failed to get image dimensions for: " + url));
            };
            var style = img.style;
            style.visibility = "hidden";
            style.position = "fixed";
            style.bottom = style.left = "0px";
            style.width = style.height = "auto";
            document.body.appendChild(img);
            img.src = url;
          });
        };
        var removePixelSuffix = function(value) {
          if (value) {
            value = value.replace(/px$/, "");
          }
          return value;
        };
        var addPixelSuffix = function(value) {
          if (value.length > 0 && /^[0-9]+$/.test(value)) {
            value += "px";
          }
          return value;
        };
        var mergeMargins = function(css) {
          if (css.margin) {
            var splitMargin = String(css.margin).split(" ");
            switch (splitMargin.length) {
              case 1:
                css["margin-top"] = css["margin-top"] || splitMargin[0];
                css["margin-right"] = css["margin-right"] || splitMargin[0];
                css["margin-bottom"] = css["margin-bottom"] || splitMargin[0];
                css["margin-left"] = css["margin-left"] || splitMargin[0];
                break;
              case 2:
                css["margin-top"] = css["margin-top"] || splitMargin[0];
                css["margin-right"] = css["margin-right"] || splitMargin[1];
                css["margin-bottom"] = css["margin-bottom"] || splitMargin[0];
                css["margin-left"] = css["margin-left"] || splitMargin[1];
                break;
              case 3:
                css["margin-top"] = css["margin-top"] || splitMargin[0];
                css["margin-right"] = css["margin-right"] || splitMargin[1];
                css["margin-bottom"] = css["margin-bottom"] || splitMargin[2];
                css["margin-left"] = css["margin-left"] || splitMargin[1];
                break;
              case 4:
                css["margin-top"] = css["margin-top"] || splitMargin[0];
                css["margin-right"] = css["margin-right"] || splitMargin[1];
                css["margin-bottom"] = css["margin-bottom"] || splitMargin[2];
                css["margin-left"] = css["margin-left"] || splitMargin[3];
            }
            delete css.margin;
          }
          return css;
        };
        var createImageList = function(editor, callback2) {
          var imageList = getImageList(editor);
          if (isString(imageList)) {
            global$2.send({
              url: imageList,
              success: function(text) {
                callback2(JSON.parse(text));
              }
            });
          } else if (isFunction2(imageList)) {
            imageList(callback2);
          } else {
            callback2(imageList);
          }
        };
        var waitLoadImage = function(editor, data, imgElm) {
          var selectImage = function() {
            imgElm.onload = imgElm.onerror = null;
            if (editor.selection) {
              editor.selection.select(imgElm);
              editor.nodeChanged();
            }
          };
          imgElm.onload = function() {
            if (!data.width && !data.height && hasDimensions(editor)) {
              editor.dom.setAttribs(imgElm, {
                width: String(imgElm.clientWidth),
                height: String(imgElm.clientHeight)
              });
            }
            selectImage();
          };
          imgElm.onerror = selectImage;
        };
        var blobToDataUri = function(blob) {
          return new global$4(function(resolve2, reject) {
            var reader = new FileReader();
            reader.onload = function() {
              resolve2(reader.result);
            };
            reader.onerror = function() {
              reject(reader.error.message);
            };
            reader.readAsDataURL(blob);
          });
        };
        var isPlaceholderImage = function(imgElm) {
          return imgElm.nodeName === "IMG" && (imgElm.hasAttribute("data-mce-object") || imgElm.hasAttribute("data-mce-placeholder"));
        };
        var isSafeImageUrl = function(editor, src) {
          return global$3.isDomSafe(src, "img", editor.settings);
        };
        var DOM = global$5.DOM;
        var getHspace = function(image) {
          if (image.style.marginLeft && image.style.marginRight && image.style.marginLeft === image.style.marginRight) {
            return removePixelSuffix(image.style.marginLeft);
          } else {
            return "";
          }
        };
        var getVspace = function(image) {
          if (image.style.marginTop && image.style.marginBottom && image.style.marginTop === image.style.marginBottom) {
            return removePixelSuffix(image.style.marginTop);
          } else {
            return "";
          }
        };
        var getBorder = function(image) {
          if (image.style.borderWidth) {
            return removePixelSuffix(image.style.borderWidth);
          } else {
            return "";
          }
        };
        var getAttrib = function(image, name) {
          if (image.hasAttribute(name)) {
            return image.getAttribute(name);
          } else {
            return "";
          }
        };
        var getStyle2 = function(image, name) {
          return image.style[name] ? image.style[name] : "";
        };
        var hasCaption = function(image) {
          return image.parentNode !== null && image.parentNode.nodeName === "FIGURE";
        };
        var updateAttrib = function(image, name, value) {
          if (value === "") {
            image.removeAttribute(name);
          } else {
            image.setAttribute(name, value);
          }
        };
        var wrapInFigure = function(image) {
          var figureElm = DOM.create("figure", { class: "image" });
          DOM.insertAfter(figureElm, image);
          figureElm.appendChild(image);
          figureElm.appendChild(DOM.create("figcaption", { contentEditable: "true" }, "Caption"));
          figureElm.contentEditable = "false";
        };
        var removeFigure = function(image) {
          var figureElm = image.parentNode;
          DOM.insertAfter(image, figureElm);
          DOM.remove(figureElm);
        };
        var toggleCaption = function(image) {
          if (hasCaption(image)) {
            removeFigure(image);
          } else {
            wrapInFigure(image);
          }
        };
        var normalizeStyle = function(image, normalizeCss2) {
          var attrValue = image.getAttribute("style");
          var value = normalizeCss2(attrValue !== null ? attrValue : "");
          if (value.length > 0) {
            image.setAttribute("style", value);
            image.setAttribute("data-mce-style", value);
          } else {
            image.removeAttribute("style");
          }
        };
        var setSize = function(name, normalizeCss2) {
          return function(image, name2, value) {
            if (image.style[name2]) {
              image.style[name2] = addPixelSuffix(value);
              normalizeStyle(image, normalizeCss2);
            } else {
              updateAttrib(image, name2, value);
            }
          };
        };
        var getSize = function(image, name) {
          if (image.style[name]) {
            return removePixelSuffix(image.style[name]);
          } else {
            return getAttrib(image, name);
          }
        };
        var setHspace = function(image, value) {
          var pxValue = addPixelSuffix(value);
          image.style.marginLeft = pxValue;
          image.style.marginRight = pxValue;
        };
        var setVspace = function(image, value) {
          var pxValue = addPixelSuffix(value);
          image.style.marginTop = pxValue;
          image.style.marginBottom = pxValue;
        };
        var setBorder = function(image, value) {
          var pxValue = addPixelSuffix(value);
          image.style.borderWidth = pxValue;
        };
        var setBorderStyle = function(image, value) {
          image.style.borderStyle = value;
        };
        var getBorderStyle = function(image) {
          return getStyle2(image, "borderStyle");
        };
        var isFigure = function(elm) {
          return elm.nodeName === "FIGURE";
        };
        var isImage = function(elm) {
          return elm.nodeName === "IMG";
        };
        var getIsDecorative = function(image) {
          return DOM.getAttrib(image, "alt").length === 0 && DOM.getAttrib(image, "role") === "presentation";
        };
        var getAlt = function(image) {
          if (getIsDecorative(image)) {
            return "";
          } else {
            return getAttrib(image, "alt");
          }
        };
        var defaultData = function() {
          return {
            src: "",
            alt: "",
            title: "",
            width: "",
            height: "",
            class: "",
            style: "",
            caption: false,
            hspace: "",
            vspace: "",
            border: "",
            borderStyle: "",
            isDecorative: false
          };
        };
        var getStyleValue = function(normalizeCss2, data) {
          var image = document.createElement("img");
          updateAttrib(image, "style", data.style);
          if (getHspace(image) || data.hspace !== "") {
            setHspace(image, data.hspace);
          }
          if (getVspace(image) || data.vspace !== "") {
            setVspace(image, data.vspace);
          }
          if (getBorder(image) || data.border !== "") {
            setBorder(image, data.border);
          }
          if (getBorderStyle(image) || data.borderStyle !== "") {
            setBorderStyle(image, data.borderStyle);
          }
          return normalizeCss2(image.getAttribute("style"));
        };
        var create = function(normalizeCss2, data) {
          var image = document.createElement("img");
          write2(normalizeCss2, __assign(__assign({}, data), { caption: false }), image);
          setAlt(image, data.alt, data.isDecorative);
          if (data.caption) {
            var figure = DOM.create("figure", { class: "image" });
            figure.appendChild(image);
            figure.appendChild(DOM.create("figcaption", { contentEditable: "true" }, "Caption"));
            figure.contentEditable = "false";
            return figure;
          } else {
            return image;
          }
        };
        var read2 = function(normalizeCss2, image) {
          return {
            src: getAttrib(image, "src"),
            alt: getAlt(image),
            title: getAttrib(image, "title"),
            width: getSize(image, "width"),
            height: getSize(image, "height"),
            class: getAttrib(image, "class"),
            style: normalizeCss2(getAttrib(image, "style")),
            caption: hasCaption(image),
            hspace: getHspace(image),
            vspace: getVspace(image),
            border: getBorder(image),
            borderStyle: getStyle2(image, "borderStyle"),
            isDecorative: getIsDecorative(image)
          };
        };
        var updateProp = function(image, oldData, newData, name, set3) {
          if (newData[name] !== oldData[name]) {
            set3(image, name, newData[name]);
          }
        };
        var setAlt = function(image, alt, isDecorative) {
          if (isDecorative) {
            DOM.setAttrib(image, "role", "presentation");
            var sugarImage = SugarElement.fromDom(image);
            set2(sugarImage, "alt", "");
          } else {
            if (isNull(alt)) {
              var sugarImage = SugarElement.fromDom(image);
              remove(sugarImage, "alt");
            } else {
              var sugarImage = SugarElement.fromDom(image);
              set2(sugarImage, "alt", alt);
            }
            if (DOM.getAttrib(image, "role") === "presentation") {
              DOM.setAttrib(image, "role", "");
            }
          }
        };
        var updateAlt = function(image, oldData, newData) {
          if (newData.alt !== oldData.alt || newData.isDecorative !== oldData.isDecorative) {
            setAlt(image, newData.alt, newData.isDecorative);
          }
        };
        var normalized = function(set3, normalizeCss2) {
          return function(image, name, value) {
            set3(image, value);
            normalizeStyle(image, normalizeCss2);
          };
        };
        var write2 = function(normalizeCss2, newData, image) {
          var oldData = read2(normalizeCss2, image);
          updateProp(image, oldData, newData, "caption", function(image2, _name, _value) {
            return toggleCaption(image2);
          });
          updateProp(image, oldData, newData, "src", updateAttrib);
          updateProp(image, oldData, newData, "title", updateAttrib);
          updateProp(image, oldData, newData, "width", setSize("width", normalizeCss2));
          updateProp(image, oldData, newData, "height", setSize("height", normalizeCss2));
          updateProp(image, oldData, newData, "class", updateAttrib);
          updateProp(image, oldData, newData, "style", normalized(function(image2, value) {
            return updateAttrib(image2, "style", value);
          }, normalizeCss2));
          updateProp(image, oldData, newData, "hspace", normalized(setHspace, normalizeCss2));
          updateProp(image, oldData, newData, "vspace", normalized(setVspace, normalizeCss2));
          updateProp(image, oldData, newData, "border", normalized(setBorder, normalizeCss2));
          updateProp(image, oldData, newData, "borderStyle", normalized(setBorderStyle, normalizeCss2));
          updateAlt(image, oldData, newData);
        };
        var normalizeCss$1 = function(editor, cssText) {
          var css = editor.dom.styles.parse(cssText);
          var mergedCss = mergeMargins(css);
          var compressed = editor.dom.styles.parse(editor.dom.styles.serialize(mergedCss));
          return editor.dom.styles.serialize(compressed);
        };
        var getSelectedImage = function(editor) {
          var imgElm = editor.selection.getNode();
          var figureElm = editor.dom.getParent(imgElm, "figure.image");
          if (figureElm) {
            return editor.dom.select("img", figureElm)[0];
          }
          if (imgElm && (imgElm.nodeName !== "IMG" || isPlaceholderImage(imgElm))) {
            return null;
          }
          return imgElm;
        };
        var splitTextBlock = function(editor, figure) {
          var dom = editor.dom;
          var textBlockElements = filter(editor.schema.getTextBlockElements(), function(_2, parentElm) {
            return !editor.schema.isValidChild(parentElm, "figure");
          });
          var textBlock = dom.getParent(figure.parentNode, function(node) {
            return hasNonNullableKey(textBlockElements, node.nodeName);
          }, editor.getBody());
          if (textBlock) {
            return dom.split(textBlock, figure);
          } else {
            return figure;
          }
        };
        var readImageDataFromSelection = function(editor) {
          var image = getSelectedImage(editor);
          return image ? read2(function(css) {
            return normalizeCss$1(editor, css);
          }, image) : defaultData();
        };
        var insertImageAtCaret = function(editor, data) {
          var elm = create(function(css) {
            return normalizeCss$1(editor, css);
          }, data);
          editor.dom.setAttrib(elm, "data-mce-id", "__mcenew");
          editor.focus();
          editor.selection.setContent(elm.outerHTML);
          var insertedElm = editor.dom.select('*[data-mce-id="__mcenew"]')[0];
          editor.dom.setAttrib(insertedElm, "data-mce-id", null);
          if (isFigure(insertedElm)) {
            var figure = splitTextBlock(editor, insertedElm);
            editor.selection.select(figure);
          } else {
            editor.selection.select(insertedElm);
          }
        };
        var syncSrcAttr = function(editor, image) {
          editor.dom.setAttrib(image, "src", image.getAttribute("src"));
        };
        var deleteImage = function(editor, image) {
          if (image) {
            var elm = editor.dom.is(image.parentNode, "figure.image") ? image.parentNode : image;
            editor.dom.remove(elm);
            editor.focus();
            editor.nodeChanged();
            if (editor.dom.isEmpty(editor.getBody())) {
              editor.setContent("");
              editor.selection.setCursorLocation();
            }
          }
        };
        var writeImageDataToSelection = function(editor, data) {
          var image = getSelectedImage(editor);
          write2(function(css) {
            return normalizeCss$1(editor, css);
          }, data, image);
          syncSrcAttr(editor, image);
          if (isFigure(image.parentNode)) {
            var figure = image.parentNode;
            splitTextBlock(editor, figure);
            editor.selection.select(image.parentNode);
          } else {
            editor.selection.select(image);
            waitLoadImage(editor, data, image);
          }
        };
        var sanitizeImageData = function(editor, data) {
          var src = data.src;
          return __assign(__assign({}, data), { src: isSafeImageUrl(editor, src) ? src : "" });
        };
        var insertOrUpdateImage = function(editor, partialData) {
          var image = getSelectedImage(editor);
          if (image) {
            var selectedImageData = read2(function(css) {
              return normalizeCss$1(editor, css);
            }, image);
            var data = __assign(__assign({}, selectedImageData), partialData);
            var sanitizedData = sanitizeImageData(editor, data);
            if (data.src) {
              writeImageDataToSelection(editor, sanitizedData);
            } else {
              deleteImage(editor, image);
            }
          } else if (partialData.src) {
            insertImageAtCaret(editor, __assign(__assign({}, defaultData()), partialData));
          }
        };
        var deep = function(old, nu) {
          var bothObjects = isObject2(old) && isObject2(nu);
          return bothObjects ? deepMerge(old, nu) : nu;
        };
        var baseMerge = function(merger) {
          return function() {
            var objects = [];
            for (var _i2 = 0; _i2 < arguments.length; _i2++) {
              objects[_i2] = arguments[_i2];
            }
            if (objects.length === 0) {
              throw new Error("Can't merge zero objects");
            }
            var ret = {};
            for (var j2 = 0; j2 < objects.length; j2++) {
              var curObject = objects[j2];
              for (var key in curObject) {
                if (has(curObject, key)) {
                  ret[key] = merger(ret[key], curObject[key]);
                }
              }
            }
            return ret;
          };
        };
        var deepMerge = baseMerge(deep);
        var isNotEmpty = function(s2) {
          return s2.length > 0;
        };
        var global$1 = tinymce.util.Tools.resolve("tinymce.util.ImageUploader");
        var global2 = tinymce.util.Tools.resolve("tinymce.util.Tools");
        var getValue = function(item) {
          return isString(item.value) ? item.value : "";
        };
        var getText = function(item) {
          if (isString(item.text)) {
            return item.text;
          } else if (isString(item.title)) {
            return item.title;
          } else {
            return "";
          }
        };
        var sanitizeList = function(list, extractValue) {
          var out = [];
          global2.each(list, function(item) {
            var text = getText(item);
            if (item.menu !== void 0) {
              var items = sanitizeList(item.menu, extractValue);
              out.push({
                text,
                items
              });
            } else {
              var value = extractValue(item);
              out.push({
                text,
                value
              });
            }
          });
          return out;
        };
        var sanitizer = function(extractor) {
          if (extractor === void 0) {
            extractor = getValue;
          }
          return function(list) {
            if (list) {
              return Optional.from(list).map(function(list2) {
                return sanitizeList(list2, extractor);
              });
            } else {
              return Optional.none();
            }
          };
        };
        var sanitize = function(list) {
          return sanitizer(getValue)(list);
        };
        var isGroup = function(item) {
          return has(item, "items");
        };
        var findEntryDelegate = function(list, value) {
          return findMap(list, function(item) {
            if (isGroup(item)) {
              return findEntryDelegate(item.items, value);
            } else if (item.value === value) {
              return Optional.some(item);
            } else {
              return Optional.none();
            }
          });
        };
        var findEntry = function(optList, value) {
          return optList.bind(function(list) {
            return findEntryDelegate(list, value);
          });
        };
        var ListUtils = {
          sanitizer,
          sanitize,
          findEntry
        };
        var makeTab$2 = function(_info) {
          return {
            title: "Advanced",
            name: "advanced",
            items: [
              {
                type: "input",
                label: "Style",
                name: "style"
              },
              {
                type: "grid",
                columns: 2,
                items: [
                  {
                    type: "input",
                    label: "Vertical space",
                    name: "vspace",
                    inputMode: "numeric"
                  },
                  {
                    type: "input",
                    label: "Horizontal space",
                    name: "hspace",
                    inputMode: "numeric"
                  },
                  {
                    type: "input",
                    label: "Border width",
                    name: "border",
                    inputMode: "numeric"
                  },
                  {
                    type: "listbox",
                    name: "borderstyle",
                    label: "Border style",
                    items: [
                      {
                        text: "Select...",
                        value: ""
                      },
                      {
                        text: "Solid",
                        value: "solid"
                      },
                      {
                        text: "Dotted",
                        value: "dotted"
                      },
                      {
                        text: "Dashed",
                        value: "dashed"
                      },
                      {
                        text: "Double",
                        value: "double"
                      },
                      {
                        text: "Groove",
                        value: "groove"
                      },
                      {
                        text: "Ridge",
                        value: "ridge"
                      },
                      {
                        text: "Inset",
                        value: "inset"
                      },
                      {
                        text: "Outset",
                        value: "outset"
                      },
                      {
                        text: "None",
                        value: "none"
                      },
                      {
                        text: "Hidden",
                        value: "hidden"
                      }
                    ]
                  }
                ]
              }
            ]
          };
        };
        var AdvTab = { makeTab: makeTab$2 };
        var collect = function(editor) {
          var urlListSanitizer = ListUtils.sanitizer(function(item) {
            return editor.convertURL(item.value || item.url, "src");
          });
          var futureImageList = new global$4(function(completer) {
            createImageList(editor, function(imageList) {
              completer(urlListSanitizer(imageList).map(function(items) {
                return flatten([
                  [{
                    text: "None",
                    value: ""
                  }],
                  items
                ]);
              }));
            });
          });
          var classList = ListUtils.sanitize(getClassList(editor));
          var hasAdvTab$1 = hasAdvTab(editor);
          var hasUploadTab$1 = hasUploadTab(editor);
          var hasUploadUrl$1 = hasUploadUrl(editor);
          var hasUploadHandler$1 = hasUploadHandler(editor);
          var image = readImageDataFromSelection(editor);
          var hasDescription$1 = hasDescription(editor);
          var hasImageTitle$1 = hasImageTitle(editor);
          var hasDimensions$1 = hasDimensions(editor);
          var hasImageCaption$1 = hasImageCaption(editor);
          var hasAccessibilityOptions = showAccessibilityOptions(editor);
          var automaticUploads = isAutomaticUploadsEnabled(editor);
          var prependURL = Optional.some(getPrependUrl(editor)).filter(function(preUrl) {
            return isString(preUrl) && preUrl.length > 0;
          });
          return futureImageList.then(function(imageList) {
            return {
              image,
              imageList,
              classList,
              hasAdvTab: hasAdvTab$1,
              hasUploadTab: hasUploadTab$1,
              hasUploadUrl: hasUploadUrl$1,
              hasUploadHandler: hasUploadHandler$1,
              hasDescription: hasDescription$1,
              hasImageTitle: hasImageTitle$1,
              hasDimensions: hasDimensions$1,
              hasImageCaption: hasImageCaption$1,
              prependURL,
              hasAccessibilityOptions,
              automaticUploads
            };
          });
        };
        var makeItems = function(info) {
          var imageUrl = {
            name: "src",
            type: "urlinput",
            filetype: "image",
            label: "Source"
          };
          var imageList = info.imageList.map(function(items) {
            return {
              name: "images",
              type: "listbox",
              label: "Image list",
              items
            };
          });
          var imageDescription = {
            name: "alt",
            type: "input",
            label: "Alternative description",
            disabled: info.hasAccessibilityOptions && info.image.isDecorative
          };
          var imageTitle = {
            name: "title",
            type: "input",
            label: "Image title"
          };
          var imageDimensions = {
            name: "dimensions",
            type: "sizeinput"
          };
          var isDecorative = {
            type: "label",
            label: "Accessibility",
            items: [{
              name: "isDecorative",
              type: "checkbox",
              label: "Image is decorative"
            }]
          };
          var classList = info.classList.map(function(items) {
            return {
              name: "classes",
              type: "listbox",
              label: "Class",
              items
            };
          });
          var caption = {
            type: "label",
            label: "Caption",
            items: [{
              type: "checkbox",
              name: "caption",
              label: "Show caption"
            }]
          };
          var getDialogContainerType = function(useColumns) {
            return useColumns ? {
              type: "grid",
              columns: 2
            } : { type: "panel" };
          };
          return flatten([
            [imageUrl],
            imageList.toArray(),
            info.hasAccessibilityOptions && info.hasDescription ? [isDecorative] : [],
            info.hasDescription ? [imageDescription] : [],
            info.hasImageTitle ? [imageTitle] : [],
            info.hasDimensions ? [imageDimensions] : [],
            [__assign(__assign({}, getDialogContainerType(info.classList.isSome() && info.hasImageCaption)), {
              items: flatten([
                classList.toArray(),
                info.hasImageCaption ? [caption] : []
              ])
            })]
          ]);
        };
        var makeTab$1 = function(info) {
          return {
            title: "General",
            name: "general",
            items: makeItems(info)
          };
        };
        var MainTab = {
          makeTab: makeTab$1,
          makeItems
        };
        var makeTab = function(_info) {
          var items = [{
            type: "dropzone",
            name: "fileinput"
          }];
          return {
            title: "Upload",
            name: "upload",
            items
          };
        };
        var UploadTab = { makeTab };
        var createState = function(info) {
          return {
            prevImage: ListUtils.findEntry(info.imageList, info.image.src),
            prevAlt: info.image.alt,
            open: true
          };
        };
        var fromImageData = function(image) {
          return {
            src: {
              value: image.src,
              meta: {}
            },
            images: image.src,
            alt: image.alt,
            title: image.title,
            dimensions: {
              width: image.width,
              height: image.height
            },
            classes: image.class,
            caption: image.caption,
            style: image.style,
            vspace: image.vspace,
            border: image.border,
            hspace: image.hspace,
            borderstyle: image.borderStyle,
            fileinput: [],
            isDecorative: image.isDecorative
          };
        };
        var toImageData = function(data, removeEmptyAlt) {
          return {
            src: data.src.value,
            alt: data.alt.length === 0 && removeEmptyAlt ? null : data.alt,
            title: data.title,
            width: data.dimensions.width,
            height: data.dimensions.height,
            class: data.classes,
            style: data.style,
            caption: data.caption,
            hspace: data.hspace,
            vspace: data.vspace,
            border: data.border,
            borderStyle: data.borderstyle,
            isDecorative: data.isDecorative
          };
        };
        var addPrependUrl2 = function(info, srcURL) {
          if (!/^(?:[a-zA-Z]+:)?\/\//.test(srcURL)) {
            return info.prependURL.bind(function(prependUrl) {
              if (srcURL.substring(0, prependUrl.length) !== prependUrl) {
                return Optional.some(prependUrl + srcURL);
              }
              return Optional.none();
            });
          }
          return Optional.none();
        };
        var addPrependUrl = function(info, api) {
          var data = api.getData();
          addPrependUrl2(info, data.src.value).each(function(srcURL) {
            api.setData({
              src: {
                value: srcURL,
                meta: data.src.meta
              }
            });
          });
        };
        var formFillFromMeta2 = function(info, data, meta) {
          if (info.hasDescription && isString(meta.alt)) {
            data.alt = meta.alt;
          }
          if (info.hasAccessibilityOptions) {
            data.isDecorative = meta.isDecorative || data.isDecorative || false;
          }
          if (info.hasImageTitle && isString(meta.title)) {
            data.title = meta.title;
          }
          if (info.hasDimensions) {
            if (isString(meta.width)) {
              data.dimensions.width = meta.width;
            }
            if (isString(meta.height)) {
              data.dimensions.height = meta.height;
            }
          }
          if (isString(meta.class)) {
            ListUtils.findEntry(info.classList, meta.class).each(function(entry) {
              data.classes = entry.value;
            });
          }
          if (info.hasImageCaption) {
            if (isBoolean(meta.caption)) {
              data.caption = meta.caption;
            }
          }
          if (info.hasAdvTab) {
            if (isString(meta.style)) {
              data.style = meta.style;
            }
            if (isString(meta.vspace)) {
              data.vspace = meta.vspace;
            }
            if (isString(meta.border)) {
              data.border = meta.border;
            }
            if (isString(meta.hspace)) {
              data.hspace = meta.hspace;
            }
            if (isString(meta.borderstyle)) {
              data.borderstyle = meta.borderstyle;
            }
          }
        };
        var formFillFromMeta = function(info, api) {
          var data = api.getData();
          var meta = data.src.meta;
          if (meta !== void 0) {
            var newData = deepMerge({}, data);
            formFillFromMeta2(info, newData, meta);
            api.setData(newData);
          }
        };
        var calculateImageSize = function(helpers, info, state, api) {
          var data = api.getData();
          var url = data.src.value;
          var meta = data.src.meta || {};
          if (!meta.width && !meta.height && info.hasDimensions) {
            if (isNotEmpty(url)) {
              helpers.imageSize(url).then(function(size) {
                if (state.open) {
                  api.setData({ dimensions: size });
                }
              }).catch(function(e2) {
                return console.error(e2);
              });
            } else {
              api.setData({
                dimensions: {
                  width: "",
                  height: ""
                }
              });
            }
          }
        };
        var updateImagesDropdown = function(info, state, api) {
          var data = api.getData();
          var image = ListUtils.findEntry(info.imageList, data.src.value);
          state.prevImage = image;
          api.setData({
            images: image.map(function(entry) {
              return entry.value;
            }).getOr("")
          });
        };
        var changeSrc = function(helpers, info, state, api) {
          addPrependUrl(info, api);
          formFillFromMeta(info, api);
          calculateImageSize(helpers, info, state, api);
          updateImagesDropdown(info, state, api);
        };
        var changeImages = function(helpers, info, state, api) {
          var data = api.getData();
          var image = ListUtils.findEntry(info.imageList, data.images);
          image.each(function(img) {
            var updateAlt2 = data.alt === "" || state.prevImage.map(function(image2) {
              return image2.text === data.alt;
            }).getOr(false);
            if (updateAlt2) {
              if (img.value === "") {
                api.setData({
                  src: img,
                  alt: state.prevAlt
                });
              } else {
                api.setData({
                  src: img,
                  alt: img.text
                });
              }
            } else {
              api.setData({ src: img });
            }
          });
          state.prevImage = image;
          changeSrc(helpers, info, state, api);
        };
        var calcVSpace = function(css) {
          var matchingTopBottom = css["margin-top"] && css["margin-bottom"] && css["margin-top"] === css["margin-bottom"];
          return matchingTopBottom ? removePixelSuffix(String(css["margin-top"])) : "";
        };
        var calcHSpace = function(css) {
          var matchingLeftRight = css["margin-right"] && css["margin-left"] && css["margin-right"] === css["margin-left"];
          return matchingLeftRight ? removePixelSuffix(String(css["margin-right"])) : "";
        };
        var calcBorderWidth = function(css) {
          return css["border-width"] ? removePixelSuffix(String(css["border-width"])) : "";
        };
        var calcBorderStyle = function(css) {
          return css["border-style"] ? String(css["border-style"]) : "";
        };
        var calcStyle = function(parseStyle2, serializeStyle2, css) {
          return serializeStyle2(parseStyle2(serializeStyle2(css)));
        };
        var changeStyle2 = function(parseStyle2, serializeStyle2, data) {
          var css = mergeMargins(parseStyle2(data.style));
          var dataCopy = deepMerge({}, data);
          dataCopy.vspace = calcVSpace(css);
          dataCopy.hspace = calcHSpace(css);
          dataCopy.border = calcBorderWidth(css);
          dataCopy.borderstyle = calcBorderStyle(css);
          dataCopy.style = calcStyle(parseStyle2, serializeStyle2, css);
          return dataCopy;
        };
        var changeStyle = function(helpers, api) {
          var data = api.getData();
          var newData = changeStyle2(helpers.parseStyle, helpers.serializeStyle, data);
          api.setData(newData);
        };
        var changeAStyle = function(helpers, info, api) {
          var data = deepMerge(fromImageData(info.image), api.getData());
          var style = getStyleValue(helpers.normalizeCss, toImageData(data, false));
          api.setData({ style });
        };
        var changeFileInput = function(helpers, info, state, api) {
          var data = api.getData();
          api.block("Uploading image");
          head(data.fileinput).fold(function() {
            api.unblock();
          }, function(file) {
            var blobUri = URL.createObjectURL(file);
            var finalize = function() {
              api.unblock();
              URL.revokeObjectURL(blobUri);
            };
            var updateSrcAndSwitchTab = function(url) {
              api.setData({
                src: {
                  value: url,
                  meta: {}
                }
              });
              api.showTab("general");
              changeSrc(helpers, info, state, api);
            };
            blobToDataUri(file).then(function(dataUrl) {
              var blobInfo = helpers.createBlobCache(file, blobUri, dataUrl);
              if (info.automaticUploads) {
                helpers.uploadImage(blobInfo).then(function(result) {
                  updateSrcAndSwitchTab(result.url);
                  finalize();
                }).catch(function(err) {
                  finalize();
                  helpers.alertErr(err);
                });
              } else {
                helpers.addToBlobCache(blobInfo);
                updateSrcAndSwitchTab(blobInfo.blobUri());
                api.unblock();
              }
            });
          });
        };
        var changeHandler = function(helpers, info, state) {
          return function(api, evt) {
            if (evt.name === "src") {
              changeSrc(helpers, info, state, api);
            } else if (evt.name === "images") {
              changeImages(helpers, info, state, api);
            } else if (evt.name === "alt") {
              state.prevAlt = api.getData().alt;
            } else if (evt.name === "style") {
              changeStyle(helpers, api);
            } else if (evt.name === "vspace" || evt.name === "hspace" || evt.name === "border" || evt.name === "borderstyle") {
              changeAStyle(helpers, info, api);
            } else if (evt.name === "fileinput") {
              changeFileInput(helpers, info, state, api);
            } else if (evt.name === "isDecorative") {
              if (api.getData().isDecorative) {
                api.disable("alt");
              } else {
                api.enable("alt");
              }
            }
          };
        };
        var closeHandler = function(state) {
          return function() {
            state.open = false;
          };
        };
        var makeDialogBody = function(info) {
          if (info.hasAdvTab || info.hasUploadUrl || info.hasUploadHandler) {
            var tabPanel = {
              type: "tabpanel",
              tabs: flatten([
                [MainTab.makeTab(info)],
                info.hasAdvTab ? [AdvTab.makeTab(info)] : [],
                info.hasUploadTab && (info.hasUploadUrl || info.hasUploadHandler) ? [UploadTab.makeTab(info)] : []
              ])
            };
            return tabPanel;
          } else {
            var panel = {
              type: "panel",
              items: MainTab.makeItems(info)
            };
            return panel;
          }
        };
        var makeDialog = function(helpers) {
          return function(info) {
            var state = createState(info);
            return {
              title: "Insert/Edit Image",
              size: "normal",
              body: makeDialogBody(info),
              buttons: [
                {
                  type: "cancel",
                  name: "cancel",
                  text: "Cancel"
                },
                {
                  type: "submit",
                  name: "save",
                  text: "Save",
                  primary: true
                }
              ],
              initialData: fromImageData(info.image),
              onSubmit: helpers.onSubmit(info),
              onChange: changeHandler(helpers, info, state),
              onClose: closeHandler(state)
            };
          };
        };
        var submitHandler = function(editor) {
          return function(info) {
            return function(api) {
              var data = deepMerge(fromImageData(info.image), api.getData());
              editor.execCommand("mceUpdateImage", false, toImageData(data, info.hasAccessibilityOptions));
              editor.editorUpload.uploadImagesAuto();
              api.close();
            };
          };
        };
        var imageSize = function(editor) {
          return function(url) {
            if (!isSafeImageUrl(editor, url)) {
              return global$4.resolve({
                width: "",
                height: ""
              });
            } else {
              return getImageSize(editor.documentBaseURI.toAbsolute(url)).then(function(dimensions) {
                return {
                  width: String(dimensions.width),
                  height: String(dimensions.height)
                };
              });
            }
          };
        };
        var createBlobCache = function(editor) {
          return function(file, blobUri, dataUrl) {
            return editor.editorUpload.blobCache.create({
              blob: file,
              blobUri,
              name: file.name ? file.name.replace(/\.[^\.]+$/, "") : null,
              filename: file.name,
              base64: dataUrl.split(",")[1]
            });
          };
        };
        var addToBlobCache = function(editor) {
          return function(blobInfo) {
            editor.editorUpload.blobCache.add(blobInfo);
          };
        };
        var alertErr = function(editor) {
          return function(message) {
            editor.windowManager.alert(message);
          };
        };
        var normalizeCss = function(editor) {
          return function(cssText) {
            return normalizeCss$1(editor, cssText);
          };
        };
        var parseStyle = function(editor) {
          return function(cssText) {
            return editor.dom.parseStyle(cssText);
          };
        };
        var serializeStyle = function(editor) {
          return function(stylesArg, name) {
            return editor.dom.serializeStyle(stylesArg, name);
          };
        };
        var uploadImage = function(editor) {
          return function(blobInfo) {
            return global$1(editor).upload([blobInfo], false).then(function(results) {
              if (results.length === 0) {
                return global$4.reject("Failed to upload image");
              } else if (results[0].status === false) {
                return global$4.reject(results[0].error.message);
              } else {
                return results[0];
              }
            });
          };
        };
        var Dialog = function(editor) {
          var helpers = {
            onSubmit: submitHandler(editor),
            imageSize: imageSize(editor),
            addToBlobCache: addToBlobCache(editor),
            createBlobCache: createBlobCache(editor),
            alertErr: alertErr(editor),
            normalizeCss: normalizeCss(editor),
            parseStyle: parseStyle(editor),
            serializeStyle: serializeStyle(editor),
            uploadImage: uploadImage(editor)
          };
          var open = function() {
            collect(editor).then(makeDialog(helpers)).then(editor.windowManager.open);
          };
          return { open };
        };
        var register$1 = function(editor) {
          editor.addCommand("mceImage", Dialog(editor).open);
          editor.addCommand("mceUpdateImage", function(_ui, data) {
            editor.undoManager.transact(function() {
              return insertOrUpdateImage(editor, data);
            });
          });
        };
        var hasImageClass = function(node) {
          var className = node.attr("class");
          return className && /\bimage\b/.test(className);
        };
        var toggleContentEditableState = function(state) {
          return function(nodes) {
            var i2 = nodes.length;
            var toggleContentEditable = function(node2) {
              node2.attr("contenteditable", state ? "true" : null);
            };
            while (i2--) {
              var node = nodes[i2];
              if (hasImageClass(node)) {
                node.attr("contenteditable", state ? "false" : null);
                global2.each(node.getAll("figcaption"), toggleContentEditable);
              }
            }
          };
        };
        var setup = function(editor) {
          editor.on("PreInit", function() {
            editor.parser.addNodeFilter("figure", toggleContentEditableState(true));
            editor.serializer.addNodeFilter("figure", toggleContentEditableState(false));
          });
        };
        var register = function(editor) {
          editor.ui.registry.addToggleButton("image", {
            icon: "image",
            tooltip: "Insert/edit image",
            onAction: Dialog(editor).open,
            onSetup: function(buttonApi) {
              buttonApi.setActive(isNonNullable(getSelectedImage(editor)));
              return editor.selection.selectorChangedWithUnbind("img:not([data-mce-object],[data-mce-placeholder]),figure.image", buttonApi.setActive).unbind;
            }
          });
          editor.ui.registry.addMenuItem("image", {
            icon: "image",
            text: "Image...",
            onAction: Dialog(editor).open
          });
          editor.ui.registry.addContextMenu("image", {
            update: function(element) {
              return isFigure(element) || isImage(element) && !isPlaceholderImage(element) ? ["image"] : [];
            }
          });
        };
        function Plugin() {
          global$6.add("image", function(editor) {
            setup(editor);
            register(editor);
            register$1(editor);
          });
        }
        Plugin();
      })();
    }
  });

  // ../../node_modules/tinymce/plugins/link/plugin.js
  var require_plugin14 = __commonJS({
    "../../node_modules/tinymce/plugins/link/plugin.js"() {
      (function() {
        "use strict";
        var global$7 = tinymce.util.Tools.resolve("tinymce.PluginManager");
        var global$6 = tinymce.util.Tools.resolve("tinymce.util.VK");
        var typeOf = function(x2) {
          var t2 = typeof x2;
          if (x2 === null) {
            return "null";
          } else if (t2 === "object" && (Array.prototype.isPrototypeOf(x2) || x2.constructor && x2.constructor.name === "Array")) {
            return "array";
          } else if (t2 === "object" && (String.prototype.isPrototypeOf(x2) || x2.constructor && x2.constructor.name === "String")) {
            return "string";
          } else {
            return t2;
          }
        };
        var isType = function(type) {
          return function(value) {
            return typeOf(value) === type;
          };
        };
        var isSimpleType = function(type) {
          return function(value) {
            return typeof value === type;
          };
        };
        var eq2 = function(t2) {
          return function(a2) {
            return t2 === a2;
          };
        };
        var isString = isType("string");
        var isArray2 = isType("array");
        var isNull = eq2(null);
        var isBoolean = isSimpleType("boolean");
        var isFunction2 = isSimpleType("function");
        var noop3 = function() {
        };
        var constant = function(value) {
          return function() {
            return value;
          };
        };
        var identity = function(x2) {
          return x2;
        };
        var tripleEquals = function(a2, b2) {
          return a2 === b2;
        };
        var never = constant(false);
        var always = constant(true);
        var none = function() {
          return NONE;
        };
        var NONE = function() {
          var call = function(thunk) {
            return thunk();
          };
          var id2 = identity;
          var me2 = {
            fold: function(n2, _s) {
              return n2();
            },
            isSome: never,
            isNone: always,
            getOr: id2,
            getOrThunk: call,
            getOrDie: function(msg) {
              throw new Error(msg || "error: getOrDie called on none.");
            },
            getOrNull: constant(null),
            getOrUndefined: constant(void 0),
            or: id2,
            orThunk: call,
            map: none,
            each: noop3,
            bind: none,
            exists: never,
            forall: always,
            filter: function() {
              return none();
            },
            toArray: function() {
              return [];
            },
            toString: constant("none()")
          };
          return me2;
        }();
        var some = function(a2) {
          var constant_a = constant(a2);
          var self2 = function() {
            return me2;
          };
          var bind2 = function(f2) {
            return f2(a2);
          };
          var me2 = {
            fold: function(n2, s2) {
              return s2(a2);
            },
            isSome: always,
            isNone: never,
            getOr: constant_a,
            getOrThunk: constant_a,
            getOrDie: constant_a,
            getOrNull: constant_a,
            getOrUndefined: constant_a,
            or: self2,
            orThunk: self2,
            map: function(f2) {
              return some(f2(a2));
            },
            each: function(f2) {
              f2(a2);
            },
            bind: bind2,
            exists: bind2,
            forall: bind2,
            filter: function(f2) {
              return f2(a2) ? me2 : NONE;
            },
            toArray: function() {
              return [a2];
            },
            toString: function() {
              return "some(" + a2 + ")";
            }
          };
          return me2;
        };
        var from = function(value) {
          return value === null || value === void 0 ? NONE : some(value);
        };
        var Optional = {
          some,
          none,
          from
        };
        var nativeIndexOf = Array.prototype.indexOf;
        var nativePush = Array.prototype.push;
        var rawIndexOf = function(ts, t2) {
          return nativeIndexOf.call(ts, t2);
        };
        var contains2 = function(xs, x2) {
          return rawIndexOf(xs, x2) > -1;
        };
        var map3 = function(xs, f2) {
          var len = xs.length;
          var r2 = new Array(len);
          for (var i2 = 0; i2 < len; i2++) {
            var x2 = xs[i2];
            r2[i2] = f2(x2, i2);
          }
          return r2;
        };
        var each$1 = function(xs, f2) {
          for (var i2 = 0, len = xs.length; i2 < len; i2++) {
            var x2 = xs[i2];
            f2(x2, i2);
          }
        };
        var foldl = function(xs, f2, acc) {
          each$1(xs, function(x2, i2) {
            acc = f2(acc, x2, i2);
          });
          return acc;
        };
        var flatten = function(xs) {
          var r2 = [];
          for (var i2 = 0, len = xs.length; i2 < len; ++i2) {
            if (!isArray2(xs[i2])) {
              throw new Error("Arr.flatten item " + i2 + " was not an array, input: " + xs);
            }
            nativePush.apply(r2, xs[i2]);
          }
          return r2;
        };
        var bind = function(xs, f2) {
          return flatten(map3(xs, f2));
        };
        var findMap = function(arr, f2) {
          for (var i2 = 0; i2 < arr.length; i2++) {
            var r2 = f2(arr[i2], i2);
            if (r2.isSome()) {
              return r2;
            }
          }
          return Optional.none();
        };
        var is = function(lhs, rhs, comparator) {
          if (comparator === void 0) {
            comparator = tripleEquals;
          }
          return lhs.exists(function(left2) {
            return comparator(left2, rhs);
          });
        };
        var cat = function(arr) {
          var r2 = [];
          var push = function(x2) {
            r2.push(x2);
          };
          for (var i2 = 0; i2 < arr.length; i2++) {
            arr[i2].each(push);
          }
          return r2;
        };
        var someIf = function(b2, a2) {
          return b2 ? Optional.some(a2) : Optional.none();
        };
        var assumeExternalTargets = function(editor) {
          var externalTargets = editor.getParam("link_assume_external_targets", false);
          if (isBoolean(externalTargets) && externalTargets) {
            return 1;
          } else if (isString(externalTargets) && (externalTargets === "http" || externalTargets === "https")) {
            return externalTargets;
          }
          return 0;
        };
        var hasContextToolbar = function(editor) {
          return editor.getParam("link_context_toolbar", false, "boolean");
        };
        var getLinkList = function(editor) {
          return editor.getParam("link_list");
        };
        var getDefaultLinkTarget = function(editor) {
          return editor.getParam("default_link_target");
        };
        var getTargetList = function(editor) {
          return editor.getParam("target_list", true);
        };
        var getRelList = function(editor) {
          return editor.getParam("rel_list", [], "array");
        };
        var getLinkClassList = function(editor) {
          return editor.getParam("link_class_list", [], "array");
        };
        var shouldShowLinkTitle = function(editor) {
          return editor.getParam("link_title", true, "boolean");
        };
        var allowUnsafeLinkTarget = function(editor) {
          return editor.getParam("allow_unsafe_link_target", false, "boolean");
        };
        var useQuickLink = function(editor) {
          return editor.getParam("link_quicklink", false, "boolean");
        };
        var getDefaultLinkProtocol = function(editor) {
          return editor.getParam("link_default_protocol", "http", "string");
        };
        var global$5 = tinymce.util.Tools.resolve("tinymce.util.Tools");
        var getValue = function(item) {
          return isString(item.value) ? item.value : "";
        };
        var getText = function(item) {
          if (isString(item.text)) {
            return item.text;
          } else if (isString(item.title)) {
            return item.title;
          } else {
            return "";
          }
        };
        var sanitizeList = function(list, extractValue) {
          var out = [];
          global$5.each(list, function(item) {
            var text = getText(item);
            if (item.menu !== void 0) {
              var items = sanitizeList(item.menu, extractValue);
              out.push({
                text,
                items
              });
            } else {
              var value = extractValue(item);
              out.push({
                text,
                value
              });
            }
          });
          return out;
        };
        var sanitizeWith = function(extracter) {
          if (extracter === void 0) {
            extracter = getValue;
          }
          return function(list) {
            return Optional.from(list).map(function(list2) {
              return sanitizeList(list2, extracter);
            });
          };
        };
        var sanitize = function(list) {
          return sanitizeWith(getValue)(list);
        };
        var createUi = function(name, label) {
          return function(items) {
            return {
              name,
              type: "listbox",
              label,
              items
            };
          };
        };
        var ListOptions = {
          sanitize,
          sanitizeWith,
          createUi,
          getValue
        };
        var __assign = function() {
          __assign = Object.assign || function __assign2(t2) {
            for (var s2, i2 = 1, n2 = arguments.length; i2 < n2; i2++) {
              s2 = arguments[i2];
              for (var p2 in s2)
                if (Object.prototype.hasOwnProperty.call(s2, p2))
                  t2[p2] = s2[p2];
            }
            return t2;
          };
          return __assign.apply(this, arguments);
        };
        var keys = Object.keys;
        var hasOwnProperty = Object.hasOwnProperty;
        var each2 = function(obj, f2) {
          var props = keys(obj);
          for (var k2 = 0, len = props.length; k2 < len; k2++) {
            var i2 = props[k2];
            var x2 = obj[i2];
            f2(x2, i2);
          }
        };
        var objAcc = function(r2) {
          return function(x2, i2) {
            r2[i2] = x2;
          };
        };
        var internalFilter = function(obj, pred, onTrue, onFalse) {
          var r2 = {};
          each2(obj, function(x2, i2) {
            (pred(x2, i2) ? onTrue : onFalse)(x2, i2);
          });
          return r2;
        };
        var filter = function(obj, pred) {
          var t2 = {};
          internalFilter(obj, pred, objAcc(t2), noop3);
          return t2;
        };
        var has = function(obj, key) {
          return hasOwnProperty.call(obj, key);
        };
        var hasNonNullableKey = function(obj, key) {
          return has(obj, key) && obj[key] !== void 0 && obj[key] !== null;
        };
        var global$4 = tinymce.util.Tools.resolve("tinymce.dom.TreeWalker");
        var global$3 = tinymce.util.Tools.resolve("tinymce.util.URI");
        var isAnchor = function(elm) {
          return elm && elm.nodeName.toLowerCase() === "a";
        };
        var isLink = function(elm) {
          return isAnchor(elm) && !!getHref(elm);
        };
        var collectNodesInRange = function(rng, predicate) {
          if (rng.collapsed) {
            return [];
          } else {
            var contents = rng.cloneContents();
            var walker = new global$4(contents.firstChild, contents);
            var elements2 = [];
            var current = contents.firstChild;
            do {
              if (predicate(current)) {
                elements2.push(current);
              }
            } while (current = walker.next());
            return elements2;
          }
        };
        var hasProtocol = function(url) {
          return /^\w+:/i.test(url);
        };
        var getHref = function(elm) {
          var href = elm.getAttribute("data-mce-href");
          return href ? href : elm.getAttribute("href");
        };
        var applyRelTargetRules = function(rel, isUnsafe) {
          var rules = ["noopener"];
          var rels = rel ? rel.split(/\s+/) : [];
          var toString = function(rels2) {
            return global$5.trim(rels2.sort().join(" "));
          };
          var addTargetRules = function(rels2) {
            rels2 = removeTargetRules(rels2);
            return rels2.length > 0 ? rels2.concat(rules) : rules;
          };
          var removeTargetRules = function(rels2) {
            return rels2.filter(function(val) {
              return global$5.inArray(rules, val) === -1;
            });
          };
          var newRels = isUnsafe ? addTargetRules(rels) : removeTargetRules(rels);
          return newRels.length > 0 ? toString(newRels) : "";
        };
        var trimCaretContainers = function(text) {
          return text.replace(/\uFEFF/g, "");
        };
        var getAnchorElement = function(editor, selectedElm) {
          selectedElm = selectedElm || editor.selection.getNode();
          if (isImageFigure(selectedElm)) {
            return editor.dom.select("a[href]", selectedElm)[0];
          } else {
            return editor.dom.getParent(selectedElm, "a[href]");
          }
        };
        var getAnchorText = function(selection, anchorElm) {
          var text = anchorElm ? anchorElm.innerText || anchorElm.textContent : selection.getContent({ format: "text" });
          return trimCaretContainers(text);
        };
        var hasLinks = function(elements2) {
          return global$5.grep(elements2, isLink).length > 0;
        };
        var hasLinksInSelection = function(rng) {
          return collectNodesInRange(rng, isLink).length > 0;
        };
        var isOnlyTextSelected = function(editor) {
          var inlineTextElements = editor.schema.getTextInlineElements();
          var isElement3 = function(elm) {
            return elm.nodeType === 1 && !isAnchor(elm) && !has(inlineTextElements, elm.nodeName.toLowerCase());
          };
          var elements2 = collectNodesInRange(editor.selection.getRng(), isElement3);
          return elements2.length === 0;
        };
        var isImageFigure = function(elm) {
          return elm && elm.nodeName === "FIGURE" && /\bimage\b/i.test(elm.className);
        };
        var getLinkAttrs = function(data) {
          var attrs = [
            "title",
            "rel",
            "class",
            "target"
          ];
          return foldl(attrs, function(acc, key) {
            data[key].each(function(value) {
              acc[key] = value.length > 0 ? value : null;
            });
            return acc;
          }, { href: data.href });
        };
        var handleExternalTargets = function(href, assumeExternalTargets2) {
          if ((assumeExternalTargets2 === "http" || assumeExternalTargets2 === "https") && !hasProtocol(href)) {
            return assumeExternalTargets2 + "://" + href;
          }
          return href;
        };
        var applyLinkOverrides = function(editor, linkAttrs) {
          var newLinkAttrs = __assign({}, linkAttrs);
          if (!(getRelList(editor).length > 0) && allowUnsafeLinkTarget(editor) === false) {
            var newRel = applyRelTargetRules(newLinkAttrs.rel, newLinkAttrs.target === "_blank");
            newLinkAttrs.rel = newRel ? newRel : null;
          }
          if (Optional.from(newLinkAttrs.target).isNone() && getTargetList(editor) === false) {
            newLinkAttrs.target = getDefaultLinkTarget(editor);
          }
          newLinkAttrs.href = handleExternalTargets(newLinkAttrs.href, assumeExternalTargets(editor));
          return newLinkAttrs;
        };
        var updateLink = function(editor, anchorElm, text, linkAttrs) {
          text.each(function(text2) {
            if (has(anchorElm, "innerText")) {
              anchorElm.innerText = text2;
            } else {
              anchorElm.textContent = text2;
            }
          });
          editor.dom.setAttribs(anchorElm, linkAttrs);
          editor.selection.select(anchorElm);
        };
        var createLink = function(editor, selectedElm, text, linkAttrs) {
          if (isImageFigure(selectedElm)) {
            linkImageFigure(editor, selectedElm, linkAttrs);
          } else {
            text.fold(function() {
              editor.execCommand("mceInsertLink", false, linkAttrs);
            }, function(text2) {
              editor.insertContent(editor.dom.createHTML("a", linkAttrs, editor.dom.encode(text2)));
            });
          }
        };
        var linkDomMutation = function(editor, attachState, data) {
          var selectedElm = editor.selection.getNode();
          var anchorElm = getAnchorElement(editor, selectedElm);
          var linkAttrs = applyLinkOverrides(editor, getLinkAttrs(data));
          editor.undoManager.transact(function() {
            if (data.href === attachState.href) {
              attachState.attach();
            }
            if (anchorElm) {
              editor.focus();
              updateLink(editor, anchorElm, data.text, linkAttrs);
            } else {
              createLink(editor, selectedElm, data.text, linkAttrs);
            }
          });
        };
        var unlinkSelection = function(editor) {
          var dom = editor.dom, selection = editor.selection;
          var bookmark = selection.getBookmark();
          var rng = selection.getRng().cloneRange();
          var startAnchorElm = dom.getParent(rng.startContainer, "a[href]", editor.getBody());
          var endAnchorElm = dom.getParent(rng.endContainer, "a[href]", editor.getBody());
          if (startAnchorElm) {
            rng.setStartBefore(startAnchorElm);
          }
          if (endAnchorElm) {
            rng.setEndAfter(endAnchorElm);
          }
          selection.setRng(rng);
          editor.execCommand("unlink");
          selection.moveToBookmark(bookmark);
        };
        var unlinkDomMutation = function(editor) {
          editor.undoManager.transact(function() {
            var node = editor.selection.getNode();
            if (isImageFigure(node)) {
              unlinkImageFigure(editor, node);
            } else {
              unlinkSelection(editor);
            }
            editor.focus();
          });
        };
        var unwrapOptions = function(data) {
          var cls = data.class, href = data.href, rel = data.rel, target = data.target, text = data.text, title = data.title;
          return filter({
            class: cls.getOrNull(),
            href,
            rel: rel.getOrNull(),
            target: target.getOrNull(),
            text: text.getOrNull(),
            title: title.getOrNull()
          }, function(v2, _k) {
            return isNull(v2) === false;
          });
        };
        var sanitizeData = function(editor, data) {
          var href = data.href;
          return __assign(__assign({}, data), { href: global$3.isDomSafe(href, "a", editor.settings) ? href : "" });
        };
        var link = function(editor, attachState, data) {
          var sanitizedData = sanitizeData(editor, data);
          editor.hasPlugin("rtc", true) ? editor.execCommand("createlink", false, unwrapOptions(sanitizedData)) : linkDomMutation(editor, attachState, sanitizedData);
        };
        var unlink = function(editor) {
          editor.hasPlugin("rtc", true) ? editor.execCommand("unlink") : unlinkDomMutation(editor);
        };
        var unlinkImageFigure = function(editor, fig) {
          var img = editor.dom.select("img", fig)[0];
          if (img) {
            var a2 = editor.dom.getParents(img, "a[href]", fig)[0];
            if (a2) {
              a2.parentNode.insertBefore(img, a2);
              editor.dom.remove(a2);
            }
          }
        };
        var linkImageFigure = function(editor, fig, attrs) {
          var img = editor.dom.select("img", fig)[0];
          if (img) {
            var a2 = editor.dom.create("a", attrs);
            img.parentNode.insertBefore(a2, img);
            a2.appendChild(img);
          }
        };
        var isListGroup = function(item) {
          return hasNonNullableKey(item, "items");
        };
        var findTextByValue = function(value, catalog) {
          return findMap(catalog, function(item) {
            if (isListGroup(item)) {
              return findTextByValue(value, item.items);
            } else {
              return someIf(item.value === value, item);
            }
          });
        };
        var getDelta = function(persistentText, fieldName, catalog, data) {
          var value = data[fieldName];
          var hasPersistentText = persistentText.length > 0;
          return value !== void 0 ? findTextByValue(value, catalog).map(function(i2) {
            return {
              url: {
                value: i2.value,
                meta: {
                  text: hasPersistentText ? persistentText : i2.text,
                  attach: noop3
                }
              },
              text: hasPersistentText ? persistentText : i2.text
            };
          }) : Optional.none();
        };
        var findCatalog = function(catalogs, fieldName) {
          if (fieldName === "link") {
            return catalogs.link;
          } else if (fieldName === "anchor") {
            return catalogs.anchor;
          } else {
            return Optional.none();
          }
        };
        var init = function(initialData, linkCatalog) {
          var persistentData = {
            text: initialData.text,
            title: initialData.title
          };
          var getTitleFromUrlChange = function(url) {
            return someIf(persistentData.title.length <= 0, Optional.from(url.meta.title).getOr(""));
          };
          var getTextFromUrlChange = function(url) {
            return someIf(persistentData.text.length <= 0, Optional.from(url.meta.text).getOr(url.value));
          };
          var onUrlChange = function(data) {
            var text = getTextFromUrlChange(data.url);
            var title = getTitleFromUrlChange(data.url);
            if (text.isSome() || title.isSome()) {
              return Optional.some(__assign(__assign({}, text.map(function(text2) {
                return { text: text2 };
              }).getOr({})), title.map(function(title2) {
                return { title: title2 };
              }).getOr({})));
            } else {
              return Optional.none();
            }
          };
          var onCatalogChange = function(data, change) {
            var catalog = findCatalog(linkCatalog, change.name).getOr([]);
            return getDelta(persistentData.text, change.name, catalog, data);
          };
          var onChange = function(getData, change) {
            var name = change.name;
            if (name === "url") {
              return onUrlChange(getData());
            } else if (contains2([
              "anchor",
              "link"
            ], name)) {
              return onCatalogChange(getData(), change);
            } else if (name === "text" || name === "title") {
              persistentData[name] = getData()[name];
              return Optional.none();
            } else {
              return Optional.none();
            }
          };
          return { onChange };
        };
        var DialogChanges = {
          init,
          getDelta
        };
        var global$2 = tinymce.util.Tools.resolve("tinymce.util.Delay");
        var global$1 = tinymce.util.Tools.resolve("tinymce.util.Promise");
        var delayedConfirm = function(editor, message, callback2) {
          var rng = editor.selection.getRng();
          global$2.setEditorTimeout(editor, function() {
            editor.windowManager.confirm(message, function(state) {
              editor.selection.setRng(rng);
              callback2(state);
            });
          });
        };
        var tryEmailTransform = function(data) {
          var url = data.href;
          var suggestMailTo = url.indexOf("@") > 0 && url.indexOf("/") === -1 && url.indexOf("mailto:") === -1;
          return suggestMailTo ? Optional.some({
            message: "The URL you entered seems to be an email address. Do you want to add the required mailto: prefix?",
            preprocess: function(oldData) {
              return __assign(__assign({}, oldData), { href: "mailto:" + url });
            }
          }) : Optional.none();
        };
        var tryProtocolTransform = function(assumeExternalTargets2, defaultLinkProtocol) {
          return function(data) {
            var url = data.href;
            var suggestProtocol = assumeExternalTargets2 === 1 && !hasProtocol(url) || assumeExternalTargets2 === 0 && /^\s*www(\.|\d\.)/i.test(url);
            return suggestProtocol ? Optional.some({
              message: "The URL you entered seems to be an external link. Do you want to add the required " + defaultLinkProtocol + ":// prefix?",
              preprocess: function(oldData) {
                return __assign(__assign({}, oldData), { href: defaultLinkProtocol + "://" + url });
              }
            }) : Optional.none();
          };
        };
        var preprocess = function(editor, data) {
          return findMap([
            tryEmailTransform,
            tryProtocolTransform(assumeExternalTargets(editor), getDefaultLinkProtocol(editor))
          ], function(f2) {
            return f2(data);
          }).fold(function() {
            return global$1.resolve(data);
          }, function(transform) {
            return new global$1(function(callback2) {
              delayedConfirm(editor, transform.message, function(state) {
                callback2(state ? transform.preprocess(data) : data);
              });
            });
          });
        };
        var DialogConfirms = { preprocess };
        var getAnchors = function(editor) {
          var anchorNodes = editor.dom.select("a:not([href])");
          var anchors = bind(anchorNodes, function(anchor) {
            var id2 = anchor.name || anchor.id;
            return id2 ? [{
              text: id2,
              value: "#" + id2
            }] : [];
          });
          return anchors.length > 0 ? Optional.some([{
            text: "None",
            value: ""
          }].concat(anchors)) : Optional.none();
        };
        var AnchorListOptions = { getAnchors };
        var getClasses = function(editor) {
          var list = getLinkClassList(editor);
          if (list.length > 0) {
            return ListOptions.sanitize(list);
          }
          return Optional.none();
        };
        var ClassListOptions = { getClasses };
        var global2 = tinymce.util.Tools.resolve("tinymce.util.XHR");
        var parseJson = function(text) {
          try {
            return Optional.some(JSON.parse(text));
          } catch (err) {
            return Optional.none();
          }
        };
        var getLinks = function(editor) {
          var extractor = function(item) {
            return editor.convertURL(item.value || item.url, "href");
          };
          var linkList = getLinkList(editor);
          return new global$1(function(callback2) {
            if (isString(linkList)) {
              global2.send({
                url: linkList,
                success: function(text) {
                  return callback2(parseJson(text));
                },
                error: function(_2) {
                  return callback2(Optional.none());
                }
              });
            } else if (isFunction2(linkList)) {
              linkList(function(output) {
                return callback2(Optional.some(output));
              });
            } else {
              callback2(Optional.from(linkList));
            }
          }).then(function(optItems) {
            return optItems.bind(ListOptions.sanitizeWith(extractor)).map(function(items) {
              if (items.length > 0) {
                var noneItem = [{
                  text: "None",
                  value: ""
                }];
                return noneItem.concat(items);
              } else {
                return items;
              }
            });
          });
        };
        var LinkListOptions = { getLinks };
        var getRels = function(editor, initialTarget) {
          var list = getRelList(editor);
          if (list.length > 0) {
            var isTargetBlank_1 = is(initialTarget, "_blank");
            var enforceSafe = allowUnsafeLinkTarget(editor) === false;
            var safeRelExtractor = function(item) {
              return applyRelTargetRules(ListOptions.getValue(item), isTargetBlank_1);
            };
            var sanitizer = enforceSafe ? ListOptions.sanitizeWith(safeRelExtractor) : ListOptions.sanitize;
            return sanitizer(list);
          }
          return Optional.none();
        };
        var RelOptions = { getRels };
        var fallbacks = [
          {
            text: "Current window",
            value: ""
          },
          {
            text: "New window",
            value: "_blank"
          }
        ];
        var getTargets = function(editor) {
          var list = getTargetList(editor);
          if (isArray2(list)) {
            return ListOptions.sanitize(list).orThunk(function() {
              return Optional.some(fallbacks);
            });
          } else if (list === false) {
            return Optional.none();
          }
          return Optional.some(fallbacks);
        };
        var TargetOptions = { getTargets };
        var nonEmptyAttr = function(dom, elem, name) {
          var val = dom.getAttrib(elem, name);
          return val !== null && val.length > 0 ? Optional.some(val) : Optional.none();
        };
        var extractFromAnchor = function(editor, anchor) {
          var dom = editor.dom;
          var onlyText = isOnlyTextSelected(editor);
          var text = onlyText ? Optional.some(getAnchorText(editor.selection, anchor)) : Optional.none();
          var url = anchor ? Optional.some(dom.getAttrib(anchor, "href")) : Optional.none();
          var target = anchor ? Optional.from(dom.getAttrib(anchor, "target")) : Optional.none();
          var rel = nonEmptyAttr(dom, anchor, "rel");
          var linkClass = nonEmptyAttr(dom, anchor, "class");
          var title = nonEmptyAttr(dom, anchor, "title");
          return {
            url,
            text,
            title,
            target,
            rel,
            linkClass
          };
        };
        var collect = function(editor, linkNode) {
          return LinkListOptions.getLinks(editor).then(function(links) {
            var anchor = extractFromAnchor(editor, linkNode);
            return {
              anchor,
              catalogs: {
                targets: TargetOptions.getTargets(editor),
                rels: RelOptions.getRels(editor, anchor.target),
                classes: ClassListOptions.getClasses(editor),
                anchor: AnchorListOptions.getAnchors(editor),
                link: links
              },
              optNode: Optional.from(linkNode),
              flags: { titleEnabled: shouldShowLinkTitle(editor) }
            };
          });
        };
        var DialogInfo = { collect };
        var handleSubmit = function(editor, info) {
          return function(api) {
            var data = api.getData();
            if (!data.url.value) {
              unlink(editor);
              api.close();
              return;
            }
            var getChangedValue = function(key) {
              return Optional.from(data[key]).filter(function(value) {
                return !is(info.anchor[key], value);
              });
            };
            var changedData = {
              href: data.url.value,
              text: getChangedValue("text"),
              target: getChangedValue("target"),
              rel: getChangedValue("rel"),
              class: getChangedValue("linkClass"),
              title: getChangedValue("title")
            };
            var attachState = {
              href: data.url.value,
              attach: data.url.meta !== void 0 && data.url.meta.attach ? data.url.meta.attach : noop3
            };
            DialogConfirms.preprocess(editor, changedData).then(function(pData) {
              link(editor, attachState, pData);
            });
            api.close();
          };
        };
        var collectData = function(editor) {
          var anchorNode = getAnchorElement(editor);
          return DialogInfo.collect(editor, anchorNode);
        };
        var getInitialData = function(info, defaultTarget) {
          var anchor = info.anchor;
          var url = anchor.url.getOr("");
          return {
            url: {
              value: url,
              meta: { original: { value: url } }
            },
            text: anchor.text.getOr(""),
            title: anchor.title.getOr(""),
            anchor: url,
            link: url,
            rel: anchor.rel.getOr(""),
            target: anchor.target.or(defaultTarget).getOr(""),
            linkClass: anchor.linkClass.getOr("")
          };
        };
        var makeDialog = function(settings, onSubmit, editor) {
          var urlInput = [{
            name: "url",
            type: "urlinput",
            filetype: "file",
            label: "URL"
          }];
          var displayText = settings.anchor.text.map(function() {
            return {
              name: "text",
              type: "input",
              label: "Text to display"
            };
          }).toArray();
          var titleText = settings.flags.titleEnabled ? [{
            name: "title",
            type: "input",
            label: "Title"
          }] : [];
          var defaultTarget = Optional.from(getDefaultLinkTarget(editor));
          var initialData = getInitialData(settings, defaultTarget);
          var catalogs = settings.catalogs;
          var dialogDelta = DialogChanges.init(initialData, catalogs);
          var body = {
            type: "panel",
            items: flatten([
              urlInput,
              displayText,
              titleText,
              cat([
                catalogs.anchor.map(ListOptions.createUi("anchor", "Anchors")),
                catalogs.rels.map(ListOptions.createUi("rel", "Rel")),
                catalogs.targets.map(ListOptions.createUi("target", "Open link in...")),
                catalogs.link.map(ListOptions.createUi("link", "Link list")),
                catalogs.classes.map(ListOptions.createUi("linkClass", "Class"))
              ])
            ])
          };
          return {
            title: "Insert/Edit Link",
            size: "normal",
            body,
            buttons: [
              {
                type: "cancel",
                name: "cancel",
                text: "Cancel"
              },
              {
                type: "submit",
                name: "save",
                text: "Save",
                primary: true
              }
            ],
            initialData,
            onChange: function(api, _a) {
              var name = _a.name;
              dialogDelta.onChange(api.getData, { name }).each(function(newData) {
                api.setData(newData);
              });
            },
            onSubmit
          };
        };
        var open$1 = function(editor) {
          var data = collectData(editor);
          data.then(function(info) {
            var onSubmit = handleSubmit(editor, info);
            return makeDialog(info, onSubmit, editor);
          }).then(function(spec) {
            editor.windowManager.open(spec);
          });
        };
        var appendClickRemove = function(link2, evt) {
          document.body.appendChild(link2);
          link2.dispatchEvent(evt);
          document.body.removeChild(link2);
        };
        var open = function(url) {
          var link2 = document.createElement("a");
          link2.target = "_blank";
          link2.href = url;
          link2.rel = "noreferrer noopener";
          var evt = document.createEvent("MouseEvents");
          evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
          appendClickRemove(link2, evt);
        };
        var getLink = function(editor, elm) {
          return editor.dom.getParent(elm, "a[href]");
        };
        var getSelectedLink = function(editor) {
          return getLink(editor, editor.selection.getStart());
        };
        var hasOnlyAltModifier = function(e2) {
          return e2.altKey === true && e2.shiftKey === false && e2.ctrlKey === false && e2.metaKey === false;
        };
        var gotoLink = function(editor, a2) {
          if (a2) {
            var href = getHref(a2);
            if (/^#/.test(href)) {
              var targetEl = editor.$(href);
              if (targetEl.length) {
                editor.selection.scrollIntoView(targetEl[0], true);
              }
            } else {
              open(a2.href);
            }
          }
        };
        var openDialog = function(editor) {
          return function() {
            open$1(editor);
          };
        };
        var gotoSelectedLink = function(editor) {
          return function() {
            gotoLink(editor, getSelectedLink(editor));
          };
        };
        var setupGotoLinks = function(editor) {
          editor.on("click", function(e2) {
            var link2 = getLink(editor, e2.target);
            if (link2 && global$6.metaKeyPressed(e2)) {
              e2.preventDefault();
              gotoLink(editor, link2);
            }
          });
          editor.on("keydown", function(e2) {
            var link2 = getSelectedLink(editor);
            if (link2 && e2.keyCode === 13 && hasOnlyAltModifier(e2)) {
              e2.preventDefault();
              gotoLink(editor, link2);
            }
          });
        };
        var toggleState = function(editor, toggler) {
          editor.on("NodeChange", toggler);
          return function() {
            return editor.off("NodeChange", toggler);
          };
        };
        var toggleActiveState = function(editor) {
          return function(api) {
            var updateState = function() {
              return api.setActive(!editor.mode.isReadOnly() && getAnchorElement(editor, editor.selection.getNode()) !== null);
            };
            updateState();
            return toggleState(editor, updateState);
          };
        };
        var toggleEnabledState = function(editor) {
          return function(api) {
            var updateState = function() {
              return api.setDisabled(getAnchorElement(editor, editor.selection.getNode()) === null);
            };
            updateState();
            return toggleState(editor, updateState);
          };
        };
        var toggleUnlinkState = function(editor) {
          return function(api) {
            var hasLinks$1 = function(parents2) {
              return hasLinks(parents2) || hasLinksInSelection(editor.selection.getRng());
            };
            var parents = editor.dom.getParents(editor.selection.getStart());
            api.setDisabled(!hasLinks$1(parents));
            return toggleState(editor, function(e2) {
              return api.setDisabled(!hasLinks$1(e2.parents));
            });
          };
        };
        var register = function(editor) {
          editor.addCommand("mceLink", function() {
            if (useQuickLink(editor)) {
              editor.fire("contexttoolbar-show", { toolbarKey: "quicklink" });
            } else {
              openDialog(editor)();
            }
          });
        };
        var setup = function(editor) {
          editor.addShortcut("Meta+K", "", function() {
            editor.execCommand("mceLink");
          });
        };
        var setupButtons = function(editor) {
          editor.ui.registry.addToggleButton("link", {
            icon: "link",
            tooltip: "Insert/edit link",
            onAction: openDialog(editor),
            onSetup: toggleActiveState(editor)
          });
          editor.ui.registry.addButton("openlink", {
            icon: "new-tab",
            tooltip: "Open link",
            onAction: gotoSelectedLink(editor),
            onSetup: toggleEnabledState(editor)
          });
          editor.ui.registry.addButton("unlink", {
            icon: "unlink",
            tooltip: "Remove link",
            onAction: function() {
              return unlink(editor);
            },
            onSetup: toggleUnlinkState(editor)
          });
        };
        var setupMenuItems = function(editor) {
          editor.ui.registry.addMenuItem("openlink", {
            text: "Open link",
            icon: "new-tab",
            onAction: gotoSelectedLink(editor),
            onSetup: toggleEnabledState(editor)
          });
          editor.ui.registry.addMenuItem("link", {
            icon: "link",
            text: "Link...",
            shortcut: "Meta+K",
            onAction: openDialog(editor)
          });
          editor.ui.registry.addMenuItem("unlink", {
            icon: "unlink",
            text: "Remove link",
            onAction: function() {
              return unlink(editor);
            },
            onSetup: toggleUnlinkState(editor)
          });
        };
        var setupContextMenu = function(editor) {
          var inLink = "link unlink openlink";
          var noLink = "link";
          editor.ui.registry.addContextMenu("link", {
            update: function(element) {
              return hasLinks(editor.dom.getParents(element, "a")) ? inLink : noLink;
            }
          });
        };
        var setupContextToolbars = function(editor) {
          var collapseSelectionToEnd = function(editor2) {
            editor2.selection.collapse(false);
          };
          var onSetupLink = function(buttonApi) {
            var node = editor.selection.getNode();
            buttonApi.setDisabled(!getAnchorElement(editor, node));
            return noop3;
          };
          var getLinkText = function(value) {
            var anchor = getAnchorElement(editor);
            var onlyText = isOnlyTextSelected(editor);
            if (!anchor && onlyText) {
              var text = getAnchorText(editor.selection, anchor);
              return Optional.some(text.length > 0 ? text : value);
            } else {
              return Optional.none();
            }
          };
          editor.ui.registry.addContextForm("quicklink", {
            launch: {
              type: "contextformtogglebutton",
              icon: "link",
              tooltip: "Link",
              onSetup: toggleActiveState(editor)
            },
            label: "Link",
            predicate: function(node) {
              return !!getAnchorElement(editor, node) && hasContextToolbar(editor);
            },
            initValue: function() {
              var elm = getAnchorElement(editor);
              return !!elm ? getHref(elm) : "";
            },
            commands: [
              {
                type: "contextformtogglebutton",
                icon: "link",
                tooltip: "Link",
                primary: true,
                onSetup: function(buttonApi) {
                  var node = editor.selection.getNode();
                  buttonApi.setActive(!!getAnchorElement(editor, node));
                  return toggleActiveState(editor)(buttonApi);
                },
                onAction: function(formApi) {
                  var value = formApi.getValue();
                  var text = getLinkText(value);
                  var attachState = {
                    href: value,
                    attach: noop3
                  };
                  link(editor, attachState, {
                    href: value,
                    text,
                    title: Optional.none(),
                    rel: Optional.none(),
                    target: Optional.none(),
                    class: Optional.none()
                  });
                  collapseSelectionToEnd(editor);
                  formApi.hide();
                }
              },
              {
                type: "contextformbutton",
                icon: "unlink",
                tooltip: "Remove link",
                onSetup: onSetupLink,
                onAction: function(formApi) {
                  unlink(editor);
                  formApi.hide();
                }
              },
              {
                type: "contextformbutton",
                icon: "new-tab",
                tooltip: "Open link",
                onSetup: onSetupLink,
                onAction: function(formApi) {
                  gotoSelectedLink(editor)();
                  formApi.hide();
                }
              }
            ]
          });
        };
        function Plugin() {
          global$7.add("link", function(editor) {
            setupButtons(editor);
            setupMenuItems(editor);
            setupContextMenu(editor);
            setupContextToolbars(editor);
            setupGotoLinks(editor);
            register(editor);
            setup(editor);
          });
        }
        Plugin();
      })();
    }
  });

  // ../../node_modules/tinymce/plugins/media/plugin.js
  var require_plugin15 = __commonJS({
    "../../node_modules/tinymce/plugins/media/plugin.js"() {
      (function() {
        "use strict";
        var global$9 = tinymce.util.Tools.resolve("tinymce.PluginManager");
        var __assign = function() {
          __assign = Object.assign || function __assign2(t2) {
            for (var s2, i2 = 1, n2 = arguments.length; i2 < n2; i2++) {
              s2 = arguments[i2];
              for (var p2 in s2)
                if (Object.prototype.hasOwnProperty.call(s2, p2))
                  t2[p2] = s2[p2];
            }
            return t2;
          };
          return __assign.apply(this, arguments);
        };
        var typeOf = function(x2) {
          var t2 = typeof x2;
          if (x2 === null) {
            return "null";
          } else if (t2 === "object" && (Array.prototype.isPrototypeOf(x2) || x2.constructor && x2.constructor.name === "Array")) {
            return "array";
          } else if (t2 === "object" && (String.prototype.isPrototypeOf(x2) || x2.constructor && x2.constructor.name === "String")) {
            return "string";
          } else {
            return t2;
          }
        };
        var isType = function(type) {
          return function(value) {
            return typeOf(value) === type;
          };
        };
        var isString = isType("string");
        var isObject2 = isType("object");
        var isArray2 = isType("array");
        var isNullable = function(a2) {
          return a2 === null || a2 === void 0;
        };
        var isNonNullable = function(a2) {
          return !isNullable(a2);
        };
        var noop3 = function() {
        };
        var constant = function(value) {
          return function() {
            return value;
          };
        };
        var identity = function(x2) {
          return x2;
        };
        var never = constant(false);
        var always = constant(true);
        var none = function() {
          return NONE;
        };
        var NONE = function() {
          var call = function(thunk) {
            return thunk();
          };
          var id2 = identity;
          var me2 = {
            fold: function(n2, _s) {
              return n2();
            },
            isSome: never,
            isNone: always,
            getOr: id2,
            getOrThunk: call,
            getOrDie: function(msg) {
              throw new Error(msg || "error: getOrDie called on none.");
            },
            getOrNull: constant(null),
            getOrUndefined: constant(void 0),
            or: id2,
            orThunk: call,
            map: none,
            each: noop3,
            bind: none,
            exists: never,
            forall: always,
            filter: function() {
              return none();
            },
            toArray: function() {
              return [];
            },
            toString: constant("none()")
          };
          return me2;
        }();
        var some = function(a2) {
          var constant_a = constant(a2);
          var self2 = function() {
            return me2;
          };
          var bind = function(f2) {
            return f2(a2);
          };
          var me2 = {
            fold: function(n2, s2) {
              return s2(a2);
            },
            isSome: always,
            isNone: never,
            getOr: constant_a,
            getOrThunk: constant_a,
            getOrDie: constant_a,
            getOrNull: constant_a,
            getOrUndefined: constant_a,
            or: self2,
            orThunk: self2,
            map: function(f2) {
              return some(f2(a2));
            },
            each: function(f2) {
              f2(a2);
            },
            bind,
            exists: bind,
            forall: bind,
            filter: function(f2) {
              return f2(a2) ? me2 : NONE;
            },
            toArray: function() {
              return [a2];
            },
            toString: function() {
              return "some(" + a2 + ")";
            }
          };
          return me2;
        };
        var from = function(value) {
          return value === null || value === void 0 ? NONE : some(value);
        };
        var Optional = {
          some,
          none,
          from
        };
        var nativePush = Array.prototype.push;
        var each$1 = function(xs, f2) {
          for (var i2 = 0, len = xs.length; i2 < len; i2++) {
            var x2 = xs[i2];
            f2(x2, i2);
          }
        };
        var flatten = function(xs) {
          var r2 = [];
          for (var i2 = 0, len = xs.length; i2 < len; ++i2) {
            if (!isArray2(xs[i2])) {
              throw new Error("Arr.flatten item " + i2 + " was not an array, input: " + xs);
            }
            nativePush.apply(r2, xs[i2]);
          }
          return r2;
        };
        var Cell = function(initial) {
          var value = initial;
          var get2 = function() {
            return value;
          };
          var set2 = function(v2) {
            value = v2;
          };
          return {
            get: get2,
            set: set2
          };
        };
        var keys = Object.keys;
        var hasOwnProperty = Object.hasOwnProperty;
        var each2 = function(obj, f2) {
          var props = keys(obj);
          for (var k2 = 0, len = props.length; k2 < len; k2++) {
            var i2 = props[k2];
            var x2 = obj[i2];
            f2(x2, i2);
          }
        };
        var get$1 = function(obj, key) {
          return has(obj, key) ? Optional.from(obj[key]) : Optional.none();
        };
        var has = function(obj, key) {
          return hasOwnProperty.call(obj, key);
        };
        var getScripts = function(editor) {
          return editor.getParam("media_scripts");
        };
        var getAudioTemplateCallback = function(editor) {
          return editor.getParam("audio_template_callback");
        };
        var getVideoTemplateCallback = function(editor) {
          return editor.getParam("video_template_callback");
        };
        var hasLiveEmbeds = function(editor) {
          return editor.getParam("media_live_embeds", true);
        };
        var shouldFilterHtml = function(editor) {
          return editor.getParam("media_filter_html", true);
        };
        var getUrlResolver = function(editor) {
          return editor.getParam("media_url_resolver");
        };
        var hasAltSource = function(editor) {
          return editor.getParam("media_alt_source", true);
        };
        var hasPoster = function(editor) {
          return editor.getParam("media_poster", true);
        };
        var hasDimensions = function(editor) {
          return editor.getParam("media_dimensions", true);
        };
        var global$8 = tinymce.util.Tools.resolve("tinymce.util.Tools");
        var global$7 = tinymce.util.Tools.resolve("tinymce.dom.DOMUtils");
        var global$6 = tinymce.util.Tools.resolve("tinymce.html.SaxParser");
        var getVideoScriptMatch = function(prefixes, src) {
          if (prefixes) {
            for (var i2 = 0; i2 < prefixes.length; i2++) {
              if (src.indexOf(prefixes[i2].filter) !== -1) {
                return prefixes[i2];
              }
            }
          }
        };
        var DOM$1 = global$7.DOM;
        var trimPx = function(value) {
          return value.replace(/px$/, "");
        };
        var getEphoxEmbedData = function(attrs) {
          var style = attrs.map.style;
          var styles = style ? DOM$1.parseStyle(style) : {};
          return {
            type: "ephox-embed-iri",
            source: attrs.map["data-ephox-embed-iri"],
            altsource: "",
            poster: "",
            width: get$1(styles, "max-width").map(trimPx).getOr(""),
            height: get$1(styles, "max-height").map(trimPx).getOr("")
          };
        };
        var htmlToData = function(prefixes, html) {
          var isEphoxEmbed = Cell(false);
          var data = {};
          global$6({
            validate: false,
            allow_conditional_comments: true,
            start: function(name, attrs) {
              if (isEphoxEmbed.get())
                ;
              else if (has(attrs.map, "data-ephox-embed-iri")) {
                isEphoxEmbed.set(true);
                data = getEphoxEmbedData(attrs);
              } else {
                if (!data.source && name === "param") {
                  data.source = attrs.map.movie;
                }
                if (name === "iframe" || name === "object" || name === "embed" || name === "video" || name === "audio") {
                  if (!data.type) {
                    data.type = name;
                  }
                  data = global$8.extend(attrs.map, data);
                }
                if (name === "script") {
                  var videoScript = getVideoScriptMatch(prefixes, attrs.map.src);
                  if (!videoScript) {
                    return;
                  }
                  data = {
                    type: "script",
                    source: attrs.map.src,
                    width: String(videoScript.width),
                    height: String(videoScript.height)
                  };
                }
                if (name === "source") {
                  if (!data.source) {
                    data.source = attrs.map.src;
                  } else if (!data.altsource) {
                    data.altsource = attrs.map.src;
                  }
                }
                if (name === "img" && !data.poster) {
                  data.poster = attrs.map.src;
                }
              }
            }
          }).parse(html);
          data.source = data.source || data.src || data.data;
          data.altsource = data.altsource || "";
          data.poster = data.poster || "";
          return data;
        };
        var guess = function(url) {
          var mimes = {
            mp3: "audio/mpeg",
            m4a: "audio/x-m4a",
            wav: "audio/wav",
            mp4: "video/mp4",
            webm: "video/webm",
            ogg: "video/ogg",
            swf: "application/x-shockwave-flash"
          };
          var fileEnd = url.toLowerCase().split(".").pop();
          var mime = mimes[fileEnd];
          return mime ? mime : "";
        };
        var global$5 = tinymce.util.Tools.resolve("tinymce.html.Schema");
        var global$4 = tinymce.util.Tools.resolve("tinymce.html.Writer");
        var DOM = global$7.DOM;
        var addPx = function(value) {
          return /^[0-9.]+$/.test(value) ? value + "px" : value;
        };
        var setAttributes = function(attrs, updatedAttrs) {
          each2(updatedAttrs, function(val, name) {
            var value = "" + val;
            if (attrs.map[name]) {
              var i2 = attrs.length;
              while (i2--) {
                var attr = attrs[i2];
                if (attr.name === name) {
                  if (value) {
                    attrs.map[name] = value;
                    attr.value = value;
                  } else {
                    delete attrs.map[name];
                    attrs.splice(i2, 1);
                  }
                }
              }
            } else if (value) {
              attrs.push({
                name,
                value
              });
              attrs.map[name] = value;
            }
          });
        };
        var updateEphoxEmbed = function(data, attrs) {
          var style = attrs.map.style;
          var styleMap = style ? DOM.parseStyle(style) : {};
          styleMap["max-width"] = addPx(data.width);
          styleMap["max-height"] = addPx(data.height);
          setAttributes(attrs, { style: DOM.serializeStyle(styleMap) });
        };
        var sources = [
          "source",
          "altsource"
        ];
        var updateHtml = function(html, data, updateAll) {
          var writer = global$4();
          var isEphoxEmbed = Cell(false);
          var sourceCount = 0;
          var hasImage;
          global$6({
            validate: false,
            allow_conditional_comments: true,
            comment: function(text) {
              writer.comment(text);
            },
            cdata: function(text) {
              writer.cdata(text);
            },
            text: function(text, raw) {
              writer.text(text, raw);
            },
            start: function(name, attrs, empty) {
              if (isEphoxEmbed.get())
                ;
              else if (has(attrs.map, "data-ephox-embed-iri")) {
                isEphoxEmbed.set(true);
                updateEphoxEmbed(data, attrs);
              } else {
                switch (name) {
                  case "video":
                  case "object":
                  case "embed":
                  case "img":
                  case "iframe":
                    if (data.height !== void 0 && data.width !== void 0) {
                      setAttributes(attrs, {
                        width: data.width,
                        height: data.height
                      });
                    }
                    break;
                }
                if (updateAll) {
                  switch (name) {
                    case "video":
                      setAttributes(attrs, {
                        poster: data.poster,
                        src: ""
                      });
                      if (data.altsource) {
                        setAttributes(attrs, { src: "" });
                      }
                      break;
                    case "iframe":
                      setAttributes(attrs, { src: data.source });
                      break;
                    case "source":
                      if (sourceCount < 2) {
                        setAttributes(attrs, {
                          src: data[sources[sourceCount]],
                          type: data[sources[sourceCount] + "mime"]
                        });
                        if (!data[sources[sourceCount]]) {
                          return;
                        }
                      }
                      sourceCount++;
                      break;
                    case "img":
                      if (!data.poster) {
                        return;
                      }
                      hasImage = true;
                      break;
                  }
                }
              }
              writer.start(name, attrs, empty);
            },
            end: function(name) {
              if (!isEphoxEmbed.get()) {
                if (name === "video" && updateAll) {
                  for (var index = 0; index < 2; index++) {
                    if (data[sources[index]]) {
                      var attrs = [];
                      attrs.map = {};
                      if (sourceCount <= index) {
                        setAttributes(attrs, {
                          src: data[sources[index]],
                          type: data[sources[index] + "mime"]
                        });
                        writer.start("source", attrs, true);
                      }
                    }
                  }
                }
                if (data.poster && name === "object" && updateAll && !hasImage) {
                  var imgAttrs = [];
                  imgAttrs.map = {};
                  setAttributes(imgAttrs, {
                    src: data.poster,
                    width: data.width,
                    height: data.height
                  });
                  writer.start("img", imgAttrs, true);
                }
              }
              writer.end(name);
            }
          }, global$5({})).parse(html);
          return writer.getContent();
        };
        var urlPatterns = [
          {
            regex: /youtu\.be\/([\w\-_\?&=.]+)/i,
            type: "iframe",
            w: 560,
            h: 314,
            url: "www.youtube.com/embed/$1",
            allowFullscreen: true
          },
          {
            regex: /youtube\.com(.+)v=([^&]+)(&([a-z0-9&=\-_]+))?/i,
            type: "iframe",
            w: 560,
            h: 314,
            url: "www.youtube.com/embed/$2?$4",
            allowFullscreen: true
          },
          {
            regex: /youtube.com\/embed\/([a-z0-9\?&=\-_]+)/i,
            type: "iframe",
            w: 560,
            h: 314,
            url: "www.youtube.com/embed/$1",
            allowFullscreen: true
          },
          {
            regex: /vimeo\.com\/([0-9]+)/,
            type: "iframe",
            w: 425,
            h: 350,
            url: "player.vimeo.com/video/$1?title=0&byline=0&portrait=0&color=8dc7dc",
            allowFullscreen: true
          },
          {
            regex: /vimeo\.com\/(.*)\/([0-9]+)/,
            type: "iframe",
            w: 425,
            h: 350,
            url: "player.vimeo.com/video/$2?title=0&amp;byline=0",
            allowFullscreen: true
          },
          {
            regex: /maps\.google\.([a-z]{2,3})\/maps\/(.+)msid=(.+)/,
            type: "iframe",
            w: 425,
            h: 350,
            url: 'maps.google.com/maps/ms?msid=$2&output=embed"',
            allowFullscreen: false
          },
          {
            regex: /dailymotion\.com\/video\/([^_]+)/,
            type: "iframe",
            w: 480,
            h: 270,
            url: "www.dailymotion.com/embed/video/$1",
            allowFullscreen: true
          },
          {
            regex: /dai\.ly\/([^_]+)/,
            type: "iframe",
            w: 480,
            h: 270,
            url: "www.dailymotion.com/embed/video/$1",
            allowFullscreen: true
          }
        ];
        var getProtocol = function(url) {
          var protocolMatches = url.match(/^(https?:\/\/|www\.)(.+)$/i);
          if (protocolMatches && protocolMatches.length > 1) {
            return protocolMatches[1] === "www." ? "https://" : protocolMatches[1];
          } else {
            return "https://";
          }
        };
        var getUrl = function(pattern, url) {
          var protocol = getProtocol(url);
          var match2 = pattern.regex.exec(url);
          var newUrl = protocol + pattern.url;
          var _loop_1 = function(i3) {
            newUrl = newUrl.replace("$" + i3, function() {
              return match2[i3] ? match2[i3] : "";
            });
          };
          for (var i2 = 0; i2 < match2.length; i2++) {
            _loop_1(i2);
          }
          return newUrl.replace(/\?$/, "");
        };
        var matchPattern = function(url) {
          var patterns2 = urlPatterns.filter(function(pattern) {
            return pattern.regex.test(url);
          });
          if (patterns2.length > 0) {
            return global$8.extend({}, patterns2[0], { url: getUrl(patterns2[0], url) });
          } else {
            return null;
          }
        };
        var getIframeHtml = function(data) {
          var allowFullscreen = data.allowfullscreen ? ' allowFullscreen="1"' : "";
          return '<iframe src="' + data.source + '" width="' + data.width + '" height="' + data.height + '"' + allowFullscreen + "></iframe>";
        };
        var getFlashHtml = function(data) {
          var html = '<object data="' + data.source + '" width="' + data.width + '" height="' + data.height + '" type="application/x-shockwave-flash">';
          if (data.poster) {
            html += '<img src="' + data.poster + '" width="' + data.width + '" height="' + data.height + '" />';
          }
          html += "</object>";
          return html;
        };
        var getAudioHtml = function(data, audioTemplateCallback) {
          if (audioTemplateCallback) {
            return audioTemplateCallback(data);
          } else {
            return '<audio controls="controls" src="' + data.source + '">' + (data.altsource ? '\n<source src="' + data.altsource + '"' + (data.altsourcemime ? ' type="' + data.altsourcemime + '"' : "") + " />\n" : "") + "</audio>";
          }
        };
        var getVideoHtml = function(data, videoTemplateCallback) {
          if (videoTemplateCallback) {
            return videoTemplateCallback(data);
          } else {
            return '<video width="' + data.width + '" height="' + data.height + '"' + (data.poster ? ' poster="' + data.poster + '"' : "") + ' controls="controls">\n<source src="' + data.source + '"' + (data.sourcemime ? ' type="' + data.sourcemime + '"' : "") + " />\n" + (data.altsource ? '<source src="' + data.altsource + '"' + (data.altsourcemime ? ' type="' + data.altsourcemime + '"' : "") + " />\n" : "") + "</video>";
          }
        };
        var getScriptHtml = function(data) {
          return '<script src="' + data.source + '"><\/script>';
        };
        var dataToHtml = function(editor, dataIn) {
          var data = global$8.extend({}, dataIn);
          if (!data.source) {
            global$8.extend(data, htmlToData(getScripts(editor), data.embed));
            if (!data.source) {
              return "";
            }
          }
          if (!data.altsource) {
            data.altsource = "";
          }
          if (!data.poster) {
            data.poster = "";
          }
          data.source = editor.convertURL(data.source, "source");
          data.altsource = editor.convertURL(data.altsource, "source");
          data.sourcemime = guess(data.source);
          data.altsourcemime = guess(data.altsource);
          data.poster = editor.convertURL(data.poster, "poster");
          var pattern = matchPattern(data.source);
          if (pattern) {
            data.source = pattern.url;
            data.type = pattern.type;
            data.allowfullscreen = pattern.allowFullscreen;
            data.width = data.width || String(pattern.w);
            data.height = data.height || String(pattern.h);
          }
          if (data.embed) {
            return updateHtml(data.embed, data, true);
          } else {
            var videoScript = getVideoScriptMatch(getScripts(editor), data.source);
            if (videoScript) {
              data.type = "script";
              data.width = String(videoScript.width);
              data.height = String(videoScript.height);
            }
            var audioTemplateCallback = getAudioTemplateCallback(editor);
            var videoTemplateCallback = getVideoTemplateCallback(editor);
            data.width = data.width || "300";
            data.height = data.height || "150";
            global$8.each(data, function(value, key) {
              data[key] = editor.dom.encode("" + value);
            });
            if (data.type === "iframe") {
              return getIframeHtml(data);
            } else if (data.sourcemime === "application/x-shockwave-flash") {
              return getFlashHtml(data);
            } else if (data.sourcemime.indexOf("audio") !== -1) {
              return getAudioHtml(data, audioTemplateCallback);
            } else if (data.type === "script") {
              return getScriptHtml(data);
            } else {
              return getVideoHtml(data, videoTemplateCallback);
            }
          }
        };
        var isMediaElement = function(element) {
          return element.hasAttribute("data-mce-object") || element.hasAttribute("data-ephox-embed-iri");
        };
        var setup$2 = function(editor) {
          editor.on("click keyup touchend", function() {
            var selectedNode = editor.selection.getNode();
            if (selectedNode && editor.dom.hasClass(selectedNode, "mce-preview-object")) {
              if (editor.dom.getAttrib(selectedNode, "data-mce-selected")) {
                selectedNode.setAttribute("data-mce-selected", "2");
              }
            }
          });
          editor.on("ObjectSelected", function(e2) {
            var objectType = e2.target.getAttribute("data-mce-object");
            if (objectType === "script") {
              e2.preventDefault();
            }
          });
          editor.on("ObjectResized", function(e2) {
            var target = e2.target;
            if (target.getAttribute("data-mce-object")) {
              var html = target.getAttribute("data-mce-html");
              if (html) {
                html = unescape(html);
                target.setAttribute("data-mce-html", escape(updateHtml(html, {
                  width: String(e2.width),
                  height: String(e2.height)
                })));
              }
            }
          });
        };
        var global$3 = tinymce.util.Tools.resolve("tinymce.util.Promise");
        var cache2 = {};
        var embedPromise = function(data, dataToHtml2, handler) {
          return new global$3(function(res, rej) {
            var wrappedResolve = function(response) {
              if (response.html) {
                cache2[data.source] = response;
              }
              return res({
                url: data.source,
                html: response.html ? response.html : dataToHtml2(data)
              });
            };
            if (cache2[data.source]) {
              wrappedResolve(cache2[data.source]);
            } else {
              handler({ url: data.source }, wrappedResolve, rej);
            }
          });
        };
        var defaultPromise = function(data, dataToHtml2) {
          return global$3.resolve({
            html: dataToHtml2(data),
            url: data.source
          });
        };
        var loadedData = function(editor) {
          return function(data) {
            return dataToHtml(editor, data);
          };
        };
        var getEmbedHtml = function(editor, data) {
          var embedHandler = getUrlResolver(editor);
          return embedHandler ? embedPromise(data, loadedData(editor), embedHandler) : defaultPromise(data, loadedData(editor));
        };
        var isCached = function(url) {
          return has(cache2, url);
        };
        var extractMeta = function(sourceInput, data) {
          return get$1(data, sourceInput).bind(function(mainData) {
            return get$1(mainData, "meta");
          });
        };
        var getValue = function(data, metaData, sourceInput) {
          return function(prop) {
            var _a;
            var getFromData = function() {
              return get$1(data, prop);
            };
            var getFromMetaData = function() {
              return get$1(metaData, prop);
            };
            var getNonEmptyValue = function(c2) {
              return get$1(c2, "value").bind(function(v2) {
                return v2.length > 0 ? Optional.some(v2) : Optional.none();
              });
            };
            var getFromValueFirst = function() {
              return getFromData().bind(function(child) {
                return isObject2(child) ? getNonEmptyValue(child).orThunk(getFromMetaData) : getFromMetaData().orThunk(function() {
                  return Optional.from(child);
                });
              });
            };
            var getFromMetaFirst = function() {
              return getFromMetaData().orThunk(function() {
                return getFromData().bind(function(child) {
                  return isObject2(child) ? getNonEmptyValue(child) : Optional.from(child);
                });
              });
            };
            return _a = {}, _a[prop] = (prop === sourceInput ? getFromValueFirst() : getFromMetaFirst()).getOr(""), _a;
          };
        };
        var getDimensions = function(data, metaData) {
          var dimensions = {};
          get$1(data, "dimensions").each(function(dims) {
            each$1([
              "width",
              "height"
            ], function(prop) {
              get$1(metaData, prop).orThunk(function() {
                return get$1(dims, prop);
              }).each(function(value) {
                return dimensions[prop] = value;
              });
            });
          });
          return dimensions;
        };
        var unwrap = function(data, sourceInput) {
          var metaData = sourceInput ? extractMeta(sourceInput, data).getOr({}) : {};
          var get2 = getValue(data, metaData, sourceInput);
          return __assign(__assign(__assign(__assign(__assign({}, get2("source")), get2("altsource")), get2("poster")), get2("embed")), getDimensions(data, metaData));
        };
        var wrap = function(data) {
          var wrapped = __assign(__assign({}, data), {
            source: { value: get$1(data, "source").getOr("") },
            altsource: { value: get$1(data, "altsource").getOr("") },
            poster: { value: get$1(data, "poster").getOr("") }
          });
          each$1([
            "width",
            "height"
          ], function(prop) {
            get$1(data, prop).each(function(value) {
              var dimensions = wrapped.dimensions || {};
              dimensions[prop] = value;
              wrapped.dimensions = dimensions;
            });
          });
          return wrapped;
        };
        var handleError = function(editor) {
          return function(error3) {
            var errorMessage = error3 && error3.msg ? "Media embed handler error: " + error3.msg : "Media embed handler threw unknown error.";
            editor.notificationManager.open({
              type: "error",
              text: errorMessage
            });
          };
        };
        var snippetToData = function(editor, embedSnippet) {
          return htmlToData(getScripts(editor), embedSnippet);
        };
        var getEditorData = function(editor) {
          var element = editor.selection.getNode();
          var snippet = isMediaElement(element) ? editor.serializer.serialize(element, { selection: true }) : "";
          return __assign({ embed: snippet }, htmlToData(getScripts(editor), snippet));
        };
        var addEmbedHtml = function(api, editor) {
          return function(response) {
            if (isString(response.url) && response.url.trim().length > 0) {
              var html = response.html;
              var snippetData = snippetToData(editor, html);
              var nuData = __assign(__assign({}, snippetData), {
                source: response.url,
                embed: html
              });
              api.setData(wrap(nuData));
            }
          };
        };
        var selectPlaceholder = function(editor, beforeObjects) {
          var afterObjects = editor.dom.select("*[data-mce-object]");
          for (var i2 = 0; i2 < beforeObjects.length; i2++) {
            for (var y2 = afterObjects.length - 1; y2 >= 0; y2--) {
              if (beforeObjects[i2] === afterObjects[y2]) {
                afterObjects.splice(y2, 1);
              }
            }
          }
          editor.selection.select(afterObjects[0]);
        };
        var handleInsert = function(editor, html) {
          var beforeObjects = editor.dom.select("*[data-mce-object]");
          editor.insertContent(html);
          selectPlaceholder(editor, beforeObjects);
          editor.nodeChanged();
        };
        var submitForm2 = function(prevData, newData, editor) {
          newData.embed = updateHtml(newData.embed, newData);
          if (newData.embed && (prevData.source === newData.source || isCached(newData.source))) {
            handleInsert(editor, newData.embed);
          } else {
            getEmbedHtml(editor, newData).then(function(response) {
              handleInsert(editor, response.html);
            }).catch(handleError(editor));
          }
        };
        var showDialog = function(editor) {
          var editorData = getEditorData(editor);
          var currentData = Cell(editorData);
          var initialData = wrap(editorData);
          var handleSource = function(prevData, api) {
            var serviceData = unwrap(api.getData(), "source");
            if (prevData.source !== serviceData.source) {
              addEmbedHtml(win, editor)({
                url: serviceData.source,
                html: ""
              });
              getEmbedHtml(editor, serviceData).then(addEmbedHtml(win, editor)).catch(handleError(editor));
            }
          };
          var handleEmbed = function(api) {
            var data = unwrap(api.getData());
            var dataFromEmbed = snippetToData(editor, data.embed);
            api.setData(wrap(dataFromEmbed));
          };
          var handleUpdate = function(api, sourceInput) {
            var data = unwrap(api.getData(), sourceInput);
            var embed = dataToHtml(editor, data);
            api.setData(wrap(__assign(__assign({}, data), { embed })));
          };
          var mediaInput = [{
            name: "source",
            type: "urlinput",
            filetype: "media",
            label: "Source"
          }];
          var sizeInput = !hasDimensions(editor) ? [] : [{
            type: "sizeinput",
            name: "dimensions",
            label: "Constrain proportions",
            constrain: true
          }];
          var generalTab = {
            title: "General",
            name: "general",
            items: flatten([
              mediaInput,
              sizeInput
            ])
          };
          var embedTextarea = {
            type: "textarea",
            name: "embed",
            label: "Paste your embed code below:"
          };
          var embedTab = {
            title: "Embed",
            items: [embedTextarea]
          };
          var advancedFormItems = [];
          if (hasAltSource(editor)) {
            advancedFormItems.push({
              name: "altsource",
              type: "urlinput",
              filetype: "media",
              label: "Alternative source URL"
            });
          }
          if (hasPoster(editor)) {
            advancedFormItems.push({
              name: "poster",
              type: "urlinput",
              filetype: "image",
              label: "Media poster (Image URL)"
            });
          }
          var advancedTab = {
            title: "Advanced",
            name: "advanced",
            items: advancedFormItems
          };
          var tabs = [
            generalTab,
            embedTab
          ];
          if (advancedFormItems.length > 0) {
            tabs.push(advancedTab);
          }
          var body = {
            type: "tabpanel",
            tabs
          };
          var win = editor.windowManager.open({
            title: "Insert/Edit Media",
            size: "normal",
            body,
            buttons: [
              {
                type: "cancel",
                name: "cancel",
                text: "Cancel"
              },
              {
                type: "submit",
                name: "save",
                text: "Save",
                primary: true
              }
            ],
            onSubmit: function(api) {
              var serviceData = unwrap(api.getData());
              submitForm2(currentData.get(), serviceData, editor);
              api.close();
            },
            onChange: function(api, detail) {
              switch (detail.name) {
                case "source":
                  handleSource(currentData.get(), api);
                  break;
                case "embed":
                  handleEmbed(api);
                  break;
                case "dimensions":
                case "altsource":
                case "poster":
                  handleUpdate(api, detail.name);
                  break;
              }
              currentData.set(unwrap(api.getData()));
            },
            initialData
          });
        };
        var get = function(editor) {
          var showDialog$1 = function() {
            showDialog(editor);
          };
          return { showDialog: showDialog$1 };
        };
        var register$1 = function(editor) {
          var showDialog$1 = function() {
            showDialog(editor);
          };
          editor.addCommand("mceMedia", showDialog$1);
        };
        var global$2 = tinymce.util.Tools.resolve("tinymce.html.Node");
        var global$1 = tinymce.util.Tools.resolve("tinymce.Env");
        var global2 = tinymce.util.Tools.resolve("tinymce.html.DomParser");
        var sanitize = function(editor, html) {
          if (shouldFilterHtml(editor) === false) {
            return html;
          }
          var writer = global$4();
          var blocked;
          global$6({
            validate: false,
            allow_conditional_comments: false,
            comment: function(text) {
              if (!blocked) {
                writer.comment(text);
              }
            },
            cdata: function(text) {
              if (!blocked) {
                writer.cdata(text);
              }
            },
            text: function(text, raw) {
              if (!blocked) {
                writer.text(text, raw);
              }
            },
            start: function(name, attrs, empty) {
              blocked = true;
              if (name === "script" || name === "noscript" || name === "svg") {
                return;
              }
              for (var i2 = attrs.length - 1; i2 >= 0; i2--) {
                var attrName = attrs[i2].name;
                if (attrName.indexOf("on") === 0) {
                  delete attrs.map[attrName];
                  attrs.splice(i2, 1);
                }
                if (attrName === "style") {
                  attrs[i2].value = editor.dom.serializeStyle(editor.dom.parseStyle(attrs[i2].value), name);
                }
              }
              writer.start(name, attrs, empty);
              blocked = false;
            },
            end: function(name) {
              if (blocked) {
                return;
              }
              writer.end(name);
            }
          }, global$5({})).parse(html);
          return writer.getContent();
        };
        var isLiveEmbedNode = function(node) {
          var name = node.name;
          return name === "iframe" || name === "video" || name === "audio";
        };
        var getDimension = function(node, styles, dimension, defaultValue) {
          if (defaultValue === void 0) {
            defaultValue = null;
          }
          var value = node.attr(dimension);
          if (isNonNullable(value)) {
            return value;
          } else if (!has(styles, dimension)) {
            return defaultValue;
          } else {
            return null;
          }
        };
        var setDimensions = function(node, previewNode, styles) {
          var useDefaults = previewNode.name === "img" || node.name === "video";
          var defaultWidth = useDefaults ? "300" : null;
          var fallbackHeight = node.name === "audio" ? "30" : "150";
          var defaultHeight = useDefaults ? fallbackHeight : null;
          previewNode.attr({
            width: getDimension(node, styles, "width", defaultWidth),
            height: getDimension(node, styles, "height", defaultHeight)
          });
        };
        var appendNodeContent = function(editor, nodeName, previewNode, html) {
          var newNode = global2({
            forced_root_block: false,
            validate: false
          }, editor.schema).parse(html, { context: nodeName });
          while (newNode.firstChild) {
            previewNode.append(newNode.firstChild);
          }
        };
        var createPlaceholderNode = function(editor, node) {
          var name = node.name;
          var placeHolder = new global$2("img", 1);
          placeHolder.shortEnded = true;
          retainAttributesAndInnerHtml(editor, node, placeHolder);
          setDimensions(node, placeHolder, {});
          placeHolder.attr({
            "style": node.attr("style"),
            "src": global$1.transparentSrc,
            "data-mce-object": name,
            "class": "mce-object mce-object-" + name
          });
          return placeHolder;
        };
        var createPreviewNode = function(editor, node) {
          var name = node.name;
          var previewWrapper = new global$2("span", 1);
          previewWrapper.attr({
            "contentEditable": "false",
            "style": node.attr("style"),
            "data-mce-object": name,
            "class": "mce-preview-object mce-object-" + name
          });
          retainAttributesAndInnerHtml(editor, node, previewWrapper);
          var styles = editor.dom.parseStyle(node.attr("style"));
          var previewNode = new global$2(name, 1);
          setDimensions(node, previewNode, styles);
          previewNode.attr({
            src: node.attr("src"),
            style: node.attr("style"),
            class: node.attr("class")
          });
          if (name === "iframe") {
            previewNode.attr({
              allowfullscreen: node.attr("allowfullscreen"),
              frameborder: "0"
            });
          } else {
            var attrs = [
              "controls",
              "crossorigin",
              "currentTime",
              "loop",
              "muted",
              "poster",
              "preload"
            ];
            each$1(attrs, function(attrName) {
              previewNode.attr(attrName, node.attr(attrName));
            });
            var sanitizedHtml = previewWrapper.attr("data-mce-html");
            if (isNonNullable(sanitizedHtml)) {
              appendNodeContent(editor, name, previewNode, unescape(sanitizedHtml));
            }
          }
          var shimNode = new global$2("span", 1);
          shimNode.attr("class", "mce-shim");
          previewWrapper.append(previewNode);
          previewWrapper.append(shimNode);
          return previewWrapper;
        };
        var retainAttributesAndInnerHtml = function(editor, sourceNode, targetNode) {
          var attribs = sourceNode.attributes;
          var ai2 = attribs.length;
          while (ai2--) {
            var attrName = attribs[ai2].name;
            var attrValue = attribs[ai2].value;
            if (attrName !== "width" && attrName !== "height" && attrName !== "style") {
              if (attrName === "data" || attrName === "src") {
                attrValue = editor.convertURL(attrValue, attrName);
              }
              targetNode.attr("data-mce-p-" + attrName, attrValue);
            }
          }
          var innerHtml = sourceNode.firstChild && sourceNode.firstChild.value;
          if (innerHtml) {
            targetNode.attr("data-mce-html", escape(sanitize(editor, innerHtml)));
            targetNode.firstChild = null;
          }
        };
        var isPageEmbedWrapper = function(node) {
          var nodeClass = node.attr("class");
          return nodeClass && /\btiny-pageembed\b/.test(nodeClass);
        };
        var isWithinEmbedWrapper = function(node) {
          while (node = node.parent) {
            if (node.attr("data-ephox-embed-iri") || isPageEmbedWrapper(node)) {
              return true;
            }
          }
          return false;
        };
        var placeHolderConverter = function(editor) {
          return function(nodes) {
            var i2 = nodes.length;
            var node;
            var videoScript;
            while (i2--) {
              node = nodes[i2];
              if (!node.parent) {
                continue;
              }
              if (node.parent.attr("data-mce-object")) {
                continue;
              }
              if (node.name === "script") {
                videoScript = getVideoScriptMatch(getScripts(editor), node.attr("src"));
                if (!videoScript) {
                  continue;
                }
              }
              if (videoScript) {
                if (videoScript.width) {
                  node.attr("width", videoScript.width.toString());
                }
                if (videoScript.height) {
                  node.attr("height", videoScript.height.toString());
                }
              }
              if (isLiveEmbedNode(node) && hasLiveEmbeds(editor) && global$1.ceFalse) {
                if (!isWithinEmbedWrapper(node)) {
                  node.replace(createPreviewNode(editor, node));
                }
              } else {
                if (!isWithinEmbedWrapper(node)) {
                  node.replace(createPlaceholderNode(editor, node));
                }
              }
            }
          };
        };
        var setup$1 = function(editor) {
          editor.on("preInit", function() {
            var specialElements = editor.schema.getSpecialElements();
            global$8.each("video audio iframe object".split(" "), function(name) {
              specialElements[name] = new RegExp("</" + name + "[^>]*>", "gi");
            });
            var boolAttrs = editor.schema.getBoolAttrs();
            global$8.each("webkitallowfullscreen mozallowfullscreen allowfullscreen".split(" "), function(name) {
              boolAttrs[name] = {};
            });
            editor.parser.addNodeFilter("iframe,video,audio,object,embed,script", placeHolderConverter(editor));
            editor.serializer.addAttributeFilter("data-mce-object", function(nodes, name) {
              var i2 = nodes.length;
              var node;
              var realElm;
              var ai2;
              var attribs;
              var innerHtml;
              var innerNode;
              var realElmName;
              var className;
              while (i2--) {
                node = nodes[i2];
                if (!node.parent) {
                  continue;
                }
                realElmName = node.attr(name);
                realElm = new global$2(realElmName, 1);
                if (realElmName !== "audio" && realElmName !== "script") {
                  className = node.attr("class");
                  if (className && className.indexOf("mce-preview-object") !== -1) {
                    realElm.attr({
                      width: node.firstChild.attr("width"),
                      height: node.firstChild.attr("height")
                    });
                  } else {
                    realElm.attr({
                      width: node.attr("width"),
                      height: node.attr("height")
                    });
                  }
                }
                realElm.attr({ style: node.attr("style") });
                attribs = node.attributes;
                ai2 = attribs.length;
                while (ai2--) {
                  var attrName = attribs[ai2].name;
                  if (attrName.indexOf("data-mce-p-") === 0) {
                    realElm.attr(attrName.substr(11), attribs[ai2].value);
                  }
                }
                if (realElmName === "script") {
                  realElm.attr("type", "text/javascript");
                }
                innerHtml = node.attr("data-mce-html");
                if (innerHtml) {
                  innerNode = new global$2("#text", 3);
                  innerNode.raw = true;
                  innerNode.value = sanitize(editor, unescape(innerHtml));
                  realElm.append(innerNode);
                }
                node.replace(realElm);
              }
            });
          });
          editor.on("SetContent", function() {
            editor.$("span.mce-preview-object").each(function(index, elm) {
              var $elm = editor.$(elm);
              if ($elm.find("span.mce-shim").length === 0) {
                $elm.append('<span class="mce-shim"></span>');
              }
            });
          });
        };
        var setup = function(editor) {
          editor.on("ResolveName", function(e2) {
            var name;
            if (e2.target.nodeType === 1 && (name = e2.target.getAttribute("data-mce-object"))) {
              e2.name = name;
            }
          });
        };
        var register = function(editor) {
          var onAction = function() {
            return editor.execCommand("mceMedia");
          };
          editor.ui.registry.addToggleButton("media", {
            tooltip: "Insert/edit media",
            icon: "embed",
            onAction,
            onSetup: function(buttonApi) {
              var selection = editor.selection;
              buttonApi.setActive(isMediaElement(selection.getNode()));
              return selection.selectorChangedWithUnbind("img[data-mce-object],span[data-mce-object],div[data-ephox-embed-iri]", buttonApi.setActive).unbind;
            }
          });
          editor.ui.registry.addMenuItem("media", {
            icon: "embed",
            text: "Media...",
            onAction
          });
        };
        function Plugin() {
          global$9.add("media", function(editor) {
            register$1(editor);
            register(editor);
            setup(editor);
            setup$1(editor);
            setup$2(editor);
            return get(editor);
          });
        }
        Plugin();
      })();
    }
  });

  // ../../node_modules/tinymce/plugins/table/plugin.js
  var require_plugin16 = __commonJS({
    "../../node_modules/tinymce/plugins/table/plugin.js"() {
      (function() {
        "use strict";
        var typeOf = function(x2) {
          var t2 = typeof x2;
          if (x2 === null) {
            return "null";
          } else if (t2 === "object" && (Array.prototype.isPrototypeOf(x2) || x2.constructor && x2.constructor.name === "Array")) {
            return "array";
          } else if (t2 === "object" && (String.prototype.isPrototypeOf(x2) || x2.constructor && x2.constructor.name === "String")) {
            return "string";
          } else {
            return t2;
          }
        };
        var isType$1 = function(type2) {
          return function(value2) {
            return typeOf(value2) === type2;
          };
        };
        var isSimpleType = function(type2) {
          return function(value2) {
            return typeof value2 === type2;
          };
        };
        var eq$2 = function(t2) {
          return function(a2) {
            return t2 === a2;
          };
        };
        var isString = isType$1("string");
        var isObject2 = isType$1("object");
        var isArray2 = isType$1("array");
        var isNull = eq$2(null);
        var isBoolean = isSimpleType("boolean");
        var isUndefined = eq$2(void 0);
        var isNullable = function(a2) {
          return a2 === null || a2 === void 0;
        };
        var isNonNullable = function(a2) {
          return !isNullable(a2);
        };
        var isFunction2 = isSimpleType("function");
        var isNumber2 = isSimpleType("number");
        var noop3 = function() {
        };
        var compose = function(fa, fb) {
          return function() {
            var args = [];
            for (var _i2 = 0; _i2 < arguments.length; _i2++) {
              args[_i2] = arguments[_i2];
            }
            return fa(fb.apply(null, args));
          };
        };
        var compose1 = function(fbc, fab) {
          return function(a2) {
            return fbc(fab(a2));
          };
        };
        var constant = function(value2) {
          return function() {
            return value2;
          };
        };
        var identity = function(x2) {
          return x2;
        };
        var tripleEquals = function(a2, b2) {
          return a2 === b2;
        };
        function curry(fn3) {
          var initialArgs = [];
          for (var _i2 = 1; _i2 < arguments.length; _i2++) {
            initialArgs[_i2 - 1] = arguments[_i2];
          }
          return function() {
            var restArgs = [];
            for (var _i3 = 0; _i3 < arguments.length; _i3++) {
              restArgs[_i3] = arguments[_i3];
            }
            var all2 = initialArgs.concat(restArgs);
            return fn3.apply(null, all2);
          };
        }
        var not = function(f2) {
          return function(t2) {
            return !f2(t2);
          };
        };
        var die = function(msg) {
          return function() {
            throw new Error(msg);
          };
        };
        var never = constant(false);
        var always = constant(true);
        var none$2 = function() {
          return NONE;
        };
        var NONE = function() {
          var call = function(thunk) {
            return thunk();
          };
          var id2 = identity;
          var me2 = {
            fold: function(n2, _s) {
              return n2();
            },
            isSome: never,
            isNone: always,
            getOr: id2,
            getOrThunk: call,
            getOrDie: function(msg) {
              throw new Error(msg || "error: getOrDie called on none.");
            },
            getOrNull: constant(null),
            getOrUndefined: constant(void 0),
            or: id2,
            orThunk: call,
            map: none$2,
            each: noop3,
            bind: none$2,
            exists: never,
            forall: always,
            filter: function() {
              return none$2();
            },
            toArray: function() {
              return [];
            },
            toString: constant("none()")
          };
          return me2;
        }();
        var some = function(a2) {
          var constant_a = constant(a2);
          var self2 = function() {
            return me2;
          };
          var bind2 = function(f2) {
            return f2(a2);
          };
          var me2 = {
            fold: function(n2, s2) {
              return s2(a2);
            },
            isSome: always,
            isNone: never,
            getOr: constant_a,
            getOrThunk: constant_a,
            getOrDie: constant_a,
            getOrNull: constant_a,
            getOrUndefined: constant_a,
            or: self2,
            orThunk: self2,
            map: function(f2) {
              return some(f2(a2));
            },
            each: function(f2) {
              f2(a2);
            },
            bind: bind2,
            exists: bind2,
            forall: bind2,
            filter: function(f2) {
              return f2(a2) ? me2 : NONE;
            },
            toArray: function() {
              return [a2];
            },
            toString: function() {
              return "some(" + a2 + ")";
            }
          };
          return me2;
        };
        var from$1 = function(value2) {
          return value2 === null || value2 === void 0 ? NONE : some(value2);
        };
        var Optional = {
          some,
          none: none$2,
          from: from$1
        };
        var nativeSlice = Array.prototype.slice;
        var nativeIndexOf = Array.prototype.indexOf;
        var nativePush = Array.prototype.push;
        var rawIndexOf = function(ts, t2) {
          return nativeIndexOf.call(ts, t2);
        };
        var contains$2 = function(xs, x2) {
          return rawIndexOf(xs, x2) > -1;
        };
        var exists = function(xs, pred) {
          for (var i2 = 0, len = xs.length; i2 < len; i2++) {
            var x2 = xs[i2];
            if (pred(x2, i2)) {
              return true;
            }
          }
          return false;
        };
        var range$1 = function(num, f2) {
          var r3 = [];
          for (var i2 = 0; i2 < num; i2++) {
            r3.push(f2(i2));
          }
          return r3;
        };
        var map$12 = function(xs, f2) {
          var len = xs.length;
          var r3 = new Array(len);
          for (var i2 = 0; i2 < len; i2++) {
            var x2 = xs[i2];
            r3[i2] = f2(x2, i2);
          }
          return r3;
        };
        var each$2 = function(xs, f2) {
          for (var i2 = 0, len = xs.length; i2 < len; i2++) {
            var x2 = xs[i2];
            f2(x2, i2);
          }
        };
        var eachr = function(xs, f2) {
          for (var i2 = xs.length - 1; i2 >= 0; i2--) {
            var x2 = xs[i2];
            f2(x2, i2);
          }
        };
        var partition = function(xs, pred) {
          var pass = [];
          var fail = [];
          for (var i2 = 0, len = xs.length; i2 < len; i2++) {
            var x2 = xs[i2];
            var arr = pred(x2, i2) ? pass : fail;
            arr.push(x2);
          }
          return {
            pass,
            fail
          };
        };
        var filter$2 = function(xs, pred) {
          var r3 = [];
          for (var i2 = 0, len = xs.length; i2 < len; i2++) {
            var x2 = xs[i2];
            if (pred(x2, i2)) {
              r3.push(x2);
            }
          }
          return r3;
        };
        var foldr = function(xs, f2, acc) {
          eachr(xs, function(x2, i2) {
            acc = f2(acc, x2, i2);
          });
          return acc;
        };
        var foldl = function(xs, f2, acc) {
          each$2(xs, function(x2, i2) {
            acc = f2(acc, x2, i2);
          });
          return acc;
        };
        var findUntil = function(xs, pred, until) {
          for (var i2 = 0, len = xs.length; i2 < len; i2++) {
            var x2 = xs[i2];
            if (pred(x2, i2)) {
              return Optional.some(x2);
            } else if (until(x2, i2)) {
              break;
            }
          }
          return Optional.none();
        };
        var find$1 = function(xs, pred) {
          return findUntil(xs, pred, never);
        };
        var findIndex2 = function(xs, pred) {
          for (var i2 = 0, len = xs.length; i2 < len; i2++) {
            var x2 = xs[i2];
            if (pred(x2, i2)) {
              return Optional.some(i2);
            }
          }
          return Optional.none();
        };
        var flatten$1 = function(xs) {
          var r3 = [];
          for (var i2 = 0, len = xs.length; i2 < len; ++i2) {
            if (!isArray2(xs[i2])) {
              throw new Error("Arr.flatten item " + i2 + " was not an array, input: " + xs);
            }
            nativePush.apply(r3, xs[i2]);
          }
          return r3;
        };
        var bind$2 = function(xs, f2) {
          return flatten$1(map$12(xs, f2));
        };
        var forall = function(xs, pred) {
          for (var i2 = 0, len = xs.length; i2 < len; ++i2) {
            var x2 = xs[i2];
            if (pred(x2, i2) !== true) {
              return false;
            }
          }
          return true;
        };
        var reverse = function(xs) {
          var r3 = nativeSlice.call(xs, 0);
          r3.reverse();
          return r3;
        };
        var mapToObject = function(xs, f2) {
          var r3 = {};
          for (var i2 = 0, len = xs.length; i2 < len; i2++) {
            var x2 = xs[i2];
            r3[String(x2)] = f2(x2, i2);
          }
          return r3;
        };
        var pure = function(x2) {
          return [x2];
        };
        var sort$1 = function(xs, comparator) {
          var copy2 = nativeSlice.call(xs, 0);
          copy2.sort(comparator);
          return copy2;
        };
        var get$d = function(xs, i2) {
          return i2 >= 0 && i2 < xs.length ? Optional.some(xs[i2]) : Optional.none();
        };
        var head = function(xs) {
          return get$d(xs, 0);
        };
        var last$2 = function(xs) {
          return get$d(xs, xs.length - 1);
        };
        var findMap = function(arr, f2) {
          for (var i2 = 0; i2 < arr.length; i2++) {
            var r3 = f2(arr[i2], i2);
            if (r3.isSome()) {
              return r3;
            }
          }
          return Optional.none();
        };
        var __assign = function() {
          __assign = Object.assign || function __assign2(t2) {
            for (var s2, i2 = 1, n2 = arguments.length; i2 < n2; i2++) {
              s2 = arguments[i2];
              for (var p2 in s2)
                if (Object.prototype.hasOwnProperty.call(s2, p2))
                  t2[p2] = s2[p2];
            }
            return t2;
          };
          return __assign.apply(this, arguments);
        };
        function __spreadArray(to, from2, pack) {
          if (pack || arguments.length === 2)
            for (var i2 = 0, l2 = from2.length, ar; i2 < l2; i2++) {
              if (ar || !(i2 in from2)) {
                if (!ar)
                  ar = Array.prototype.slice.call(from2, 0, i2);
                ar[i2] = from2[i2];
              }
            }
          return to.concat(ar || Array.prototype.slice.call(from2));
        }
        var cached = function(f2) {
          var called = false;
          var r3;
          return function() {
            var args = [];
            for (var _i2 = 0; _i2 < arguments.length; _i2++) {
              args[_i2] = arguments[_i2];
            }
            if (!called) {
              called = true;
              r3 = f2.apply(null, args);
            }
            return r3;
          };
        };
        var DeviceType = function(os, browser, userAgent, mediaMatch2) {
          var isiPad = os.isiOS() && /ipad/i.test(userAgent) === true;
          var isiPhone = os.isiOS() && !isiPad;
          var isMobile = os.isiOS() || os.isAndroid();
          var isTouch = isMobile || mediaMatch2("(pointer:coarse)");
          var isTablet = isiPad || !isiPhone && isMobile && mediaMatch2("(min-device-width:768px)");
          var isPhone = isiPhone || isMobile && !isTablet;
          var iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false;
          var isDesktop = !isPhone && !isTablet && !iOSwebview;
          return {
            isiPad: constant(isiPad),
            isiPhone: constant(isiPhone),
            isTablet: constant(isTablet),
            isPhone: constant(isPhone),
            isTouch: constant(isTouch),
            isAndroid: os.isAndroid,
            isiOS: os.isiOS,
            isWebView: constant(iOSwebview),
            isDesktop: constant(isDesktop)
          };
        };
        var firstMatch = function(regexes, s2) {
          for (var i2 = 0; i2 < regexes.length; i2++) {
            var x2 = regexes[i2];
            if (x2.test(s2)) {
              return x2;
            }
          }
          return void 0;
        };
        var find = function(regexes, agent) {
          var r3 = firstMatch(regexes, agent);
          if (!r3) {
            return {
              major: 0,
              minor: 0
            };
          }
          var group = function(i2) {
            return Number(agent.replace(r3, "$" + i2));
          };
          return nu$2(group(1), group(2));
        };
        var detect$6 = function(versionRegexes, agent) {
          var cleanedAgent = String(agent).toLowerCase();
          if (versionRegexes.length === 0) {
            return unknown$2();
          }
          return find(versionRegexes, cleanedAgent);
        };
        var unknown$2 = function() {
          return nu$2(0, 0);
        };
        var nu$2 = function(major, minor) {
          return {
            major,
            minor
          };
        };
        var Version = {
          nu: nu$2,
          detect: detect$6,
          unknown: unknown$2
        };
        var detectBrowser$1 = function(browsers2, userAgentData) {
          return findMap(userAgentData.brands, function(uaBrand) {
            var lcBrand = uaBrand.brand.toLowerCase();
            return find$1(browsers2, function(browser) {
              var _a;
              return lcBrand === ((_a = browser.brand) === null || _a === void 0 ? void 0 : _a.toLowerCase());
            }).map(function(info) {
              return {
                current: info.name,
                version: Version.nu(parseInt(uaBrand.version, 10), 0)
              };
            });
          });
        };
        var detect$5 = function(candidates, userAgent) {
          var agent = String(userAgent).toLowerCase();
          return find$1(candidates, function(candidate) {
            return candidate.search(agent);
          });
        };
        var detectBrowser = function(browsers2, userAgent) {
          return detect$5(browsers2, userAgent).map(function(browser) {
            var version2 = Version.detect(browser.versionRegexes, userAgent);
            return {
              current: browser.name,
              version: version2
            };
          });
        };
        var detectOs = function(oses2, userAgent) {
          return detect$5(oses2, userAgent).map(function(os) {
            var version2 = Version.detect(os.versionRegexes, userAgent);
            return {
              current: os.name,
              version: version2
            };
          });
        };
        var removeFromStart = function(str, numChars) {
          return str.substring(numChars);
        };
        var checkRange = function(str, substr, start4) {
          return substr === "" || str.length >= substr.length && str.substr(start4, start4 + substr.length) === substr;
        };
        var removeLeading = function(str, prefix) {
          return startsWith(str, prefix) ? removeFromStart(str, prefix.length) : str;
        };
        var contains$1 = function(str, substr) {
          return str.indexOf(substr) !== -1;
        };
        var startsWith = function(str, prefix) {
          return checkRange(str, prefix, 0);
        };
        var endsWith = function(str, suffix) {
          return checkRange(str, suffix, str.length - suffix.length);
        };
        var blank = function(r3) {
          return function(s2) {
            return s2.replace(r3, "");
          };
        };
        var trim = blank(/^\s+|\s+$/g);
        var isNotEmpty = function(s2) {
          return s2.length > 0;
        };
        var isEmpty$1 = function(s2) {
          return !isNotEmpty(s2);
        };
        var toFloat = function(value2) {
          var num = parseFloat(value2);
          return isNaN(num) ? Optional.none() : Optional.some(num);
        };
        var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/;
        var checkContains = function(target) {
          return function(uastring) {
            return contains$1(uastring, target);
          };
        };
        var browsers = [
          {
            name: "Edge",
            versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],
            search: function(uastring) {
              return contains$1(uastring, "edge/") && contains$1(uastring, "chrome") && contains$1(uastring, "safari") && contains$1(uastring, "applewebkit");
            }
          },
          {
            name: "Chrome",
            brand: "Chromium",
            versionRegexes: [
              /.*?chrome\/([0-9]+)\.([0-9]+).*/,
              normalVersionRegex
            ],
            search: function(uastring) {
              return contains$1(uastring, "chrome") && !contains$1(uastring, "chromeframe");
            }
          },
          {
            name: "IE",
            versionRegexes: [
              /.*?msie\ ?([0-9]+)\.([0-9]+).*/,
              /.*?rv:([0-9]+)\.([0-9]+).*/
            ],
            search: function(uastring) {
              return contains$1(uastring, "msie") || contains$1(uastring, "trident");
            }
          },
          {
            name: "Opera",
            versionRegexes: [
              normalVersionRegex,
              /.*?opera\/([0-9]+)\.([0-9]+).*/
            ],
            search: checkContains("opera")
          },
          {
            name: "Firefox",
            versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],
            search: checkContains("firefox")
          },
          {
            name: "Safari",
            versionRegexes: [
              normalVersionRegex,
              /.*?cpu os ([0-9]+)_([0-9]+).*/
            ],
            search: function(uastring) {
              return (contains$1(uastring, "safari") || contains$1(uastring, "mobile/")) && contains$1(uastring, "applewebkit");
            }
          }
        ];
        var oses = [
          {
            name: "Windows",
            search: checkContains("win"),
            versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]
          },
          {
            name: "iOS",
            search: function(uastring) {
              return contains$1(uastring, "iphone") || contains$1(uastring, "ipad");
            },
            versionRegexes: [
              /.*?version\/\ ?([0-9]+)\.([0-9]+).*/,
              /.*cpu os ([0-9]+)_([0-9]+).*/,
              /.*cpu iphone os ([0-9]+)_([0-9]+).*/
            ]
          },
          {
            name: "Android",
            search: checkContains("android"),
            versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/]
          },
          {
            name: "OSX",
            search: checkContains("mac os x"),
            versionRegexes: [/.*?mac\ os\ x\ ?([0-9]+)_([0-9]+).*/]
          },
          {
            name: "Linux",
            search: checkContains("linux"),
            versionRegexes: []
          },
          {
            name: "Solaris",
            search: checkContains("sunos"),
            versionRegexes: []
          },
          {
            name: "FreeBSD",
            search: checkContains("freebsd"),
            versionRegexes: []
          },
          {
            name: "ChromeOS",
            search: checkContains("cros"),
            versionRegexes: [/.*?chrome\/([0-9]+)\.([0-9]+).*/]
          }
        ];
        var PlatformInfo = {
          browsers: constant(browsers),
          oses: constant(oses)
        };
        var edge = "Edge";
        var chrome = "Chrome";
        var ie2 = "IE";
        var opera = "Opera";
        var firefox = "Firefox";
        var safari = "Safari";
        var unknown$1 = function() {
          return nu$1({
            current: void 0,
            version: Version.unknown()
          });
        };
        var nu$1 = function(info) {
          var current = info.current;
          var version2 = info.version;
          var isBrowser = function(name2) {
            return function() {
              return current === name2;
            };
          };
          return {
            current,
            version: version2,
            isEdge: isBrowser(edge),
            isChrome: isBrowser(chrome),
            isIE: isBrowser(ie2),
            isOpera: isBrowser(opera),
            isFirefox: isBrowser(firefox),
            isSafari: isBrowser(safari)
          };
        };
        var Browser = {
          unknown: unknown$1,
          nu: nu$1,
          edge: constant(edge),
          chrome: constant(chrome),
          ie: constant(ie2),
          opera: constant(opera),
          firefox: constant(firefox),
          safari: constant(safari)
        };
        var windows = "Windows";
        var ios = "iOS";
        var android = "Android";
        var linux = "Linux";
        var osx = "OSX";
        var solaris = "Solaris";
        var freebsd = "FreeBSD";
        var chromeos = "ChromeOS";
        var unknown = function() {
          return nu({
            current: void 0,
            version: Version.unknown()
          });
        };
        var nu = function(info) {
          var current = info.current;
          var version2 = info.version;
          var isOS = function(name2) {
            return function() {
              return current === name2;
            };
          };
          return {
            current,
            version: version2,
            isWindows: isOS(windows),
            isiOS: isOS(ios),
            isAndroid: isOS(android),
            isOSX: isOS(osx),
            isLinux: isOS(linux),
            isSolaris: isOS(solaris),
            isFreeBSD: isOS(freebsd),
            isChromeOS: isOS(chromeos)
          };
        };
        var OperatingSystem = {
          unknown,
          nu,
          windows: constant(windows),
          ios: constant(ios),
          android: constant(android),
          linux: constant(linux),
          osx: constant(osx),
          solaris: constant(solaris),
          freebsd: constant(freebsd),
          chromeos: constant(chromeos)
        };
        var detect$4 = function(userAgent, userAgentDataOpt, mediaMatch2) {
          var browsers2 = PlatformInfo.browsers();
          var oses2 = PlatformInfo.oses();
          var browser = userAgentDataOpt.bind(function(userAgentData) {
            return detectBrowser$1(browsers2, userAgentData);
          }).orThunk(function() {
            return detectBrowser(browsers2, userAgent);
          }).fold(Browser.unknown, Browser.nu);
          var os = detectOs(oses2, userAgent).fold(OperatingSystem.unknown, OperatingSystem.nu);
          var deviceType = DeviceType(os, browser, userAgent, mediaMatch2);
          return {
            browser,
            os,
            deviceType
          };
        };
        var PlatformDetection = { detect: detect$4 };
        var mediaMatch = function(query) {
          return window.matchMedia(query).matches;
        };
        var platform = cached(function() {
          return PlatformDetection.detect(navigator.userAgent, Optional.from(navigator.userAgentData), mediaMatch);
        });
        var detect$3 = function() {
          return platform();
        };
        var compareDocumentPosition = function(a2, b2, match2) {
          return (a2.compareDocumentPosition(b2) & match2) !== 0;
        };
        var documentPositionContainedBy = function(a2, b2) {
          return compareDocumentPosition(a2, b2, Node.DOCUMENT_POSITION_CONTAINED_BY);
        };
        var COMMENT = 8;
        var DOCUMENT = 9;
        var DOCUMENT_FRAGMENT = 11;
        var ELEMENT = 1;
        var TEXT = 3;
        var fromHtml$1 = function(html, scope) {
          var doc = scope || document;
          var div = doc.createElement("div");
          div.innerHTML = html;
          if (!div.hasChildNodes() || div.childNodes.length > 1) {
            console.error("HTML does not have a single root node", html);
            throw new Error("HTML must have a single root node");
          }
          return fromDom$1(div.childNodes[0]);
        };
        var fromTag = function(tag, scope) {
          var doc = scope || document;
          var node = doc.createElement(tag);
          return fromDom$1(node);
        };
        var fromText = function(text, scope) {
          var doc = scope || document;
          var node = doc.createTextNode(text);
          return fromDom$1(node);
        };
        var fromDom$1 = function(node) {
          if (node === null || node === void 0) {
            throw new Error("Node cannot be null or undefined");
          }
          return { dom: node };
        };
        var fromPoint$1 = function(docElm, x2, y2) {
          return Optional.from(docElm.dom.elementFromPoint(x2, y2)).map(fromDom$1);
        };
        var SugarElement = {
          fromHtml: fromHtml$1,
          fromTag,
          fromText,
          fromDom: fromDom$1,
          fromPoint: fromPoint$1
        };
        var is$2 = function(element, selector) {
          var dom = element.dom;
          if (dom.nodeType !== ELEMENT) {
            return false;
          } else {
            var elem = dom;
            if (elem.matches !== void 0) {
              return elem.matches(selector);
            } else if (elem.msMatchesSelector !== void 0) {
              return elem.msMatchesSelector(selector);
            } else if (elem.webkitMatchesSelector !== void 0) {
              return elem.webkitMatchesSelector(selector);
            } else if (elem.mozMatchesSelector !== void 0) {
              return elem.mozMatchesSelector(selector);
            } else {
              throw new Error("Browser lacks native selectors");
            }
          }
        };
        var bypassSelector = function(dom) {
          return dom.nodeType !== ELEMENT && dom.nodeType !== DOCUMENT && dom.nodeType !== DOCUMENT_FRAGMENT || dom.childElementCount === 0;
        };
        var all$1 = function(selector, scope) {
          var base2 = scope === void 0 ? document : scope.dom;
          return bypassSelector(base2) ? [] : map$12(base2.querySelectorAll(selector), SugarElement.fromDom);
        };
        var one = function(selector, scope) {
          var base2 = scope === void 0 ? document : scope.dom;
          return bypassSelector(base2) ? Optional.none() : Optional.from(base2.querySelector(selector)).map(SugarElement.fromDom);
        };
        var eq$1 = function(e1, e2) {
          return e1.dom === e2.dom;
        };
        var regularContains = function(e1, e2) {
          var d1 = e1.dom;
          var d2 = e2.dom;
          return d1 === d2 ? false : d1.contains(d2);
        };
        var ieContains = function(e1, e2) {
          return documentPositionContainedBy(e1.dom, e2.dom);
        };
        var contains2 = function(e1, e2) {
          return detect$3().browser.isIE() ? ieContains(e1, e2) : regularContains(e1, e2);
        };
        var is$1 = is$2;
        var keys = Object.keys;
        var hasOwnProperty = Object.hasOwnProperty;
        var each$1 = function(obj, f2) {
          var props = keys(obj);
          for (var k2 = 0, len = props.length; k2 < len; k2++) {
            var i2 = props[k2];
            var x2 = obj[i2];
            f2(x2, i2);
          }
        };
        var map3 = function(obj, f2) {
          return tupleMap(obj, function(x2, i2) {
            return {
              k: i2,
              v: f2(x2, i2)
            };
          });
        };
        var tupleMap = function(obj, f2) {
          var r3 = {};
          each$1(obj, function(x2, i2) {
            var tuple = f2(x2, i2);
            r3[tuple.k] = tuple.v;
          });
          return r3;
        };
        var objAcc = function(r3) {
          return function(x2, i2) {
            r3[i2] = x2;
          };
        };
        var internalFilter = function(obj, pred, onTrue, onFalse) {
          var r3 = {};
          each$1(obj, function(x2, i2) {
            (pred(x2, i2) ? onTrue : onFalse)(x2, i2);
          });
          return r3;
        };
        var filter$1 = function(obj, pred) {
          var t2 = {};
          internalFilter(obj, pred, objAcc(t2), noop3);
          return t2;
        };
        var mapToArray = function(obj, f2) {
          var r3 = [];
          each$1(obj, function(value2, name2) {
            r3.push(f2(value2, name2));
          });
          return r3;
        };
        var values = function(obj) {
          return mapToArray(obj, identity);
        };
        var size = function(obj) {
          return keys(obj).length;
        };
        var get$c = function(obj, key2) {
          return has$1(obj, key2) ? Optional.from(obj[key2]) : Optional.none();
        };
        var has$1 = function(obj, key2) {
          return hasOwnProperty.call(obj, key2);
        };
        var hasNonNullableKey = function(obj, key2) {
          return has$1(obj, key2) && obj[key2] !== void 0 && obj[key2] !== null;
        };
        var isEmpty = function(r3) {
          for (var x2 in r3) {
            if (hasOwnProperty.call(r3, x2)) {
              return false;
            }
          }
          return true;
        };
        var validSectionList = [
          "tfoot",
          "thead",
          "tbody",
          "colgroup"
        ];
        var isValidSection = function(parentName) {
          return contains$2(validSectionList, parentName);
        };
        var grid = function(rows2, columns2) {
          return {
            rows: rows2,
            columns: columns2
          };
        };
        var address = function(row2, column) {
          return {
            row: row2,
            column
          };
        };
        var detail = function(element, rowspan, colspan) {
          return {
            element,
            rowspan,
            colspan
          };
        };
        var detailnew = function(element, rowspan, colspan, isNew) {
          return {
            element,
            rowspan,
            colspan,
            isNew
          };
        };
        var extended = function(element, rowspan, colspan, row2, column, isLocked) {
          return {
            element,
            rowspan,
            colspan,
            row: row2,
            column,
            isLocked
          };
        };
        var rowdetail = function(element, cells2, section2) {
          return {
            element,
            cells: cells2,
            section: section2
          };
        };
        var rowdetailnew = function(element, cells2, section2, isNew) {
          return {
            element,
            cells: cells2,
            section: section2,
            isNew
          };
        };
        var elementnew = function(element, isNew, isLocked) {
          return {
            element,
            isNew,
            isLocked
          };
        };
        var rowcells = function(element, cells2, section2, isNew) {
          return {
            element,
            cells: cells2,
            section: section2,
            isNew
          };
        };
        var bounds = function(startRow, startCol, finishRow, finishCol) {
          return {
            startRow,
            startCol,
            finishRow,
            finishCol
          };
        };
        var columnext = function(element, colspan, column) {
          return {
            element,
            colspan,
            column
          };
        };
        var colgroup = function(element, columns2) {
          return {
            element,
            columns: columns2
          };
        };
        typeof window !== "undefined" ? window : Function("return this;")();
        var name = function(element) {
          var r3 = element.dom.nodeName;
          return r3.toLowerCase();
        };
        var type$1 = function(element) {
          return element.dom.nodeType;
        };
        var isType = function(t2) {
          return function(element) {
            return type$1(element) === t2;
          };
        };
        var isComment = function(element) {
          return type$1(element) === COMMENT || name(element) === "#comment";
        };
        var isElement3 = isType(ELEMENT);
        var isText = isType(TEXT);
        var isDocument = isType(DOCUMENT);
        var isDocumentFragment = isType(DOCUMENT_FRAGMENT);
        var isTag = function(tag) {
          return function(e2) {
            return isElement3(e2) && name(e2) === tag;
          };
        };
        var owner = function(element) {
          return SugarElement.fromDom(element.dom.ownerDocument);
        };
        var documentOrOwner = function(dos) {
          return isDocument(dos) ? dos : owner(dos);
        };
        var defaultView = function(element) {
          return SugarElement.fromDom(documentOrOwner(element).dom.defaultView);
        };
        var parent = function(element) {
          return Optional.from(element.dom.parentNode).map(SugarElement.fromDom);
        };
        var parentElement = function(element) {
          return Optional.from(element.dom.parentElement).map(SugarElement.fromDom);
        };
        var parents = function(element, isRoot) {
          var stop = isFunction2(isRoot) ? isRoot : never;
          var dom = element.dom;
          var ret = [];
          while (dom.parentNode !== null && dom.parentNode !== void 0) {
            var rawParent = dom.parentNode;
            var p2 = SugarElement.fromDom(rawParent);
            ret.push(p2);
            if (stop(p2) === true) {
              break;
            } else {
              dom = rawParent;
            }
          }
          return ret;
        };
        var prevSibling = function(element) {
          return Optional.from(element.dom.previousSibling).map(SugarElement.fromDom);
        };
        var nextSibling = function(element) {
          return Optional.from(element.dom.nextSibling).map(SugarElement.fromDom);
        };
        var children$3 = function(element) {
          return map$12(element.dom.childNodes, SugarElement.fromDom);
        };
        var child$3 = function(element, index) {
          var cs = element.dom.childNodes;
          return Optional.from(cs[index]).map(SugarElement.fromDom);
        };
        var firstChild = function(element) {
          return child$3(element, 0);
        };
        var isShadowRoot2 = function(dos) {
          return isDocumentFragment(dos) && isNonNullable(dos.dom.host);
        };
        var supported = isFunction2(Element.prototype.attachShadow) && isFunction2(Node.prototype.getRootNode);
        var isSupported$1 = constant(supported);
        var getRootNode = supported ? function(e2) {
          return SugarElement.fromDom(e2.dom.getRootNode());
        } : documentOrOwner;
        var getShadowRoot = function(e2) {
          var r3 = getRootNode(e2);
          return isShadowRoot2(r3) ? Optional.some(r3) : Optional.none();
        };
        var getShadowHost = function(e2) {
          return SugarElement.fromDom(e2.dom.host);
        };
        var getOriginalEventTarget = function(event) {
          if (isSupported$1() && isNonNullable(event.target)) {
            var el = SugarElement.fromDom(event.target);
            if (isElement3(el) && isOpenShadowHost(el)) {
              if (event.composed && event.composedPath) {
                var composedPath = event.composedPath();
                if (composedPath) {
                  return head(composedPath);
                }
              }
            }
          }
          return Optional.from(event.target);
        };
        var isOpenShadowHost = function(element) {
          return isNonNullable(element.dom.shadowRoot);
        };
        var inBody = function(element) {
          var dom = isText(element) ? element.dom.parentNode : element.dom;
          if (dom === void 0 || dom === null || dom.ownerDocument === null) {
            return false;
          }
          var doc = dom.ownerDocument;
          return getShadowRoot(SugarElement.fromDom(dom)).fold(function() {
            return doc.body.contains(dom);
          }, compose1(inBody, getShadowHost));
        };
        var body$1 = function() {
          return getBody$1(SugarElement.fromDom(document));
        };
        var getBody$1 = function(doc) {
          var b2 = doc.dom.body;
          if (b2 === null || b2 === void 0) {
            throw new Error("Body is not available yet");
          }
          return SugarElement.fromDom(b2);
        };
        var ancestors$4 = function(scope, predicate, isRoot) {
          return filter$2(parents(scope, isRoot), predicate);
        };
        var children$2 = function(scope, predicate) {
          return filter$2(children$3(scope), predicate);
        };
        var descendants$1 = function(scope, predicate) {
          var result = [];
          each$2(children$3(scope), function(x2) {
            if (predicate(x2)) {
              result = result.concat([x2]);
            }
            result = result.concat(descendants$1(x2, predicate));
          });
          return result;
        };
        var ancestors$3 = function(scope, selector, isRoot) {
          return ancestors$4(scope, function(e2) {
            return is$2(e2, selector);
          }, isRoot);
        };
        var children$1 = function(scope, selector) {
          return children$2(scope, function(e2) {
            return is$2(e2, selector);
          });
        };
        var descendants = function(scope, selector) {
          return all$1(selector, scope);
        };
        function ClosestOrAncestor(is2, ancestor2, scope, a2, isRoot) {
          if (is2(scope, a2)) {
            return Optional.some(scope);
          } else if (isFunction2(isRoot) && isRoot(scope)) {
            return Optional.none();
          } else {
            return ancestor2(scope, a2, isRoot);
          }
        }
        var ancestor$2 = function(scope, predicate, isRoot) {
          var element = scope.dom;
          var stop = isFunction2(isRoot) ? isRoot : never;
          while (element.parentNode) {
            element = element.parentNode;
            var el = SugarElement.fromDom(element);
            if (predicate(el)) {
              return Optional.some(el);
            } else if (stop(el)) {
              break;
            }
          }
          return Optional.none();
        };
        var closest$2 = function(scope, predicate, isRoot) {
          var is2 = function(s2, test) {
            return test(s2);
          };
          return ClosestOrAncestor(is2, ancestor$2, scope, predicate, isRoot);
        };
        var child$2 = function(scope, predicate) {
          var pred = function(node) {
            return predicate(SugarElement.fromDom(node));
          };
          var result = find$1(scope.dom.childNodes, pred);
          return result.map(SugarElement.fromDom);
        };
        var descendant$1 = function(scope, predicate) {
          var descend = function(node) {
            for (var i2 = 0; i2 < node.childNodes.length; i2++) {
              var child_1 = SugarElement.fromDom(node.childNodes[i2]);
              if (predicate(child_1)) {
                return Optional.some(child_1);
              }
              var res = descend(node.childNodes[i2]);
              if (res.isSome()) {
                return res;
              }
            }
            return Optional.none();
          };
          return descend(scope.dom);
        };
        var ancestor$1 = function(scope, selector, isRoot) {
          return ancestor$2(scope, function(e2) {
            return is$2(e2, selector);
          }, isRoot);
        };
        var child$1 = function(scope, selector) {
          return child$2(scope, function(e2) {
            return is$2(e2, selector);
          });
        };
        var descendant = function(scope, selector) {
          return one(selector, scope);
        };
        var closest$1 = function(scope, selector, isRoot) {
          var is2 = function(element, selector2) {
            return is$2(element, selector2);
          };
          return ClosestOrAncestor(is2, ancestor$1, scope, selector, isRoot);
        };
        var rawSet = function(dom, key2, value2) {
          if (isString(value2) || isBoolean(value2) || isNumber2(value2)) {
            dom.setAttribute(key2, value2 + "");
          } else {
            console.error("Invalid call to Attribute.set. Key ", key2, ":: Value ", value2, ":: Element ", dom);
            throw new Error("Attribute value was not simple");
          }
        };
        var set$2 = function(element, key2, value2) {
          rawSet(element.dom, key2, value2);
        };
        var setAll$1 = function(element, attrs) {
          var dom = element.dom;
          each$1(attrs, function(v2, k2) {
            rawSet(dom, k2, v2);
          });
        };
        var setOptions = function(element, attrs) {
          each$1(attrs, function(v2, k2) {
            v2.fold(function() {
              remove$7(element, k2);
            }, function(value2) {
              rawSet(element.dom, k2, value2);
            });
          });
        };
        var get$b = function(element, key2) {
          var v2 = element.dom.getAttribute(key2);
          return v2 === null ? void 0 : v2;
        };
        var getOpt = function(element, key2) {
          return Optional.from(get$b(element, key2));
        };
        var remove$7 = function(element, key2) {
          element.dom.removeAttribute(key2);
        };
        var clone$2 = function(element) {
          return foldl(element.dom.attributes, function(acc, attr) {
            acc[attr.name] = attr.value;
            return acc;
          }, {});
        };
        var is = function(lhs, rhs, comparator) {
          if (comparator === void 0) {
            comparator = tripleEquals;
          }
          return lhs.exists(function(left3) {
            return comparator(left3, rhs);
          });
        };
        var cat = function(arr) {
          var r3 = [];
          var push = function(x2) {
            r3.push(x2);
          };
          for (var i2 = 0; i2 < arr.length; i2++) {
            arr[i2].each(push);
          }
          return r3;
        };
        var lift2 = function(oa, ob, f2) {
          return oa.isSome() && ob.isSome() ? Optional.some(f2(oa.getOrDie(), ob.getOrDie())) : Optional.none();
        };
        var bindFrom = function(a2, f2) {
          return a2 !== void 0 && a2 !== null ? f2(a2) : Optional.none();
        };
        var flatten = function(oot) {
          return oot.bind(identity);
        };
        var someIf = function(b2, a2) {
          return b2 ? Optional.some(a2) : Optional.none();
        };
        var isSupported = function(dom) {
          return dom.style !== void 0 && isFunction2(dom.style.getPropertyValue);
        };
        var internalSet = function(dom, property, value2) {
          if (!isString(value2)) {
            console.error("Invalid call to CSS.set. Property ", property, ":: Value ", value2, ":: Element ", dom);
            throw new Error("CSS value must be a string: " + value2);
          }
          if (isSupported(dom)) {
            dom.style.setProperty(property, value2);
          }
        };
        var internalRemove = function(dom, property) {
          if (isSupported(dom)) {
            dom.style.removeProperty(property);
          }
        };
        var set$1 = function(element, property, value2) {
          var dom = element.dom;
          internalSet(dom, property, value2);
        };
        var setAll = function(element, css2) {
          var dom = element.dom;
          each$1(css2, function(v2, k2) {
            internalSet(dom, k2, v2);
          });
        };
        var get$a = function(element, property) {
          var dom = element.dom;
          var styles2 = window.getComputedStyle(dom);
          var r3 = styles2.getPropertyValue(property);
          return r3 === "" && !inBody(element) ? getUnsafeProperty(dom, property) : r3;
        };
        var getUnsafeProperty = function(dom, property) {
          return isSupported(dom) ? dom.style.getPropertyValue(property) : "";
        };
        var getRaw$2 = function(element, property) {
          var dom = element.dom;
          var raw = getUnsafeProperty(dom, property);
          return Optional.from(raw).filter(function(r3) {
            return r3.length > 0;
          });
        };
        var remove$6 = function(element, property) {
          var dom = element.dom;
          internalRemove(dom, property);
          if (is(getOpt(element, "style").map(trim), "")) {
            remove$7(element, "style");
          }
        };
        var copy$2 = function(source, target) {
          var sourceDom = source.dom;
          var targetDom = target.dom;
          if (isSupported(sourceDom) && isSupported(targetDom)) {
            targetDom.style.cssText = sourceDom.style.cssText;
          }
        };
        var getAttrValue = function(cell2, name2, fallback2) {
          if (fallback2 === void 0) {
            fallback2 = 0;
          }
          return getOpt(cell2, name2).map(function(value2) {
            return parseInt(value2, 10);
          }).getOr(fallback2);
        };
        var getSpan = function(cell2, type2) {
          return getAttrValue(cell2, type2, 1);
        };
        var hasColspan = function(cellOrCol) {
          if (isTag("col")(cellOrCol)) {
            return getAttrValue(cellOrCol, "span", 1) > 1;
          } else {
            return getSpan(cellOrCol, "colspan") > 1;
          }
        };
        var hasRowspan = function(cell2) {
          return getSpan(cell2, "rowspan") > 1;
        };
        var getCssValue = function(element, property) {
          return parseInt(get$a(element, property), 10);
        };
        var minWidth = constant(10);
        var minHeight = constant(10);
        var firstLayer = function(scope, selector) {
          return filterFirstLayer(scope, selector, always);
        };
        var filterFirstLayer = function(scope, selector, predicate) {
          return bind$2(children$3(scope), function(x2) {
            if (is$2(x2, selector)) {
              return predicate(x2) ? [x2] : [];
            } else {
              return filterFirstLayer(x2, selector, predicate);
            }
          });
        };
        var lookup = function(tags, element, isRoot) {
          if (isRoot === void 0) {
            isRoot = never;
          }
          if (isRoot(element)) {
            return Optional.none();
          }
          if (contains$2(tags, name(element))) {
            return Optional.some(element);
          }
          var isRootOrUpperTable = function(elm) {
            return is$2(elm, "table") || isRoot(elm);
          };
          return ancestor$1(element, tags.join(","), isRootOrUpperTable);
        };
        var cell = function(element, isRoot) {
          return lookup([
            "td",
            "th"
          ], element, isRoot);
        };
        var cells$1 = function(ancestor2) {
          return firstLayer(ancestor2, "th,td");
        };
        var columns$1 = function(ancestor2) {
          if (is$2(ancestor2, "colgroup")) {
            return children$1(ancestor2, "col");
          } else {
            return bind$2(columnGroups(ancestor2), function(columnGroup) {
              return children$1(columnGroup, "col");
            });
          }
        };
        var table = function(element, isRoot) {
          return closest$1(element, "table", isRoot);
        };
        var rows$1 = function(ancestor2) {
          return firstLayer(ancestor2, "tr");
        };
        var columnGroups = function(ancestor2) {
          return table(ancestor2).fold(constant([]), function(table2) {
            return children$1(table2, "colgroup");
          });
        };
        var fromRowsOrColGroups = function(elems, getSection) {
          return map$12(elems, function(row2) {
            if (name(row2) === "colgroup") {
              var cells2 = map$12(columns$1(row2), function(column) {
                var colspan = getAttrValue(column, "span", 1);
                return detail(column, 1, colspan);
              });
              return rowdetail(row2, cells2, "colgroup");
            } else {
              var cells2 = map$12(cells$1(row2), function(cell2) {
                var rowspan = getAttrValue(cell2, "rowspan", 1);
                var colspan = getAttrValue(cell2, "colspan", 1);
                return detail(cell2, rowspan, colspan);
              });
              return rowdetail(row2, cells2, getSection(row2));
            }
          });
        };
        var getParentSection = function(group) {
          return parent(group).map(function(parent2) {
            var parentName = name(parent2);
            return isValidSection(parentName) ? parentName : "tbody";
          }).getOr("tbody");
        };
        var fromTable$1 = function(table2) {
          var rows2 = rows$1(table2);
          var columnGroups$1 = columnGroups(table2);
          var elems = __spreadArray(__spreadArray([], columnGroups$1, true), rows2, true);
          return fromRowsOrColGroups(elems, getParentSection);
        };
        var fromPastedRows = function(elems, section2) {
          return fromRowsOrColGroups(elems, function() {
            return section2;
          });
        };
        var addCells = function(gridRow, index, cells2) {
          var existingCells = gridRow.cells;
          var before2 = existingCells.slice(0, index);
          var after2 = existingCells.slice(index);
          var newCells = before2.concat(cells2).concat(after2);
          return setCells(gridRow, newCells);
        };
        var addCell = function(gridRow, index, cell2) {
          return addCells(gridRow, index, [cell2]);
        };
        var mutateCell = function(gridRow, index, cell2) {
          var cells2 = gridRow.cells;
          cells2[index] = cell2;
        };
        var setCells = function(gridRow, cells2) {
          return rowcells(gridRow.element, cells2, gridRow.section, gridRow.isNew);
        };
        var mapCells = function(gridRow, f2) {
          var cells2 = gridRow.cells;
          var r3 = map$12(cells2, f2);
          return rowcells(gridRow.element, r3, gridRow.section, gridRow.isNew);
        };
        var getCell = function(gridRow, index) {
          return gridRow.cells[index];
        };
        var getCellElement = function(gridRow, index) {
          return getCell(gridRow, index).element;
        };
        var cellLength = function(gridRow) {
          return gridRow.cells.length;
        };
        var extractGridDetails = function(grid2) {
          var result = partition(grid2, function(row2) {
            return row2.section === "colgroup";
          });
          return {
            rows: result.fail,
            cols: result.pass
          };
        };
        var clone$12 = function(gridRow, cloneRow2, cloneCell) {
          var newCells = map$12(gridRow.cells, cloneCell);
          return rowcells(cloneRow2(gridRow.element), newCells, gridRow.section, true);
        };
        var LOCKED_COL_ATTR = "data-snooker-locked-cols";
        var getLockedColumnsFromTable = function(table2) {
          return getOpt(table2, LOCKED_COL_ATTR).bind(function(lockedColStr) {
            return Optional.from(lockedColStr.match(/\d+/g));
          }).map(function(lockedCols) {
            return mapToObject(lockedCols, always);
          });
        };
        var getLockedColumnsFromGrid = function(grid2) {
          var locked = foldl(extractGridDetails(grid2).rows, function(acc, row2) {
            each$2(row2.cells, function(cell2, idx) {
              if (cell2.isLocked) {
                acc[idx] = true;
              }
            });
            return acc;
          }, {});
          var lockedArr = mapToArray(locked, function(_val, key2) {
            return parseInt(key2, 10);
          });
          return sort$1(lockedArr);
        };
        var key = function(row2, column) {
          return row2 + "," + column;
        };
        var getAt = function(warehouse, row2, column) {
          return Optional.from(warehouse.access[key(row2, column)]);
        };
        var findItem = function(warehouse, item, comparator) {
          var filtered = filterItems(warehouse, function(detail2) {
            return comparator(item, detail2.element);
          });
          return filtered.length > 0 ? Optional.some(filtered[0]) : Optional.none();
        };
        var filterItems = function(warehouse, predicate) {
          var all2 = bind$2(warehouse.all, function(r3) {
            return r3.cells;
          });
          return filter$2(all2, predicate);
        };
        var generateColumns = function(rowData) {
          var columnsGroup = {};
          var index = 0;
          each$2(rowData.cells, function(column) {
            var colspan = column.colspan;
            range$1(colspan, function(columnIndex) {
              var colIndex = index + columnIndex;
              columnsGroup[colIndex] = columnext(column.element, colspan, colIndex);
            });
            index += colspan;
          });
          return columnsGroup;
        };
        var generate$1 = function(list) {
          var access = {};
          var cells2 = [];
          var tableOpt = head(list).map(function(rowData) {
            return rowData.element;
          }).bind(table);
          var lockedColumns = tableOpt.bind(getLockedColumnsFromTable).getOr({});
          var maxRows = 0;
          var maxColumns = 0;
          var rowCount = 0;
          var _a = partition(list, function(rowData) {
            return rowData.section === "colgroup";
          }), colgroupRows = _a.pass, rows2 = _a.fail;
          each$2(rows2, function(rowData) {
            var currentRow = [];
            each$2(rowData.cells, function(rowCell) {
              var start4 = 0;
              while (access[key(rowCount, start4)] !== void 0) {
                start4++;
              }
              var isLocked = hasNonNullableKey(lockedColumns, start4.toString());
              var current = extended(rowCell.element, rowCell.rowspan, rowCell.colspan, rowCount, start4, isLocked);
              for (var occupiedColumnPosition = 0; occupiedColumnPosition < rowCell.colspan; occupiedColumnPosition++) {
                for (var occupiedRowPosition = 0; occupiedRowPosition < rowCell.rowspan; occupiedRowPosition++) {
                  var rowPosition = rowCount + occupiedRowPosition;
                  var columnPosition = start4 + occupiedColumnPosition;
                  var newpos = key(rowPosition, columnPosition);
                  access[newpos] = current;
                  maxColumns = Math.max(maxColumns, columnPosition + 1);
                }
              }
              currentRow.push(current);
            });
            maxRows++;
            cells2.push(rowdetail(rowData.element, currentRow, rowData.section));
            rowCount++;
          });
          var _b = last$2(colgroupRows).map(function(rowData) {
            var columns3 = generateColumns(rowData);
            var colgroup$1 = colgroup(rowData.element, values(columns3));
            return {
              colgroups: [colgroup$1],
              columns: columns3
            };
          }).getOrThunk(function() {
            return {
              colgroups: [],
              columns: {}
            };
          }), columns2 = _b.columns, colgroups = _b.colgroups;
          var grid$1 = grid(maxRows, maxColumns);
          return {
            grid: grid$1,
            access,
            all: cells2,
            columns: columns2,
            colgroups
          };
        };
        var fromTable = function(table2) {
          var list = fromTable$1(table2);
          return generate$1(list);
        };
        var justCells = function(warehouse) {
          return bind$2(warehouse.all, function(w2) {
            return w2.cells;
          });
        };
        var justColumns = function(warehouse) {
          return values(warehouse.columns);
        };
        var hasColumns = function(warehouse) {
          return keys(warehouse.columns).length > 0;
        };
        var getColumnAt = function(warehouse, columnIndex) {
          return Optional.from(warehouse.columns[columnIndex]);
        };
        var Warehouse = {
          fromTable,
          generate: generate$1,
          getAt,
          findItem,
          filterItems,
          justCells,
          justColumns,
          hasColumns,
          getColumnAt
        };
        var inSelection = function(bounds2, detail2) {
          var leftEdge = detail2.column;
          var rightEdge = detail2.column + detail2.colspan - 1;
          var topEdge = detail2.row;
          var bottomEdge = detail2.row + detail2.rowspan - 1;
          return leftEdge <= bounds2.finishCol && rightEdge >= bounds2.startCol && (topEdge <= bounds2.finishRow && bottomEdge >= bounds2.startRow);
        };
        var isWithin = function(bounds2, detail2) {
          return detail2.column >= bounds2.startCol && detail2.column + detail2.colspan - 1 <= bounds2.finishCol && detail2.row >= bounds2.startRow && detail2.row + detail2.rowspan - 1 <= bounds2.finishRow;
        };
        var isRectangular = function(warehouse, bounds2) {
          var isRect = true;
          var detailIsWithin = curry(isWithin, bounds2);
          for (var i2 = bounds2.startRow; i2 <= bounds2.finishRow; i2++) {
            for (var j2 = bounds2.startCol; j2 <= bounds2.finishCol; j2++) {
              isRect = isRect && Warehouse.getAt(warehouse, i2, j2).exists(detailIsWithin);
            }
          }
          return isRect ? Optional.some(bounds2) : Optional.none();
        };
        var getBounds2 = function(detailA, detailB) {
          return bounds(Math.min(detailA.row, detailB.row), Math.min(detailA.column, detailB.column), Math.max(detailA.row + detailA.rowspan - 1, detailB.row + detailB.rowspan - 1), Math.max(detailA.column + detailA.colspan - 1, detailB.column + detailB.colspan - 1));
        };
        var getAnyBox = function(warehouse, startCell, finishCell) {
          var startCoords = Warehouse.findItem(warehouse, startCell, eq$1);
          var finishCoords = Warehouse.findItem(warehouse, finishCell, eq$1);
          return startCoords.bind(function(sc) {
            return finishCoords.map(function(fc) {
              return getBounds2(sc, fc);
            });
          });
        };
        var getBox$1 = function(warehouse, startCell, finishCell) {
          return getAnyBox(warehouse, startCell, finishCell).bind(function(bounds2) {
            return isRectangular(warehouse, bounds2);
          });
        };
        var moveBy$1 = function(warehouse, cell2, row2, column) {
          return Warehouse.findItem(warehouse, cell2, eq$1).bind(function(detail2) {
            var startRow = row2 > 0 ? detail2.row + detail2.rowspan - 1 : detail2.row;
            var startCol = column > 0 ? detail2.column + detail2.colspan - 1 : detail2.column;
            var dest = Warehouse.getAt(warehouse, startRow + row2, startCol + column);
            return dest.map(function(d2) {
              return d2.element;
            });
          });
        };
        var intercepts$1 = function(warehouse, start4, finish) {
          return getAnyBox(warehouse, start4, finish).map(function(bounds2) {
            var inside = Warehouse.filterItems(warehouse, curry(inSelection, bounds2));
            return map$12(inside, function(detail2) {
              return detail2.element;
            });
          });
        };
        var parentCell = function(warehouse, innerCell) {
          var isContainedBy = function(c1, c2) {
            return contains2(c2, c1);
          };
          return Warehouse.findItem(warehouse, innerCell, isContainedBy).map(function(detail2) {
            return detail2.element;
          });
        };
        var moveBy = function(cell2, deltaRow, deltaColumn) {
          return table(cell2).bind(function(table2) {
            var warehouse = getWarehouse(table2);
            return moveBy$1(warehouse, cell2, deltaRow, deltaColumn);
          });
        };
        var intercepts = function(table2, first2, last2) {
          var warehouse = getWarehouse(table2);
          return intercepts$1(warehouse, first2, last2);
        };
        var nestedIntercepts = function(table2, first2, firstTable, last2, lastTable) {
          var warehouse = getWarehouse(table2);
          var optStartCell = eq$1(table2, firstTable) ? Optional.some(first2) : parentCell(warehouse, first2);
          var optLastCell = eq$1(table2, lastTable) ? Optional.some(last2) : parentCell(warehouse, last2);
          return optStartCell.bind(function(startCell) {
            return optLastCell.bind(function(lastCell) {
              return intercepts$1(warehouse, startCell, lastCell);
            });
          });
        };
        var getBox = function(table2, first2, last2) {
          var warehouse = getWarehouse(table2);
          return getBox$1(warehouse, first2, last2);
        };
        var getWarehouse = Warehouse.fromTable;
        var before$4 = function(marker, element) {
          var parent$1 = parent(marker);
          parent$1.each(function(v2) {
            v2.dom.insertBefore(element.dom, marker.dom);
          });
        };
        var after$5 = function(marker, element) {
          var sibling = nextSibling(marker);
          sibling.fold(function() {
            var parent$1 = parent(marker);
            parent$1.each(function(v2) {
              append$1(v2, element);
            });
          }, function(v2) {
            before$4(v2, element);
          });
        };
        var prepend = function(parent2, element) {
          var firstChild$1 = firstChild(parent2);
          firstChild$1.fold(function() {
            append$1(parent2, element);
          }, function(v2) {
            parent2.dom.insertBefore(element.dom, v2.dom);
          });
        };
        var append$1 = function(parent2, element) {
          parent2.dom.appendChild(element.dom);
        };
        var appendAt = function(parent2, element, index) {
          child$3(parent2, index).fold(function() {
            append$1(parent2, element);
          }, function(v2) {
            before$4(v2, element);
          });
        };
        var wrap = function(element, wrapper) {
          before$4(element, wrapper);
          append$1(wrapper, element);
        };
        var before$3 = function(marker, elements2) {
          each$2(elements2, function(x2) {
            before$4(marker, x2);
          });
        };
        var after$4 = function(marker, elements2) {
          each$2(elements2, function(x2, i2) {
            var e2 = i2 === 0 ? marker : elements2[i2 - 1];
            after$5(e2, x2);
          });
        };
        var append = function(parent2, elements2) {
          each$2(elements2, function(x2) {
            append$1(parent2, x2);
          });
        };
        var empty = function(element) {
          element.dom.textContent = "";
          each$2(children$3(element), function(rogue) {
            remove$5(rogue);
          });
        };
        var remove$5 = function(element) {
          var dom = element.dom;
          if (dom.parentNode !== null) {
            dom.parentNode.removeChild(dom);
          }
        };
        var unwrap = function(wrapper) {
          var children2 = children$3(wrapper);
          if (children2.length > 0) {
            before$3(wrapper, children2);
          }
          remove$5(wrapper);
        };
        var NodeValue = function(is2, name2) {
          var get2 = function(element) {
            if (!is2(element)) {
              throw new Error("Can only get " + name2 + " value of a " + name2 + " node");
            }
            return getOption2(element).getOr("");
          };
          var getOption2 = function(element) {
            return is2(element) ? Optional.from(element.dom.nodeValue) : Optional.none();
          };
          var set3 = function(element, value2) {
            if (!is2(element)) {
              throw new Error("Can only set raw " + name2 + " value of a " + name2 + " node");
            }
            element.dom.nodeValue = value2;
          };
          return {
            get: get2,
            getOption: getOption2,
            set: set3
          };
        };
        var api$2 = NodeValue(isText, "text");
        var get$9 = function(element) {
          return api$2.get(element);
        };
        var getOption = function(element) {
          return api$2.getOption(element);
        };
        var set2 = function(element, value2) {
          return api$2.set(element, value2);
        };
        var TagBoundaries = [
          "body",
          "p",
          "div",
          "article",
          "aside",
          "figcaption",
          "figure",
          "footer",
          "header",
          "nav",
          "section",
          "ol",
          "ul",
          "li",
          "table",
          "thead",
          "tbody",
          "tfoot",
          "caption",
          "tr",
          "td",
          "th",
          "h1",
          "h2",
          "h3",
          "h4",
          "h5",
          "h6",
          "blockquote",
          "pre",
          "address"
        ];
        function DomUniverse() {
          var clone3 = function(element) {
            return SugarElement.fromDom(element.dom.cloneNode(false));
          };
          var document2 = function(element) {
            return documentOrOwner(element).dom;
          };
          var isBoundary = function(element) {
            if (!isElement3(element)) {
              return false;
            }
            if (name(element) === "body") {
              return true;
            }
            return contains$2(TagBoundaries, name(element));
          };
          var isEmptyTag2 = function(element) {
            if (!isElement3(element)) {
              return false;
            }
            return contains$2([
              "br",
              "img",
              "hr",
              "input"
            ], name(element));
          };
          var isNonEditable = function(element) {
            return isElement3(element) && get$b(element, "contenteditable") === "false";
          };
          var comparePosition = function(element, other) {
            return element.dom.compareDocumentPosition(other.dom);
          };
          var copyAttributesTo = function(source, destination) {
            var as = clone$2(source);
            setAll$1(destination, as);
          };
          var isSpecial = function(element) {
            var tag = name(element);
            return contains$2([
              "script",
              "noscript",
              "iframe",
              "noframes",
              "noembed",
              "title",
              "style",
              "textarea",
              "xmp"
            ], tag);
          };
          var getLanguage = function(element) {
            return isElement3(element) ? getOpt(element, "lang") : Optional.none();
          };
          return {
            up: constant({
              selector: ancestor$1,
              closest: closest$1,
              predicate: ancestor$2,
              all: parents
            }),
            down: constant({
              selector: descendants,
              predicate: descendants$1
            }),
            styles: constant({
              get: get$a,
              getRaw: getRaw$2,
              set: set$1,
              remove: remove$6
            }),
            attrs: constant({
              get: get$b,
              set: set$2,
              remove: remove$7,
              copyTo: copyAttributesTo
            }),
            insert: constant({
              before: before$4,
              after: after$5,
              afterAll: after$4,
              append: append$1,
              appendAll: append,
              prepend,
              wrap
            }),
            remove: constant({
              unwrap,
              remove: remove$5
            }),
            create: constant({
              nu: SugarElement.fromTag,
              clone: clone3,
              text: SugarElement.fromText
            }),
            query: constant({
              comparePosition,
              prevSibling,
              nextSibling
            }),
            property: constant({
              children: children$3,
              name,
              parent,
              document: document2,
              isText,
              isComment,
              isElement: isElement3,
              isSpecial,
              getLanguage,
              getText: get$9,
              setText: set2,
              isBoundary,
              isEmptyTag: isEmptyTag2,
              isNonEditable
            }),
            eq: eq$1,
            is: is$1
          };
        }
        var all = function(universe2, look, elements2, f2) {
          var head2 = elements2[0];
          var tail = elements2.slice(1);
          return f2(universe2, look, head2, tail);
        };
        var oneAll = function(universe2, look, elements2) {
          return elements2.length > 0 ? all(universe2, look, elements2, unsafeOne) : Optional.none();
        };
        var unsafeOne = function(universe2, look, head2, tail) {
          var start4 = look(universe2, head2);
          return foldr(tail, function(b2, a2) {
            var current = look(universe2, a2);
            return commonElement(universe2, b2, current);
          }, start4);
        };
        var commonElement = function(universe2, start4, end2) {
          return start4.bind(function(s2) {
            return end2.filter(curry(universe2.eq, s2));
          });
        };
        var eq2 = function(universe2, item) {
          return curry(universe2.eq, item);
        };
        var ancestors$2 = function(universe2, start4, end2, isRoot) {
          if (isRoot === void 0) {
            isRoot = never;
          }
          var ps1 = [start4].concat(universe2.up().all(start4));
          var ps2 = [end2].concat(universe2.up().all(end2));
          var prune4 = function(path) {
            var index = findIndex2(path, isRoot);
            return index.fold(function() {
              return path;
            }, function(ind) {
              return path.slice(0, ind + 1);
            });
          };
          var pruned1 = prune4(ps1);
          var pruned2 = prune4(ps2);
          var shared = find$1(pruned1, function(x2) {
            return exists(pruned2, eq2(universe2, x2));
          });
          return {
            firstpath: pruned1,
            secondpath: pruned2,
            shared
          };
        };
        var sharedOne$1 = oneAll;
        var ancestors$1 = ancestors$2;
        var universe$3 = DomUniverse();
        var sharedOne = function(look, elements2) {
          return sharedOne$1(universe$3, function(_universe, element) {
            return look(element);
          }, elements2);
        };
        var ancestors = function(start4, finish, isRoot) {
          return ancestors$1(universe$3, start4, finish, isRoot);
        };
        var lookupTable = function(container) {
          return ancestor$1(container, "table");
        };
        var identify = function(start4, finish, isRoot) {
          var getIsRoot2 = function(rootTable) {
            return function(element) {
              return isRoot !== void 0 && isRoot(element) || eq$1(element, rootTable);
            };
          };
          if (eq$1(start4, finish)) {
            return Optional.some({
              boxes: Optional.some([start4]),
              start: start4,
              finish
            });
          } else {
            return lookupTable(start4).bind(function(startTable) {
              return lookupTable(finish).bind(function(finishTable) {
                if (eq$1(startTable, finishTable)) {
                  return Optional.some({
                    boxes: intercepts(startTable, start4, finish),
                    start: start4,
                    finish
                  });
                } else if (contains2(startTable, finishTable)) {
                  var ancestorCells = ancestors$3(finish, "td,th", getIsRoot2(startTable));
                  var finishCell = ancestorCells.length > 0 ? ancestorCells[ancestorCells.length - 1] : finish;
                  return Optional.some({
                    boxes: nestedIntercepts(startTable, start4, startTable, finish, finishTable),
                    start: start4,
                    finish: finishCell
                  });
                } else if (contains2(finishTable, startTable)) {
                  var ancestorCells = ancestors$3(start4, "td,th", getIsRoot2(finishTable));
                  var startCell = ancestorCells.length > 0 ? ancestorCells[ancestorCells.length - 1] : start4;
                  return Optional.some({
                    boxes: nestedIntercepts(finishTable, start4, startTable, finish, finishTable),
                    start: start4,
                    finish: startCell
                  });
                } else {
                  return ancestors(start4, finish).shared.bind(function(lca) {
                    return closest$1(lca, "table", isRoot).bind(function(lcaTable) {
                      var finishAncestorCells = ancestors$3(finish, "td,th", getIsRoot2(lcaTable));
                      var finishCell2 = finishAncestorCells.length > 0 ? finishAncestorCells[finishAncestorCells.length - 1] : finish;
                      var startAncestorCells = ancestors$3(start4, "td,th", getIsRoot2(lcaTable));
                      var startCell2 = startAncestorCells.length > 0 ? startAncestorCells[startAncestorCells.length - 1] : start4;
                      return Optional.some({
                        boxes: nestedIntercepts(lcaTable, start4, startTable, finish, finishTable),
                        start: startCell2,
                        finish: finishCell2
                      });
                    });
                  });
                }
              });
            });
          }
        };
        var retrieve$1 = function(container, selector) {
          var sels = descendants(container, selector);
          return sels.length > 0 ? Optional.some(sels) : Optional.none();
        };
        var getLast = function(boxes, lastSelectedSelector) {
          return find$1(boxes, function(box) {
            return is$2(box, lastSelectedSelector);
          });
        };
        var getEdges = function(container, firstSelectedSelector, lastSelectedSelector) {
          return descendant(container, firstSelectedSelector).bind(function(first2) {
            return descendant(container, lastSelectedSelector).bind(function(last2) {
              return sharedOne(lookupTable, [
                first2,
                last2
              ]).map(function(table2) {
                return {
                  first: first2,
                  last: last2,
                  table: table2
                };
              });
            });
          });
        };
        var expandTo = function(finish, firstSelectedSelector) {
          return ancestor$1(finish, "table").bind(function(table2) {
            return descendant(table2, firstSelectedSelector).bind(function(start4) {
              return identify(start4, finish).bind(function(identified) {
                return identified.boxes.map(function(boxes) {
                  return {
                    boxes,
                    start: identified.start,
                    finish: identified.finish
                  };
                });
              });
            });
          });
        };
        var shiftSelection = function(boxes, deltaRow, deltaColumn, firstSelectedSelector, lastSelectedSelector) {
          return getLast(boxes, lastSelectedSelector).bind(function(last2) {
            return moveBy(last2, deltaRow, deltaColumn).bind(function(finish) {
              return expandTo(finish, firstSelectedSelector);
            });
          });
        };
        var retrieve = function(container, selector) {
          return retrieve$1(container, selector);
        };
        var retrieveBox = function(container, firstSelectedSelector, lastSelectedSelector) {
          return getEdges(container, firstSelectedSelector, lastSelectedSelector).bind(function(edges) {
            var isRoot = function(ancestor2) {
              return eq$1(container, ancestor2);
            };
            var sectionSelector = "thead,tfoot,tbody,table";
            var firstAncestor = ancestor$1(edges.first, sectionSelector, isRoot);
            var lastAncestor = ancestor$1(edges.last, sectionSelector, isRoot);
            return firstAncestor.bind(function(fA) {
              return lastAncestor.bind(function(lA) {
                return eq$1(fA, lA) ? getBox(edges.table, edges.first, edges.last) : Optional.none();
              });
            });
          });
        };
        var generate = function(cases) {
          if (!isArray2(cases)) {
            throw new Error("cases must be an array");
          }
          if (cases.length === 0) {
            throw new Error("there must be at least one case");
          }
          var constructors = [];
          var adt2 = {};
          each$2(cases, function(acase, count) {
            var keys$1 = keys(acase);
            if (keys$1.length !== 1) {
              throw new Error("one and only one name per case");
            }
            var key2 = keys$1[0];
            var value2 = acase[key2];
            if (adt2[key2] !== void 0) {
              throw new Error("duplicate key detected:" + key2);
            } else if (key2 === "cata") {
              throw new Error("cannot have a case named cata (sorry)");
            } else if (!isArray2(value2)) {
              throw new Error("case arguments must be an array");
            }
            constructors.push(key2);
            adt2[key2] = function() {
              var args = [];
              for (var _i2 = 0; _i2 < arguments.length; _i2++) {
                args[_i2] = arguments[_i2];
              }
              var argLength = args.length;
              if (argLength !== value2.length) {
                throw new Error("Wrong number of arguments to case " + key2 + ". Expected " + value2.length + " (" + value2 + "), got " + argLength);
              }
              var match2 = function(branches) {
                var branchKeys = keys(branches);
                if (constructors.length !== branchKeys.length) {
                  throw new Error("Wrong number of arguments to match. Expected: " + constructors.join(",") + "\nActual: " + branchKeys.join(","));
                }
                var allReqd = forall(constructors, function(reqKey) {
                  return contains$2(branchKeys, reqKey);
                });
                if (!allReqd) {
                  throw new Error("Not all branches were specified when using match. Specified: " + branchKeys.join(", ") + "\nRequired: " + constructors.join(", "));
                }
                return branches[key2].apply(null, args);
              };
              return {
                fold: function() {
                  var foldArgs = [];
                  for (var _i3 = 0; _i3 < arguments.length; _i3++) {
                    foldArgs[_i3] = arguments[_i3];
                  }
                  if (foldArgs.length !== cases.length) {
                    throw new Error("Wrong number of arguments to fold. Expected " + cases.length + ", got " + foldArgs.length);
                  }
                  var target = foldArgs[count];
                  return target.apply(null, args);
                },
                match: match2,
                log: function(label) {
                  console.log(label, {
                    constructors,
                    constructor: key2,
                    params: args
                  });
                }
              };
            };
          });
          return adt2;
        };
        var Adt = { generate };
        var type = Adt.generate([
          { none: [] },
          { multiple: ["elements"] },
          { single: ["element"] }
        ]);
        var cata$2 = function(subject, onNone, onMultiple, onSingle) {
          return subject.fold(onNone, onMultiple, onSingle);
        };
        var none$1 = type.none;
        var multiple = type.multiple;
        var single = type.single;
        var Selections = function(lazyRoot, getStart2, selectedSelector) {
          var get2 = function() {
            return retrieve(lazyRoot(), selectedSelector).fold(function() {
              return getStart2().fold(none$1, single);
            }, function(cells2) {
              return multiple(cells2);
            });
          };
          return { get: get2 };
        };
        var global$3 = tinymce.util.Tools.resolve("tinymce.PluginManager");
        var clone2 = function(original, isDeep) {
          return SugarElement.fromDom(original.dom.cloneNode(isDeep));
        };
        var shallow = function(original) {
          return clone2(original, false);
        };
        var deep = function(original) {
          return clone2(original, true);
        };
        var shallowAs = function(original, tag) {
          var nu2 = SugarElement.fromTag(tag);
          var attributes = clone$2(original);
          setAll$1(nu2, attributes);
          return nu2;
        };
        var copy$1 = function(original, tag) {
          var nu2 = shallowAs(original, tag);
          var cloneChildren = children$3(deep(original));
          append(nu2, cloneChildren);
          return nu2;
        };
        var mutate$1 = function(original, tag) {
          var nu2 = shallowAs(original, tag);
          before$4(original, nu2);
          var children2 = children$3(original);
          append(nu2, children2);
          remove$5(original);
          return nu2;
        };
        var Dimension = function(name2, getOffset) {
          var set3 = function(element, h3) {
            if (!isNumber2(h3) && !h3.match(/^[0-9]+$/)) {
              throw new Error(name2 + ".set accepts only positive integer values. Value was " + h3);
            }
            var dom = element.dom;
            if (isSupported(dom)) {
              dom.style[name2] = h3 + "px";
            }
          };
          var get2 = function(element) {
            var r3 = getOffset(element);
            if (r3 <= 0 || r3 === null) {
              var css2 = get$a(element, name2);
              return parseFloat(css2) || 0;
            }
            return r3;
          };
          var getOuter2 = get2;
          var aggregate = function(element, properties) {
            return foldl(properties, function(acc, property) {
              var val = get$a(element, property);
              var value2 = val === void 0 ? 0 : parseInt(val, 10);
              return isNaN(value2) ? acc : acc + value2;
            }, 0);
          };
          var max2 = function(element, value2, properties) {
            var cumulativeInclusions = aggregate(element, properties);
            var absoluteMax = value2 > cumulativeInclusions ? value2 - cumulativeInclusions : 0;
            return absoluteMax;
          };
          return {
            set: set3,
            get: get2,
            getOuter: getOuter2,
            aggregate,
            max: max2
          };
        };
        var needManualCalc = function() {
          var browser = detect$3().browser;
          return browser.isIE() || browser.isEdge();
        };
        var toNumber = function(px, fallback2) {
          return toFloat(px).getOr(fallback2);
        };
        var getProp = function(element, name2, fallback2) {
          return toNumber(get$a(element, name2), fallback2);
        };
        var getBoxSizing = function(element) {
          return get$a(element, "box-sizing");
        };
        var calcContentBoxSize = function(element, size2, upper, lower) {
          var paddingUpper = getProp(element, "padding-" + upper, 0);
          var paddingLower = getProp(element, "padding-" + lower, 0);
          var borderUpper = getProp(element, "border-" + upper + "-width", 0);
          var borderLower = getProp(element, "border-" + lower + "-width", 0);
          return size2 - paddingUpper - paddingLower - borderUpper - borderLower;
        };
        var getCalculatedHeight = function(element, boxSizing) {
          var dom = element.dom;
          var height2 = dom.getBoundingClientRect().height || dom.offsetHeight;
          return boxSizing === "border-box" ? height2 : calcContentBoxSize(element, height2, "top", "bottom");
        };
        var getCalculatedWidth = function(element, boxSizing) {
          var dom = element.dom;
          var width2 = dom.getBoundingClientRect().width || dom.offsetWidth;
          return boxSizing === "border-box" ? width2 : calcContentBoxSize(element, width2, "left", "right");
        };
        var getHeight$1 = function(element) {
          return needManualCalc() ? getCalculatedHeight(element, getBoxSizing(element)) : getProp(element, "height", element.dom.offsetHeight);
        };
        var getWidth = function(element) {
          return needManualCalc() ? getCalculatedWidth(element, getBoxSizing(element)) : getProp(element, "width", element.dom.offsetWidth);
        };
        var getInnerWidth = function(element) {
          return getCalculatedWidth(element, "content-box");
        };
        var api$1 = Dimension("width", function(element) {
          return element.dom.offsetWidth;
        });
        var get$8 = function(element) {
          return api$1.get(element);
        };
        var getOuter$2 = function(element) {
          return api$1.getOuter(element);
        };
        var getInner = getInnerWidth;
        var getRuntime$1 = getWidth;
        var columns = function(warehouse, isValidCell) {
          if (isValidCell === void 0) {
            isValidCell = always;
          }
          var grid2 = warehouse.grid;
          var cols = range$1(grid2.columns, identity);
          var rowsArr = range$1(grid2.rows, identity);
          return map$12(cols, function(col2) {
            var getBlock = function() {
              return bind$2(rowsArr, function(r3) {
                return Warehouse.getAt(warehouse, r3, col2).filter(function(detail2) {
                  return detail2.column === col2;
                }).toArray();
              });
            };
            var isValid2 = function(detail2) {
              return detail2.colspan === 1 && isValidCell(detail2.element);
            };
            var getFallback = function() {
              return Warehouse.getAt(warehouse, 0, col2);
            };
            return decide(getBlock, isValid2, getFallback);
          });
        };
        var decide = function(getBlock, isValid2, getFallback) {
          var inBlock = getBlock();
          var validInBlock = find$1(inBlock, isValid2);
          var detailOption = validInBlock.orThunk(function() {
            return Optional.from(inBlock[0]).orThunk(getFallback);
          });
          return detailOption.map(function(detail2) {
            return detail2.element;
          });
        };
        var rows = function(warehouse) {
          var grid2 = warehouse.grid;
          var rowsArr = range$1(grid2.rows, identity);
          var cols = range$1(grid2.columns, identity);
          return map$12(rowsArr, function(row2) {
            var getBlock = function() {
              return bind$2(cols, function(c2) {
                return Warehouse.getAt(warehouse, row2, c2).filter(function(detail2) {
                  return detail2.row === row2;
                }).fold(constant([]), function(detail2) {
                  return [detail2];
                });
              });
            };
            var isSingle = function(detail2) {
              return detail2.rowspan === 1;
            };
            var getFallback = function() {
              return Warehouse.getAt(warehouse, row2, 0);
            };
            return decide(getBlock, isSingle, getFallback);
          });
        };
        var deduce = function(xs, index) {
          if (index < 0 || index >= xs.length - 1) {
            return Optional.none();
          }
          var current = xs[index].fold(function() {
            var rest = reverse(xs.slice(0, index));
            return findMap(rest, function(a2, i2) {
              return a2.map(function(aa) {
                return {
                  value: aa,
                  delta: i2 + 1
                };
              });
            });
          }, function(c2) {
            return Optional.some({
              value: c2,
              delta: 0
            });
          });
          var next2 = xs[index + 1].fold(function() {
            var rest = xs.slice(index + 1);
            return findMap(rest, function(a2, i2) {
              return a2.map(function(aa) {
                return {
                  value: aa,
                  delta: i2 + 1
                };
              });
            });
          }, function(n2) {
            return Optional.some({
              value: n2,
              delta: 1
            });
          });
          return current.bind(function(c2) {
            return next2.map(function(n2) {
              var extras = n2.delta + c2.delta;
              return Math.abs(n2.value - c2.value) / extras;
            });
          });
        };
        var onDirection = function(isLtr, isRtl) {
          return function(element) {
            return getDirection(element) === "rtl" ? isRtl : isLtr;
          };
        };
        var getDirection = function(element) {
          return get$a(element, "direction") === "rtl" ? "rtl" : "ltr";
        };
        var api = Dimension("height", function(element) {
          var dom = element.dom;
          return inBody(element) ? dom.getBoundingClientRect().height : dom.offsetHeight;
        });
        var get$7 = function(element) {
          return api.get(element);
        };
        var getOuter$1 = function(element) {
          return api.getOuter(element);
        };
        var getRuntime = getHeight$1;
        var r2 = function(left3, top2) {
          var translate2 = function(x2, y2) {
            return r2(left3 + x2, top2 + y2);
          };
          return {
            left: left3,
            top: top2,
            translate: translate2
          };
        };
        var SugarPosition = r2;
        var boxPosition = function(dom) {
          var box = dom.getBoundingClientRect();
          return SugarPosition(box.left, box.top);
        };
        var firstDefinedOrZero = function(a2, b2) {
          if (a2 !== void 0) {
            return a2;
          } else {
            return b2 !== void 0 ? b2 : 0;
          }
        };
        var absolute = function(element) {
          var doc = element.dom.ownerDocument;
          var body2 = doc.body;
          var win = doc.defaultView;
          var html = doc.documentElement;
          if (body2 === element.dom) {
            return SugarPosition(body2.offsetLeft, body2.offsetTop);
          }
          var scrollTop = firstDefinedOrZero(win === null || win === void 0 ? void 0 : win.pageYOffset, html.scrollTop);
          var scrollLeft = firstDefinedOrZero(win === null || win === void 0 ? void 0 : win.pageXOffset, html.scrollLeft);
          var clientTop = firstDefinedOrZero(html.clientTop, body2.clientTop);
          var clientLeft = firstDefinedOrZero(html.clientLeft, body2.clientLeft);
          return viewport2(element).translate(scrollLeft - clientLeft, scrollTop - clientTop);
        };
        var viewport2 = function(element) {
          var dom = element.dom;
          var doc = dom.ownerDocument;
          var body2 = doc.body;
          if (body2 === dom) {
            return SugarPosition(body2.offsetLeft, body2.offsetTop);
          }
          if (!inBody(element)) {
            return SugarPosition(0, 0);
          }
          return boxPosition(dom);
        };
        var rowInfo = function(row2, y2) {
          return {
            row: row2,
            y: y2
          };
        };
        var colInfo = function(col2, x2) {
          return {
            col: col2,
            x: x2
          };
        };
        var rtlEdge = function(cell2) {
          var pos = absolute(cell2);
          return pos.left + getOuter$2(cell2);
        };
        var ltrEdge = function(cell2) {
          return absolute(cell2).left;
        };
        var getLeftEdge = function(index, cell2) {
          return colInfo(index, ltrEdge(cell2));
        };
        var getRightEdge = function(index, cell2) {
          return colInfo(index, rtlEdge(cell2));
        };
        var getTop$1 = function(cell2) {
          return absolute(cell2).top;
        };
        var getTopEdge = function(index, cell2) {
          return rowInfo(index, getTop$1(cell2));
        };
        var getBottomEdge = function(index, cell2) {
          return rowInfo(index, getTop$1(cell2) + getOuter$1(cell2));
        };
        var findPositions = function(getInnerEdge, getOuterEdge, array) {
          if (array.length === 0) {
            return [];
          }
          var lines = map$12(array.slice(1), function(cellOption, index) {
            return cellOption.map(function(cell2) {
              return getInnerEdge(index, cell2);
            });
          });
          var lastLine = array[array.length - 1].map(function(cell2) {
            return getOuterEdge(array.length - 1, cell2);
          });
          return lines.concat([lastLine]);
        };
        var negate = function(step) {
          return -step;
        };
        var height = {
          delta: identity,
          positions: function(optElements) {
            return findPositions(getTopEdge, getBottomEdge, optElements);
          },
          edge: getTop$1
        };
        var ltr$1 = {
          delta: identity,
          edge: ltrEdge,
          positions: function(optElements) {
            return findPositions(getLeftEdge, getRightEdge, optElements);
          }
        };
        var rtl$1 = {
          delta: negate,
          edge: rtlEdge,
          positions: function(optElements) {
            return findPositions(getRightEdge, getLeftEdge, optElements);
          }
        };
        var detect$2 = onDirection(ltr$1, rtl$1);
        var width = {
          delta: function(amount, table2) {
            return detect$2(table2).delta(amount, table2);
          },
          positions: function(cols, table2) {
            return detect$2(table2).positions(cols, table2);
          },
          edge: function(cell2) {
            return detect$2(cell2).edge(cell2);
          }
        };
        var units = {
          unsupportedLength: [
            "em",
            "ex",
            "cap",
            "ch",
            "ic",
            "rem",
            "lh",
            "rlh",
            "vw",
            "vh",
            "vi",
            "vb",
            "vmin",
            "vmax",
            "cm",
            "mm",
            "Q",
            "in",
            "pc",
            "pt",
            "px"
          ],
          fixed: [
            "px",
            "pt"
          ],
          relative: ["%"],
          empty: [""]
        };
        var pattern = function() {
          var decimalDigits = "[0-9]+";
          var signedInteger = "[+-]?" + decimalDigits;
          var exponentPart = "[eE]" + signedInteger;
          var dot2 = "\\.";
          var opt = function(input) {
            return "(?:" + input + ")?";
          };
          var unsignedDecimalLiteral = [
            "Infinity",
            decimalDigits + dot2 + opt(decimalDigits) + opt(exponentPart),
            dot2 + decimalDigits + opt(exponentPart),
            decimalDigits + opt(exponentPart)
          ].join("|");
          var float = "[+-]?(?:" + unsignedDecimalLiteral + ")";
          return new RegExp("^(" + float + ")(.*)$");
        }();
        var isUnit = function(unit, accepted) {
          return exists(accepted, function(acc) {
            return exists(units[acc], function(check) {
              return unit === check;
            });
          });
        };
        var parse3 = function(input, accepted) {
          var match2 = Optional.from(pattern.exec(input));
          return match2.bind(function(array) {
            var value2 = Number(array[1]);
            var unitRaw = array[2];
            if (isUnit(unitRaw, accepted)) {
              return Optional.some({
                value: value2,
                unit: unitRaw
              });
            } else {
              return Optional.none();
            }
          });
        };
        var rPercentageBasedSizeRegex = /(\d+(\.\d+)?)%/;
        var rPixelBasedSizeRegex = /(\d+(\.\d+)?)px|em/;
        var isCol$2 = isTag("col");
        var getPercentSize = function(elm, outerGetter, innerGetter) {
          var relativeParent = parentElement(elm).getOrThunk(function() {
            return getBody$1(owner(elm));
          });
          return outerGetter(elm) / innerGetter(relativeParent) * 100;
        };
        var setPixelWidth = function(cell2, amount) {
          set$1(cell2, "width", amount + "px");
        };
        var setPercentageWidth = function(cell2, amount) {
          set$1(cell2, "width", amount + "%");
        };
        var setHeight = function(cell2, amount) {
          set$1(cell2, "height", amount + "px");
        };
        var getHeightValue = function(cell2) {
          return getRuntime(cell2) + "px";
        };
        var convert = function(cell2, number, getter, setter) {
          var newSize = table(cell2).map(function(table2) {
            var total2 = getter(table2);
            return Math.floor(number / 100 * total2);
          }).getOr(number);
          setter(cell2, newSize);
          return newSize;
        };
        var normalizePixelSize = function(value2, cell2, getter, setter) {
          var number = parseFloat(value2);
          return endsWith(value2, "%") && name(cell2) !== "table" ? convert(cell2, number, getter, setter) : number;
        };
        var getTotalHeight = function(cell2) {
          var value2 = getHeightValue(cell2);
          if (!value2) {
            return get$7(cell2);
          }
          return normalizePixelSize(value2, cell2, get$7, setHeight);
        };
        var get$6 = function(cell2, type2, f2) {
          var v2 = f2(cell2);
          var span = getSpan(cell2, type2);
          return v2 / span;
        };
        var getRaw$1 = function(element, prop) {
          return getRaw$2(element, prop).orThunk(function() {
            return getOpt(element, prop).map(function(val) {
              return val + "px";
            });
          });
        };
        var getRawWidth$1 = function(element) {
          return getRaw$1(element, "width");
        };
        var getRawHeight = function(element) {
          return getRaw$1(element, "height");
        };
        var getPercentageWidth = function(cell2) {
          return getPercentSize(cell2, get$8, getInner);
        };
        var getPixelWidth$1 = function(cell2) {
          return isCol$2(cell2) ? get$8(cell2) : getRuntime$1(cell2);
        };
        var getHeight = function(cell2) {
          return get$6(cell2, "rowspan", getTotalHeight);
        };
        var getGenericWidth = function(cell2) {
          var width2 = getRawWidth$1(cell2);
          return width2.bind(function(w2) {
            return parse3(w2, [
              "fixed",
              "relative",
              "empty"
            ]);
          });
        };
        var setGenericWidth = function(cell2, amount, unit) {
          set$1(cell2, "width", amount + unit);
        };
        var getPixelTableWidth = function(table2) {
          return get$8(table2) + "px";
        };
        var getPercentTableWidth = function(table2) {
          return getPercentSize(table2, get$8, getInner) + "%";
        };
        var isPercentSizing$1 = function(table2) {
          return getRawWidth$1(table2).exists(function(size2) {
            return rPercentageBasedSizeRegex.test(size2);
          });
        };
        var isPixelSizing$1 = function(table2) {
          return getRawWidth$1(table2).exists(function(size2) {
            return rPixelBasedSizeRegex.test(size2);
          });
        };
        var isNoneSizing$1 = function(table2) {
          return getRawWidth$1(table2).isNone();
        };
        var percentageBasedSizeRegex = constant(rPercentageBasedSizeRegex);
        var isCol$1 = isTag("col");
        var getRawW = function(cell2) {
          return getRawWidth$1(cell2).getOrThunk(function() {
            return getPixelWidth$1(cell2) + "px";
          });
        };
        var getRawH = function(cell2) {
          return getRawHeight(cell2).getOrThunk(function() {
            return getHeight(cell2) + "px";
          });
        };
        var justCols = function(warehouse) {
          return map$12(Warehouse.justColumns(warehouse), function(column) {
            return Optional.from(column.element);
          });
        };
        var isValidColumn = function(cell2) {
          var browser = detect$3().browser;
          var supportsColWidths = browser.isChrome() || browser.isFirefox();
          return isCol$1(cell2) ? supportsColWidths : true;
        };
        var getDimension = function(cellOpt, index, backups, filter2, getter, fallback2) {
          return cellOpt.filter(filter2).fold(function() {
            return fallback2(deduce(backups, index));
          }, function(cell2) {
            return getter(cell2);
          });
        };
        var getWidthFrom = function(warehouse, table2, getWidth2, fallback2) {
          var columnCells = columns(warehouse);
          var columns$12 = Warehouse.hasColumns(warehouse) ? justCols(warehouse) : columnCells;
          var backups = [Optional.some(width.edge(table2))].concat(map$12(width.positions(columnCells, table2), function(pos) {
            return pos.map(function(p2) {
              return p2.x;
            });
          }));
          var colFilter = not(hasColspan);
          return map$12(columns$12, function(cellOption, c2) {
            return getDimension(cellOption, c2, backups, colFilter, function(column) {
              if (isValidColumn(column)) {
                return getWidth2(column);
              } else {
                var cell2 = bindFrom(columnCells[c2], identity);
                return getDimension(cell2, c2, backups, colFilter, function(cell3) {
                  return fallback2(Optional.some(get$8(cell3)));
                }, fallback2);
              }
            }, fallback2);
          });
        };
        var getDeduced = function(deduced) {
          return deduced.map(function(d2) {
            return d2 + "px";
          }).getOr("");
        };
        var getRawWidths = function(warehouse, table2) {
          return getWidthFrom(warehouse, table2, getRawW, getDeduced);
        };
        var getPercentageWidths = function(warehouse, table2, tableSize) {
          return getWidthFrom(warehouse, table2, getPercentageWidth, function(deduced) {
            return deduced.fold(function() {
              return tableSize.minCellWidth();
            }, function(cellWidth) {
              return cellWidth / tableSize.pixelWidth() * 100;
            });
          });
        };
        var getPixelWidths = function(warehouse, table2, tableSize) {
          return getWidthFrom(warehouse, table2, getPixelWidth$1, function(deduced) {
            return deduced.getOrThunk(tableSize.minCellWidth);
          });
        };
        var getHeightFrom = function(warehouse, table2, direction, getHeight2, fallback2) {
          var rows$12 = rows(warehouse);
          var backups = [Optional.some(direction.edge(table2))].concat(map$12(direction.positions(rows$12, table2), function(pos) {
            return pos.map(function(p2) {
              return p2.y;
            });
          }));
          return map$12(rows$12, function(cellOption, c2) {
            return getDimension(cellOption, c2, backups, not(hasRowspan), getHeight2, fallback2);
          });
        };
        var getPixelHeights = function(warehouse, table2, direction) {
          return getHeightFrom(warehouse, table2, direction, getHeight, function(deduced) {
            return deduced.getOrThunk(minHeight);
          });
        };
        var getRawHeights = function(warehouse, table2, direction) {
          return getHeightFrom(warehouse, table2, direction, getRawH, getDeduced);
        };
        var widthLookup = function(table2, getter) {
          return function() {
            if (inBody(table2)) {
              return getter(table2);
            } else {
              return parseFloat(getRaw$2(table2, "width").getOr("0"));
            }
          };
        };
        var noneSize = function(table2) {
          var getWidth2 = widthLookup(table2, get$8);
          var zero2 = constant(0);
          var getWidths = function(warehouse, tableSize) {
            return getPixelWidths(warehouse, table2, tableSize);
          };
          return {
            width: getWidth2,
            pixelWidth: getWidth2,
            getWidths,
            getCellDelta: zero2,
            singleColumnWidth: constant([0]),
            minCellWidth: zero2,
            setElementWidth: noop3,
            adjustTableWidth: noop3,
            isRelative: true,
            label: "none"
          };
        };
        var percentageSize = function(table2) {
          var getFloatWidth = widthLookup(table2, function(elem) {
            return parseFloat(getPercentTableWidth(elem));
          });
          var getWidth2 = widthLookup(table2, get$8);
          var getCellDelta = function(delta) {
            return delta / getWidth2() * 100;
          };
          var singleColumnWidth = function(w2, _delta) {
            return [100 - w2];
          };
          var minCellWidth = function() {
            return minWidth() / getWidth2() * 100;
          };
          var adjustTableWidth = function(delta) {
            var currentWidth = getFloatWidth();
            var change = delta / 100 * currentWidth;
            var newWidth = currentWidth + change;
            setPercentageWidth(table2, newWidth);
          };
          var getWidths = function(warehouse, tableSize) {
            return getPercentageWidths(warehouse, table2, tableSize);
          };
          return {
            width: getFloatWidth,
            pixelWidth: getWidth2,
            getWidths,
            getCellDelta,
            singleColumnWidth,
            minCellWidth,
            setElementWidth: setPercentageWidth,
            adjustTableWidth,
            isRelative: true,
            label: "percent"
          };
        };
        var pixelSize = function(table2) {
          var getWidth2 = widthLookup(table2, get$8);
          var getCellDelta = identity;
          var singleColumnWidth = function(w2, delta) {
            var newNext = Math.max(minWidth(), w2 + delta);
            return [newNext - w2];
          };
          var adjustTableWidth = function(delta) {
            var newWidth = getWidth2() + delta;
            setPixelWidth(table2, newWidth);
          };
          var getWidths = function(warehouse, tableSize) {
            return getPixelWidths(warehouse, table2, tableSize);
          };
          return {
            width: getWidth2,
            pixelWidth: getWidth2,
            getWidths,
            getCellDelta,
            singleColumnWidth,
            minCellWidth: minWidth,
            setElementWidth: setPixelWidth,
            adjustTableWidth,
            isRelative: false,
            label: "pixel"
          };
        };
        var chooseSize = function(element, width2) {
          var percentMatch = percentageBasedSizeRegex().exec(width2);
          if (percentMatch !== null) {
            return percentageSize(element);
          } else {
            return pixelSize(element);
          }
        };
        var getTableSize = function(table2) {
          var width2 = getRawWidth$1(table2);
          return width2.fold(function() {
            return noneSize(table2);
          }, function(w2) {
            return chooseSize(table2, w2);
          });
        };
        var TableSize = {
          getTableSize,
          pixelSize,
          percentageSize,
          noneSize
        };
        var statsStruct = function(minRow, minCol, maxRow, maxCol, allCells, selectedCells) {
          return {
            minRow,
            minCol,
            maxRow,
            maxCol,
            allCells,
            selectedCells
          };
        };
        var findSelectedStats = function(house, isSelected) {
          var totalColumns = house.grid.columns;
          var totalRows = house.grid.rows;
          var minRow = totalRows;
          var minCol = totalColumns;
          var maxRow = 0;
          var maxCol = 0;
          var allCells = [];
          var selectedCells = [];
          each$1(house.access, function(detail2) {
            allCells.push(detail2);
            if (isSelected(detail2)) {
              selectedCells.push(detail2);
              var startRow = detail2.row;
              var endRow = startRow + detail2.rowspan - 1;
              var startCol = detail2.column;
              var endCol = startCol + detail2.colspan - 1;
              if (startRow < minRow) {
                minRow = startRow;
              } else if (endRow > maxRow) {
                maxRow = endRow;
              }
              if (startCol < minCol) {
                minCol = startCol;
              } else if (endCol > maxCol) {
                maxCol = endCol;
              }
            }
          });
          return statsStruct(minRow, minCol, maxRow, maxCol, allCells, selectedCells);
        };
        var makeCell = function(list, seenSelected, rowIndex) {
          var row2 = list[rowIndex].element;
          var td = SugarElement.fromTag("td");
          append$1(td, SugarElement.fromTag("br"));
          var f2 = seenSelected ? append$1 : prepend;
          f2(row2, td);
        };
        var fillInGaps = function(list, house, stats, isSelected) {
          var totalColumns = house.grid.columns;
          var totalRows = house.grid.rows;
          for (var i2 = 0; i2 < totalRows; i2++) {
            var seenSelected = false;
            for (var j2 = 0; j2 < totalColumns; j2++) {
              if (!(i2 < stats.minRow || i2 > stats.maxRow || j2 < stats.minCol || j2 > stats.maxCol)) {
                var needCell = Warehouse.getAt(house, i2, j2).filter(isSelected).isNone();
                if (needCell) {
                  makeCell(list, seenSelected, i2);
                } else {
                  seenSelected = true;
                }
              }
            }
          }
        };
        var clean = function(replica, stats, house, widthDelta) {
          each$1(house.columns, function(col2) {
            if (col2.column < stats.minCol || col2.column > stats.maxCol) {
              remove$5(col2.element);
            }
          });
          var emptyRows = filter$2(firstLayer(replica, "tr"), function(row2) {
            return row2.dom.childElementCount === 0;
          });
          each$2(emptyRows, remove$5);
          if (stats.minCol === stats.maxCol || stats.minRow === stats.maxRow) {
            each$2(firstLayer(replica, "th,td"), function(cell2) {
              remove$7(cell2, "rowspan");
              remove$7(cell2, "colspan");
            });
          }
          remove$7(replica, LOCKED_COL_ATTR);
          remove$7(replica, "data-snooker-col-series");
          var tableSize = TableSize.getTableSize(replica);
          tableSize.adjustTableWidth(widthDelta);
        };
        var getTableWidthDelta = function(table2, warehouse, tableSize, stats) {
          if (stats.minCol === 0 && warehouse.grid.columns === stats.maxCol + 1) {
            return 0;
          }
          var colWidths = getPixelWidths(warehouse, table2, tableSize);
          var allColsWidth = foldl(colWidths, function(acc, width2) {
            return acc + width2;
          }, 0);
          var selectedColsWidth = foldl(colWidths.slice(stats.minCol, stats.maxCol + 1), function(acc, width2) {
            return acc + width2;
          }, 0);
          var newWidth = selectedColsWidth / allColsWidth * tableSize.pixelWidth();
          var delta = newWidth - tableSize.pixelWidth();
          return tableSize.getCellDelta(delta);
        };
        var extract$1 = function(table2, selectedSelector) {
          var isSelected = function(detail2) {
            return is$2(detail2.element, selectedSelector);
          };
          var replica = deep(table2);
          var list = fromTable$1(replica);
          var tableSize = TableSize.getTableSize(table2);
          var replicaHouse = Warehouse.generate(list);
          var replicaStats = findSelectedStats(replicaHouse, isSelected);
          var selector = "th:not(" + selectedSelector + "),td:not(" + selectedSelector + ")";
          var unselectedCells = filterFirstLayer(replica, "th,td", function(cell2) {
            return is$2(cell2, selector);
          });
          each$2(unselectedCells, remove$5);
          fillInGaps(list, replicaHouse, replicaStats, isSelected);
          var house = Warehouse.fromTable(table2);
          var widthDelta = getTableWidthDelta(table2, house, tableSize, replicaStats);
          clean(replica, replicaStats, replicaHouse, widthDelta);
          return replica;
        };
        var nbsp = "\xA0";
        var getEnd = function(element) {
          return name(element) === "img" ? 1 : getOption(element).fold(function() {
            return children$3(element).length;
          }, function(v2) {
            return v2.length;
          });
        };
        var isTextNodeWithCursorPosition = function(el) {
          return getOption(el).filter(function(text) {
            return text.trim().length !== 0 || text.indexOf(nbsp) > -1;
          }).isSome();
        };
        var elementsWithCursorPosition = [
          "img",
          "br"
        ];
        var isCursorPosition = function(elem) {
          var hasCursorPosition = isTextNodeWithCursorPosition(elem);
          return hasCursorPosition || contains$2(elementsWithCursorPosition, name(elem));
        };
        var first = function(element) {
          return descendant$1(element, isCursorPosition);
        };
        var last$1 = function(element) {
          return descendantRtl(element, isCursorPosition);
        };
        var descendantRtl = function(scope, predicate) {
          var descend = function(element) {
            var children2 = children$3(element);
            for (var i2 = children2.length - 1; i2 >= 0; i2--) {
              var child2 = children2[i2];
              if (predicate(child2)) {
                return Optional.some(child2);
              }
              var res = descend(child2);
              if (res.isSome()) {
                return res;
              }
            }
            return Optional.none();
          };
          return descend(scope);
        };
        var transferableAttributes = {
          scope: [
            "row",
            "col"
          ]
        };
        var createCell = function(doc) {
          return function() {
            var td = SugarElement.fromTag("td", doc.dom);
            append$1(td, SugarElement.fromTag("br", doc.dom));
            return td;
          };
        };
        var createCol = function(doc) {
          return function() {
            return SugarElement.fromTag("col", doc.dom);
          };
        };
        var createColgroup = function(doc) {
          return function() {
            return SugarElement.fromTag("colgroup", doc.dom);
          };
        };
        var createRow$1 = function(doc) {
          return function() {
            return SugarElement.fromTag("tr", doc.dom);
          };
        };
        var replace$1 = function(cell2, tag, attrs) {
          var replica = copy$1(cell2, tag);
          each$1(attrs, function(v2, k2) {
            if (v2 === null) {
              remove$7(replica, k2);
            } else {
              set$2(replica, k2, v2);
            }
          });
          return replica;
        };
        var pasteReplace = function(cell2) {
          return cell2;
        };
        var cloneFormats = function(oldCell, newCell, formats) {
          var first$1 = first(oldCell);
          return first$1.map(function(firstText) {
            var formatSelector = formats.join(",");
            var parents2 = ancestors$3(firstText, formatSelector, function(element) {
              return eq$1(element, oldCell);
            });
            return foldr(parents2, function(last2, parent2) {
              var clonedFormat = shallow(parent2);
              remove$7(clonedFormat, "contenteditable");
              append$1(last2, clonedFormat);
              return clonedFormat;
            }, newCell);
          }).getOr(newCell);
        };
        var cloneAppropriateAttributes = function(original, clone3) {
          each$1(transferableAttributes, function(validAttributes, attributeName) {
            return getOpt(original, attributeName).filter(function(attribute) {
              return contains$2(validAttributes, attribute);
            }).each(function(attribute) {
              return set$2(clone3, attributeName, attribute);
            });
          });
        };
        var cellOperations = function(mutate2, doc, formatsToClone) {
          var cloneCss = function(prev2, clone3) {
            copy$2(prev2.element, clone3);
            remove$6(clone3, "height");
            if (prev2.colspan !== 1) {
              remove$6(clone3, "width");
            }
          };
          var newCell = function(prev2) {
            var td = SugarElement.fromTag(name(prev2.element), doc.dom);
            var formats = formatsToClone.getOr([
              "strong",
              "em",
              "b",
              "i",
              "span",
              "font",
              "h1",
              "h2",
              "h3",
              "h4",
              "h5",
              "h6",
              "p",
              "div"
            ]);
            var lastNode = formats.length > 0 ? cloneFormats(prev2.element, td, formats) : td;
            append$1(lastNode, SugarElement.fromTag("br"));
            cloneCss(prev2, td);
            cloneAppropriateAttributes(prev2.element, td);
            mutate2(prev2.element, td);
            return td;
          };
          var newCol = function(prev2) {
            var col2 = SugarElement.fromTag(name(prev2.element), doc.dom);
            cloneCss(prev2, col2);
            mutate2(prev2.element, col2);
            return col2;
          };
          return {
            col: newCol,
            colgroup: createColgroup(doc),
            row: createRow$1(doc),
            cell: newCell,
            replace: replace$1,
            colGap: createCol(doc),
            gap: createCell(doc)
          };
        };
        var paste$1 = function(doc) {
          return {
            col: createCol(doc),
            colgroup: createColgroup(doc),
            row: createRow$1(doc),
            cell: createCell(doc),
            replace: pasteReplace,
            colGap: createCol(doc),
            gap: createCell(doc)
          };
        };
        var fromHtml = function(html, scope) {
          var doc = scope || document;
          var div = doc.createElement("div");
          div.innerHTML = html;
          return children$3(SugarElement.fromDom(div));
        };
        var fromDom = function(nodes) {
          return map$12(nodes, SugarElement.fromDom);
        };
        var getNodeName2 = function(elm) {
          return elm.nodeName.toLowerCase();
        };
        var getBody = function(editor) {
          return SugarElement.fromDom(editor.getBody());
        };
        var getPixelWidth = function(elm) {
          return elm.getBoundingClientRect().width;
        };
        var getPixelHeight = function(elm) {
          return elm.getBoundingClientRect().height;
        };
        var getIsRoot = function(editor) {
          return function(element) {
            return eq$1(element, getBody(editor));
          };
        };
        var removePxSuffix = function(size2) {
          return size2 ? size2.replace(/px$/, "") : "";
        };
        var addPxSuffix = function(size2) {
          return /^\d+(\.\d+)?$/.test(size2) ? size2 + "px" : size2;
        };
        var removeDataStyle = function(table2) {
          remove$7(table2, "data-mce-style");
          var removeStyleAttribute = function(element) {
            return remove$7(element, "data-mce-style");
          };
          each$2(cells$1(table2), removeStyleAttribute);
          each$2(columns$1(table2), removeStyleAttribute);
          each$2(rows$1(table2), removeStyleAttribute);
        };
        var getRawWidth = function(editor, elm) {
          var raw = editor.dom.getStyle(elm, "width") || editor.dom.getAttrib(elm, "width");
          return Optional.from(raw).filter(isNotEmpty);
        };
        var isPercentage$1 = function(value2) {
          return /^(\d+(\.\d+)?)%$/.test(value2);
        };
        var isPixel = function(value2) {
          return /^(\d+(\.\d+)?)px$/.test(value2);
        };
        var getSelectionStart = function(editor) {
          return SugarElement.fromDom(editor.selection.getStart());
        };
        var getSelectionEnd = function(editor) {
          return SugarElement.fromDom(editor.selection.getEnd());
        };
        var selection = function(selections) {
          return cata$2(selections.get(), constant([]), identity, pure);
        };
        var unmergable = function(selections) {
          var hasSpan = function(elem, type2) {
            return getOpt(elem, type2).exists(function(span) {
              return parseInt(span, 10) > 1;
            });
          };
          var hasRowOrColSpan = function(elem) {
            return hasSpan(elem, "rowspan") || hasSpan(elem, "colspan");
          };
          var candidates = selection(selections);
          return candidates.length > 0 && forall(candidates, hasRowOrColSpan) ? Optional.some(candidates) : Optional.none();
        };
        var mergable = function(table2, selections, ephemera2) {
          return cata$2(selections.get(), Optional.none, function(cells2) {
            if (cells2.length <= 1) {
              return Optional.none();
            } else {
              return retrieveBox(table2, ephemera2.firstSelectedSelector, ephemera2.lastSelectedSelector).map(function(bounds2) {
                return {
                  bounds: bounds2,
                  cells: cells2
                };
              });
            }
          }, Optional.none);
        };
        var strSelected = "data-mce-selected";
        var strSelectedSelector = "td[" + strSelected + "],th[" + strSelected + "]";
        var strAttributeSelector = "[" + strSelected + "]";
        var strFirstSelected = "data-mce-first-selected";
        var strFirstSelectedSelector = "td[" + strFirstSelected + "],th[" + strFirstSelected + "]";
        var strLastSelected = "data-mce-last-selected";
        var strLastSelectedSelector = "td[" + strLastSelected + "],th[" + strLastSelected + "]";
        var attributeSelector = strAttributeSelector;
        var ephemera = {
          selected: strSelected,
          selectedSelector: strSelectedSelector,
          firstSelected: strFirstSelected,
          firstSelectedSelector: strFirstSelectedSelector,
          lastSelected: strLastSelected,
          lastSelectedSelector: strLastSelectedSelector
        };
        var noMenu = function(cell2) {
          return {
            element: cell2,
            mergable: Optional.none(),
            unmergable: Optional.none(),
            selection: [cell2]
          };
        };
        var forMenu = function(selections, table2, cell2) {
          return {
            element: cell2,
            mergable: mergable(table2, selections, ephemera),
            unmergable: unmergable(selections),
            selection: selection(selections)
          };
        };
        var paste = function(element, clipboard, generators) {
          return {
            element,
            clipboard,
            generators
          };
        };
        var pasteRows = function(selections, cell2, clipboard, generators) {
          return {
            selection: selection(selections),
            clipboard,
            generators
          };
        };
        var getSelectionCellFallback = function(element) {
          return table(element).bind(function(table2) {
            return retrieve(table2, ephemera.firstSelectedSelector);
          }).fold(constant(element), function(cells2) {
            return cells2[0];
          });
        };
        var getSelectionFromSelector = function(selector) {
          return function(initCell, isRoot) {
            var cellName = name(initCell);
            var cell2 = cellName === "col" || cellName === "colgroup" ? getSelectionCellFallback(initCell) : initCell;
            return closest$1(cell2, selector, isRoot);
          };
        };
        var getSelectionCellOrCaption = getSelectionFromSelector("th,td,caption");
        var getSelectionCell = getSelectionFromSelector("th,td");
        var getCellsFromSelection = function(selections) {
          return selection(selections);
        };
        var getRowsFromSelection = function(selected, selector) {
          var cellOpt = getSelectionCell(selected);
          var rowsOpt = cellOpt.bind(function(cell2) {
            return table(cell2);
          }).map(function(table2) {
            return rows$1(table2);
          });
          return lift2(cellOpt, rowsOpt, function(cell2, rows2) {
            return filter$2(rows2, function(row2) {
              return exists(fromDom(row2.dom.cells), function(rowCell) {
                return get$b(rowCell, selector) === "1" || eq$1(rowCell, cell2);
              });
            });
          }).getOr([]);
        };
        var extractSelected = function(cells2) {
          return table(cells2[0]).map(function(table2) {
            var replica = extract$1(table2, attributeSelector);
            removeDataStyle(replica);
            return [replica];
          });
        };
        var serializeElements = function(editor, elements2) {
          return map$12(elements2, function(elm) {
            return editor.selection.serializer.serialize(elm.dom, {});
          }).join("");
        };
        var getTextContent = function(elements2) {
          return map$12(elements2, function(element) {
            return element.dom.innerText;
          }).join("");
        };
        var registerEvents = function(editor, selections, actions) {
          editor.on("BeforeGetContent", function(e2) {
            var multiCellContext = function(cells2) {
              e2.preventDefault();
              extractSelected(cells2).each(function(elements2) {
                e2.content = e2.format === "text" ? getTextContent(elements2) : serializeElements(editor, elements2);
              });
            };
            if (e2.selection === true) {
              cata$2(selections.get(), noop3, multiCellContext, noop3);
            }
          });
          editor.on("BeforeSetContent", function(e2) {
            if (e2.selection === true && e2.paste === true) {
              var selectedCells = getCellsFromSelection(selections);
              head(selectedCells).each(function(cell2) {
                table(cell2).each(function(table2) {
                  var elements2 = filter$2(fromHtml(e2.content), function(content) {
                    return name(content) !== "meta";
                  });
                  var isTable = isTag("table");
                  if (elements2.length === 1 && isTable(elements2[0])) {
                    e2.preventDefault();
                    var doc = SugarElement.fromDom(editor.getDoc());
                    var generators = paste$1(doc);
                    var targets = paste(cell2, elements2[0], generators);
                    actions.pasteCells(table2, targets).each(function() {
                      editor.focus();
                    });
                  }
                });
              });
            }
          });
        };
        var adt$7 = Adt.generate([
          { none: [] },
          { only: ["index"] },
          {
            left: [
              "index",
              "next"
            ]
          },
          {
            middle: [
              "prev",
              "index",
              "next"
            ]
          },
          {
            right: [
              "prev",
              "index"
            ]
          }
        ]);
        var ColumnContext = __assign({}, adt$7);
        var neighbours = function(input, index) {
          if (input.length === 0) {
            return ColumnContext.none();
          }
          if (input.length === 1) {
            return ColumnContext.only(0);
          }
          if (index === 0) {
            return ColumnContext.left(0, 1);
          }
          if (index === input.length - 1) {
            return ColumnContext.right(index - 1, index);
          }
          if (index > 0 && index < input.length - 1) {
            return ColumnContext.middle(index - 1, index, index + 1);
          }
          return ColumnContext.none();
        };
        var determine = function(input, column, step, tableSize, resize2) {
          var result = input.slice(0);
          var context = neighbours(input, column);
          var onNone = constant(map$12(result, constant(0)));
          var onOnly = function(index) {
            return tableSize.singleColumnWidth(result[index], step);
          };
          var onLeft = function(index, next2) {
            return resize2.calcLeftEdgeDeltas(result, index, next2, step, tableSize.minCellWidth(), tableSize.isRelative);
          };
          var onMiddle = function(prev2, index, next2) {
            return resize2.calcMiddleDeltas(result, prev2, index, next2, step, tableSize.minCellWidth(), tableSize.isRelative);
          };
          var onRight = function(prev2, index) {
            return resize2.calcRightEdgeDeltas(result, prev2, index, step, tableSize.minCellWidth(), tableSize.isRelative);
          };
          return context.fold(onNone, onOnly, onLeft, onMiddle, onRight);
        };
        var total = function(start4, end2, measures) {
          var r3 = 0;
          for (var i2 = start4; i2 < end2; i2++) {
            r3 += measures[i2] !== void 0 ? measures[i2] : 0;
          }
          return r3;
        };
        var recalculateWidthForCells = function(warehouse, widths) {
          var all2 = Warehouse.justCells(warehouse);
          return map$12(all2, function(cell2) {
            var width2 = total(cell2.column, cell2.column + cell2.colspan, widths);
            return {
              element: cell2.element,
              width: width2,
              colspan: cell2.colspan
            };
          });
        };
        var recalculateWidthForColumns = function(warehouse, widths) {
          var groups = Warehouse.justColumns(warehouse);
          return map$12(groups, function(column, index) {
            return {
              element: column.element,
              width: widths[index],
              colspan: column.colspan
            };
          });
        };
        var recalculateHeightForCells = function(warehouse, heights) {
          var all2 = Warehouse.justCells(warehouse);
          return map$12(all2, function(cell2) {
            var height2 = total(cell2.row, cell2.row + cell2.rowspan, heights);
            return {
              element: cell2.element,
              height: height2,
              rowspan: cell2.rowspan
            };
          });
        };
        var matchRowHeight = function(warehouse, heights) {
          return map$12(warehouse.all, function(row2, i2) {
            return {
              element: row2.element,
              height: heights[i2]
            };
          });
        };
        var sumUp = function(newSize) {
          return foldr(newSize, function(b2, a2) {
            return b2 + a2;
          }, 0);
        };
        var recalculate = function(warehouse, widths) {
          if (Warehouse.hasColumns(warehouse)) {
            return recalculateWidthForColumns(warehouse, widths);
          } else {
            return recalculateWidthForCells(warehouse, widths);
          }
        };
        var recalculateAndApply = function(warehouse, widths, tableSize) {
          var newSizes = recalculate(warehouse, widths);
          each$2(newSizes, function(cell2) {
            tableSize.setElementWidth(cell2.element, cell2.width);
          });
        };
        var adjustWidth = function(table2, delta, index, resizing, tableSize) {
          var warehouse = Warehouse.fromTable(table2);
          var step = tableSize.getCellDelta(delta);
          var widths = tableSize.getWidths(warehouse, tableSize);
          var isLastColumn = index === warehouse.grid.columns - 1;
          var clampedStep = resizing.clampTableDelta(widths, index, step, tableSize.minCellWidth(), isLastColumn);
          var deltas = determine(widths, index, clampedStep, tableSize, resizing);
          var newWidths = map$12(deltas, function(dx, i2) {
            return dx + widths[i2];
          });
          recalculateAndApply(warehouse, newWidths, tableSize);
          resizing.resizeTable(tableSize.adjustTableWidth, clampedStep, isLastColumn);
        };
        var adjustHeight = function(table2, delta, index, direction) {
          var warehouse = Warehouse.fromTable(table2);
          var heights = getPixelHeights(warehouse, table2, direction);
          var newHeights = map$12(heights, function(dy, i2) {
            return index === i2 ? Math.max(delta + dy, minHeight()) : dy;
          });
          var newCellSizes = recalculateHeightForCells(warehouse, newHeights);
          var newRowSizes = matchRowHeight(warehouse, newHeights);
          each$2(newRowSizes, function(row2) {
            setHeight(row2.element, row2.height);
          });
          each$2(newCellSizes, function(cell2) {
            setHeight(cell2.element, cell2.height);
          });
          var total2 = sumUp(newHeights);
          setHeight(table2, total2);
        };
        var adjustAndRedistributeWidths$1 = function(_table, list, details, tableSize, resizeBehaviour) {
          var warehouse = Warehouse.generate(list);
          var sizes = tableSize.getWidths(warehouse, tableSize);
          var tablePixelWidth = tableSize.pixelWidth();
          var _a = resizeBehaviour.calcRedestributedWidths(sizes, tablePixelWidth, details.pixelDelta, tableSize.isRelative), newSizes = _a.newSizes, delta = _a.delta;
          recalculateAndApply(warehouse, newSizes, tableSize);
          tableSize.adjustTableWidth(delta);
        };
        var adjustWidthTo = function(_table, list, _info, tableSize) {
          var warehouse = Warehouse.generate(list);
          var widths = tableSize.getWidths(warehouse, tableSize);
          recalculateAndApply(warehouse, widths, tableSize);
        };
        var zero = function(array) {
          return map$12(array, constant(0));
        };
        var surround = function(sizes, startIndex, endIndex, results, f2) {
          return f2(sizes.slice(0, startIndex)).concat(results).concat(f2(sizes.slice(endIndex)));
        };
        var clampDeltaHelper = function(predicate) {
          return function(sizes, index, delta, minCellSize) {
            if (!predicate(delta)) {
              return delta;
            } else {
              var newSize = Math.max(minCellSize, sizes[index] - Math.abs(delta));
              var diff = Math.abs(newSize - sizes[index]);
              return delta >= 0 ? diff : -diff;
            }
          };
        };
        var clampNegativeDelta = clampDeltaHelper(function(delta) {
          return delta < 0;
        });
        var clampDelta = clampDeltaHelper(always);
        var resizeTable = function() {
          var calcFixedDeltas = function(sizes, index, next2, delta, minCellSize) {
            var clampedDelta = clampNegativeDelta(sizes, index, delta, minCellSize);
            return surround(sizes, index, next2 + 1, [
              clampedDelta,
              0
            ], zero);
          };
          var calcRelativeDeltas = function(sizes, index, delta, minCellSize) {
            var ratio = (100 + delta) / 100;
            var newThis = Math.max(minCellSize, (sizes[index] + delta) / ratio);
            return map$12(sizes, function(size2, idx) {
              var newSize = idx === index ? newThis : size2 / ratio;
              return newSize - size2;
            });
          };
          var calcLeftEdgeDeltas = function(sizes, index, next2, delta, minCellSize, isRelative) {
            if (isRelative) {
              return calcRelativeDeltas(sizes, index, delta, minCellSize);
            } else {
              return calcFixedDeltas(sizes, index, next2, delta, minCellSize);
            }
          };
          var calcMiddleDeltas = function(sizes, _prev, index, next2, delta, minCellSize, isRelative) {
            return calcLeftEdgeDeltas(sizes, index, next2, delta, minCellSize, isRelative);
          };
          var resizeTable2 = function(resizer, delta) {
            return resizer(delta);
          };
          var calcRightEdgeDeltas = function(sizes, _prev, index, delta, minCellSize, isRelative) {
            if (isRelative) {
              return calcRelativeDeltas(sizes, index, delta, minCellSize);
            } else {
              var clampedDelta = clampNegativeDelta(sizes, index, delta, minCellSize);
              return zero(sizes.slice(0, index)).concat([clampedDelta]);
            }
          };
          var calcRedestributedWidths = function(sizes, totalWidth, pixelDelta, isRelative) {
            if (isRelative) {
              var tableWidth = totalWidth + pixelDelta;
              var ratio_1 = tableWidth / totalWidth;
              var newSizes = map$12(sizes, function(size2) {
                return size2 / ratio_1;
              });
              return {
                delta: ratio_1 * 100 - 100,
                newSizes
              };
            } else {
              return {
                delta: pixelDelta,
                newSizes: sizes
              };
            }
          };
          return {
            resizeTable: resizeTable2,
            clampTableDelta: clampNegativeDelta,
            calcLeftEdgeDeltas,
            calcMiddleDeltas,
            calcRightEdgeDeltas,
            calcRedestributedWidths
          };
        };
        var preserveTable = function() {
          var calcLeftEdgeDeltas = function(sizes, index, next2, delta, minCellSize) {
            var idx = delta >= 0 ? next2 : index;
            var clampedDelta = clampDelta(sizes, idx, delta, minCellSize);
            return surround(sizes, index, next2 + 1, [
              clampedDelta,
              -clampedDelta
            ], zero);
          };
          var calcMiddleDeltas = function(sizes, _prev, index, next2, delta, minCellSize) {
            return calcLeftEdgeDeltas(sizes, index, next2, delta, minCellSize);
          };
          var resizeTable2 = function(resizer, delta, isLastColumn) {
            if (isLastColumn) {
              resizer(delta);
            }
          };
          var calcRightEdgeDeltas = function(sizes, _prev, _index, delta, _minCellSize, isRelative) {
            if (isRelative) {
              return zero(sizes);
            } else {
              var diff = delta / sizes.length;
              return map$12(sizes, constant(diff));
            }
          };
          var clampTableDelta = function(sizes, index, delta, minCellSize, isLastColumn) {
            if (isLastColumn) {
              if (delta >= 0) {
                return delta;
              } else {
                var maxDelta = foldl(sizes, function(a2, b2) {
                  return a2 + b2 - minCellSize;
                }, 0);
                return Math.max(-maxDelta, delta);
              }
            } else {
              return clampNegativeDelta(sizes, index, delta, minCellSize);
            }
          };
          var calcRedestributedWidths = function(sizes, _totalWidth, _pixelDelta, _isRelative) {
            return {
              delta: 0,
              newSizes: sizes
            };
          };
          return {
            resizeTable: resizeTable2,
            clampTableDelta,
            calcLeftEdgeDeltas,
            calcMiddleDeltas,
            calcRightEdgeDeltas,
            calcRedestributedWidths
          };
        };
        var only = function(element, isResizable2) {
          var parent2 = Optional.from(element.dom.documentElement).map(SugarElement.fromDom).getOr(element);
          return {
            parent: constant(parent2),
            view: constant(element),
            origin: constant(SugarPosition(0, 0)),
            isResizable: isResizable2
          };
        };
        var detached = function(editable, chrome2, isResizable2) {
          var origin = function() {
            return absolute(chrome2);
          };
          return {
            parent: constant(chrome2),
            view: constant(editable),
            origin,
            isResizable: isResizable2
          };
        };
        var body = function(editable, chrome2, isResizable2) {
          return {
            parent: constant(chrome2),
            view: constant(editable),
            origin: constant(SugarPosition(0, 0)),
            isResizable: isResizable2
          };
        };
        var ResizeWire = {
          only,
          detached,
          body
        };
        var adt$6 = Adt.generate([
          { invalid: ["raw"] },
          { pixels: ["value"] },
          { percent: ["value"] }
        ]);
        var validateFor = function(suffix, type2, value2) {
          var rawAmount = value2.substring(0, value2.length - suffix.length);
          var amount = parseFloat(rawAmount);
          return rawAmount === amount.toString() ? type2(amount) : adt$6.invalid(value2);
        };
        var from = function(value2) {
          if (endsWith(value2, "%")) {
            return validateFor("%", adt$6.percent, value2);
          }
          if (endsWith(value2, "px")) {
            return validateFor("px", adt$6.pixels, value2);
          }
          return adt$6.invalid(value2);
        };
        var Size = __assign(__assign({}, adt$6), { from });
        var redistributeToPercent = function(widths, totalWidth) {
          return map$12(widths, function(w2) {
            var colType = Size.from(w2);
            return colType.fold(function() {
              return w2;
            }, function(px) {
              var ratio = px / totalWidth * 100;
              return ratio + "%";
            }, function(pc) {
              return pc + "%";
            });
          });
        };
        var redistributeToPx = function(widths, totalWidth, newTotalWidth) {
          var scale = newTotalWidth / totalWidth;
          return map$12(widths, function(w2) {
            var colType = Size.from(w2);
            return colType.fold(function() {
              return w2;
            }, function(px) {
              return px * scale + "px";
            }, function(pc) {
              return pc / 100 * newTotalWidth + "px";
            });
          });
        };
        var redistributeEmpty = function(newWidthType, columns2) {
          var f2 = newWidthType.fold(function() {
            return constant("");
          }, function(pixels) {
            var num = pixels / columns2;
            return constant(num + "px");
          }, function() {
            var num = 100 / columns2;
            return constant(num + "%");
          });
          return range$1(columns2, f2);
        };
        var redistributeValues = function(newWidthType, widths, totalWidth) {
          return newWidthType.fold(function() {
            return widths;
          }, function(px) {
            return redistributeToPx(widths, totalWidth, px);
          }, function(_pc) {
            return redistributeToPercent(widths, totalWidth);
          });
        };
        var redistribute$1 = function(widths, totalWidth, newWidth) {
          var newType = Size.from(newWidth);
          var floats = forall(widths, function(s2) {
            return s2 === "0px";
          }) ? redistributeEmpty(newType, widths.length) : redistributeValues(newType, widths, totalWidth);
          return normalize(floats);
        };
        var sum = function(values2, fallback2) {
          if (values2.length === 0) {
            return fallback2;
          }
          return foldr(values2, function(rest, v2) {
            return Size.from(v2).fold(constant(0), identity, identity) + rest;
          }, 0);
        };
        var roundDown = function(num, unit) {
          var floored = Math.floor(num);
          return {
            value: floored + unit,
            remainder: num - floored
          };
        };
        var add$3 = function(value2, amount) {
          return Size.from(value2).fold(constant(value2), function(px) {
            return px + amount + "px";
          }, function(pc) {
            return pc + amount + "%";
          });
        };
        var normalize = function(values2) {
          if (values2.length === 0) {
            return values2;
          }
          var scan2 = foldr(values2, function(rest, value2) {
            var info = Size.from(value2).fold(function() {
              return {
                value: value2,
                remainder: 0
              };
            }, function(num) {
              return roundDown(num, "px");
            }, function(num) {
              return {
                value: num + "%",
                remainder: 0
              };
            });
            return {
              output: [info.value].concat(rest.output),
              remainder: rest.remainder + info.remainder
            };
          }, {
            output: [],
            remainder: 0
          });
          var r3 = scan2.output;
          return r3.slice(0, r3.length - 1).concat([add$3(r3[r3.length - 1], Math.round(scan2.remainder))]);
        };
        var validate = Size.from;
        var redistributeToW = function(newWidths, cells2, unit) {
          each$2(cells2, function(cell2) {
            var widths = newWidths.slice(cell2.column, cell2.colspan + cell2.column);
            var w2 = sum(widths, minWidth());
            set$1(cell2.element, "width", w2 + unit);
          });
        };
        var redistributeToColumns = function(newWidths, columns2, unit) {
          each$2(columns2, function(column, index) {
            var width2 = sum([newWidths[index]], minWidth());
            set$1(column.element, "width", width2 + unit);
          });
        };
        var redistributeToH = function(newHeights, rows2, cells2, unit) {
          each$2(cells2, function(cell2) {
            var heights = newHeights.slice(cell2.row, cell2.rowspan + cell2.row);
            var h3 = sum(heights, minHeight());
            set$1(cell2.element, "height", h3 + unit);
          });
          each$2(rows2, function(row2, i2) {
            set$1(row2.element, "height", newHeights[i2]);
          });
        };
        var getUnit = function(newSize) {
          return validate(newSize).fold(constant("px"), constant("px"), constant("%"));
        };
        var redistribute = function(table2, optWidth, optHeight) {
          var warehouse = Warehouse.fromTable(table2);
          var rows2 = warehouse.all;
          var cells2 = Warehouse.justCells(warehouse);
          var columns2 = Warehouse.justColumns(warehouse);
          optWidth.each(function(newWidth) {
            var widthUnit = getUnit(newWidth);
            var totalWidth = get$8(table2);
            var oldWidths = getRawWidths(warehouse, table2);
            var nuWidths = redistribute$1(oldWidths, totalWidth, newWidth);
            if (Warehouse.hasColumns(warehouse)) {
              redistributeToColumns(nuWidths, columns2, widthUnit);
            } else {
              redistributeToW(nuWidths, cells2, widthUnit);
            }
            set$1(table2, "width", newWidth);
          });
          optHeight.each(function(newHeight) {
            var hUnit = getUnit(newHeight);
            var totalHeight = get$7(table2);
            var oldHeights = getRawHeights(warehouse, table2, height);
            var nuHeights = redistribute$1(oldHeights, totalHeight, newHeight);
            redistributeToH(nuHeights, rows2, cells2, hUnit);
            set$1(table2, "height", newHeight);
          });
        };
        var isPercentSizing = isPercentSizing$1;
        var isPixelSizing = isPixelSizing$1;
        var isNoneSizing = isNoneSizing$1;
        var getGridSize = function(table2) {
          var warehouse = Warehouse.fromTable(table2);
          return warehouse.grid;
        };
        var Event2 = function(fields) {
          var handlers = [];
          var bind2 = function(handler) {
            if (handler === void 0) {
              throw new Error("Event bind error: undefined handler");
            }
            handlers.push(handler);
          };
          var unbind2 = function(handler) {
            handlers = filter$2(handlers, function(h3) {
              return h3 !== handler;
            });
          };
          var trigger = function() {
            var args = [];
            for (var _i2 = 0; _i2 < arguments.length; _i2++) {
              args[_i2] = arguments[_i2];
            }
            var event = {};
            each$2(fields, function(name2, i2) {
              event[name2] = args[i2];
            });
            each$2(handlers, function(handler) {
              handler(event);
            });
          };
          return {
            bind: bind2,
            unbind: unbind2,
            trigger
          };
        };
        var create$4 = function(typeDefs) {
          var registry2 = map3(typeDefs, function(event) {
            return {
              bind: event.bind,
              unbind: event.unbind
            };
          });
          var trigger = map3(typeDefs, function(event) {
            return event.trigger;
          });
          return {
            registry: registry2,
            trigger
          };
        };
        var last = function(fn3, rate) {
          var timer = null;
          var cancel = function() {
            if (!isNull(timer)) {
              clearTimeout(timer);
              timer = null;
            }
          };
          var throttle = function() {
            var args = [];
            for (var _i2 = 0; _i2 < arguments.length; _i2++) {
              args[_i2] = arguments[_i2];
            }
            cancel();
            timer = setTimeout(function() {
              timer = null;
              fn3.apply(null, args);
            }, rate);
          };
          return {
            cancel,
            throttle
          };
        };
        var sort = function(arr) {
          return arr.slice(0).sort();
        };
        var reqMessage = function(required, keys2) {
          throw new Error("All required keys (" + sort(required).join(", ") + ") were not specified. Specified keys were: " + sort(keys2).join(", ") + ".");
        };
        var unsuppMessage = function(unsupported) {
          throw new Error("Unsupported keys for object: " + sort(unsupported).join(", "));
        };
        var validateStrArr = function(label, array) {
          if (!isArray2(array)) {
            throw new Error("The " + label + " fields must be an array. Was: " + array + ".");
          }
          each$2(array, function(a2) {
            if (!isString(a2)) {
              throw new Error("The value " + a2 + " in the " + label + " fields was not a string.");
            }
          });
        };
        var invalidTypeMessage = function(incorrect, type2) {
          throw new Error("All values need to be of type: " + type2 + ". Keys (" + sort(incorrect).join(", ") + ") were not.");
        };
        var checkDupes = function(everything) {
          var sorted = sort(everything);
          var dupe = find$1(sorted, function(s2, i2) {
            return i2 < sorted.length - 1 && s2 === sorted[i2 + 1];
          });
          dupe.each(function(d2) {
            throw new Error("The field: " + d2 + " occurs more than once in the combined fields: [" + sorted.join(", ") + "].");
          });
        };
        var base = function(handleUnsupported, required) {
          return baseWith(handleUnsupported, required, {
            validate: isFunction2,
            label: "function"
          });
        };
        var baseWith = function(handleUnsupported, required, pred) {
          if (required.length === 0) {
            throw new Error("You must specify at least one required field.");
          }
          validateStrArr("required", required);
          checkDupes(required);
          return function(obj) {
            var keys$1 = keys(obj);
            var allReqd = forall(required, function(req) {
              return contains$2(keys$1, req);
            });
            if (!allReqd) {
              reqMessage(required, keys$1);
            }
            handleUnsupported(required, keys$1);
            var invalidKeys = filter$2(required, function(key2) {
              return !pred.validate(obj[key2], key2);
            });
            if (invalidKeys.length > 0) {
              invalidTypeMessage(invalidKeys, pred.label);
            }
            return obj;
          };
        };
        var handleExact = function(required, keys2) {
          var unsupported = filter$2(keys2, function(key2) {
            return !contains$2(required, key2);
          });
          if (unsupported.length > 0) {
            unsuppMessage(unsupported);
          }
        };
        var exactly = function(required) {
          return base(handleExact, required);
        };
        var DragMode = exactly([
          "compare",
          "extract",
          "mutate",
          "sink"
        ]);
        var DragSink = exactly([
          "element",
          "start",
          "stop",
          "destroy"
        ]);
        var DragApi = exactly([
          "forceDrop",
          "drop",
          "move",
          "delayDrop"
        ]);
        var InDrag = function() {
          var previous = Optional.none();
          var reset = function() {
            previous = Optional.none();
          };
          var update2 = function(mode, nu2) {
            var result = previous.map(function(old) {
              return mode.compare(old, nu2);
            });
            previous = Optional.some(nu2);
            return result;
          };
          var onEvent = function(event, mode) {
            var dataOption = mode.extract(event);
            dataOption.each(function(data) {
              var offset2 = update2(mode, data);
              offset2.each(function(d2) {
                events.trigger.move(d2);
              });
            });
          };
          var events = create$4({ move: Event2(["info"]) });
          return {
            onEvent,
            reset,
            events: events.registry
          };
        };
        var NoDrag = function() {
          var events = create$4({ move: Event2(["info"]) });
          return {
            onEvent: noop3,
            reset: noop3,
            events: events.registry
          };
        };
        var Movement = function() {
          var noDragState = NoDrag();
          var inDragState = InDrag();
          var dragState = noDragState;
          var on3 = function() {
            dragState.reset();
            dragState = inDragState;
          };
          var off = function() {
            dragState.reset();
            dragState = noDragState;
          };
          var onEvent = function(event, mode) {
            dragState.onEvent(event, mode);
          };
          var isOn = function() {
            return dragState === inDragState;
          };
          return {
            on: on3,
            off,
            isOn,
            onEvent,
            events: inDragState.events
          };
        };
        var setup = function(mutation, mode, settings) {
          var active = false;
          var events = create$4({
            start: Event2([]),
            stop: Event2([])
          });
          var movement = Movement();
          var drop = function() {
            sink2.stop();
            if (movement.isOn()) {
              movement.off();
              events.trigger.stop();
            }
          };
          var throttledDrop = last(drop, 200);
          var go2 = function(parent2) {
            sink2.start(parent2);
            movement.on();
            events.trigger.start();
          };
          var mousemove = function(event) {
            throttledDrop.cancel();
            movement.onEvent(event, mode);
          };
          movement.events.move.bind(function(event) {
            mode.mutate(mutation, event.info);
          });
          var on3 = function() {
            active = true;
          };
          var off = function() {
            active = false;
          };
          var runIfActive = function(f2) {
            return function() {
              var args = [];
              for (var _i2 = 0; _i2 < arguments.length; _i2++) {
                args[_i2] = arguments[_i2];
              }
              if (active) {
                f2.apply(null, args);
              }
            };
          };
          var sink2 = mode.sink(DragApi({
            forceDrop: drop,
            drop: runIfActive(drop),
            move: runIfActive(mousemove),
            delayDrop: runIfActive(throttledDrop.throttle)
          }), settings);
          var destroy2 = function() {
            sink2.destroy();
          };
          return {
            element: sink2.element,
            go: go2,
            on: on3,
            off,
            destroy: destroy2,
            events: events.registry
          };
        };
        var mkEvent = function(target, x2, y2, stop, prevent, kill, raw) {
          return {
            target,
            x: x2,
            y: y2,
            stop,
            prevent,
            kill,
            raw
          };
        };
        var fromRawEvent$1 = function(rawEvent) {
          var target = SugarElement.fromDom(getOriginalEventTarget(rawEvent).getOr(rawEvent.target));
          var stop = function() {
            return rawEvent.stopPropagation();
          };
          var prevent = function() {
            return rawEvent.preventDefault();
          };
          var kill = compose(prevent, stop);
          return mkEvent(target, rawEvent.clientX, rawEvent.clientY, stop, prevent, kill, rawEvent);
        };
        var handle$2 = function(filter2, handler) {
          return function(rawEvent) {
            if (filter2(rawEvent)) {
              handler(fromRawEvent$1(rawEvent));
            }
          };
        };
        var binder = function(element, event, filter2, handler, useCapture) {
          var wrapped = handle$2(filter2, handler);
          element.dom.addEventListener(event, wrapped, useCapture);
          return { unbind: curry(unbind, element, event, wrapped, useCapture) };
        };
        var bind$1 = function(element, event, filter2, handler) {
          return binder(element, event, filter2, handler, false);
        };
        var unbind = function(element, event, handler, useCapture) {
          element.dom.removeEventListener(event, handler, useCapture);
        };
        var filter = always;
        var bind = function(element, event, handler) {
          return bind$1(element, event, filter, handler);
        };
        var fromRawEvent = fromRawEvent$1;
        var read2 = function(element, attr) {
          var value2 = get$b(element, attr);
          return value2 === void 0 || value2 === "" ? [] : value2.split(" ");
        };
        var add$2 = function(element, attr, id2) {
          var old = read2(element, attr);
          var nu2 = old.concat([id2]);
          set$2(element, attr, nu2.join(" "));
          return true;
        };
        var remove$4 = function(element, attr, id2) {
          var nu2 = filter$2(read2(element, attr), function(v2) {
            return v2 !== id2;
          });
          if (nu2.length > 0) {
            set$2(element, attr, nu2.join(" "));
          } else {
            remove$7(element, attr);
          }
          return false;
        };
        var supports = function(element) {
          return element.dom.classList !== void 0;
        };
        var get$5 = function(element) {
          return read2(element, "class");
        };
        var add$1 = function(element, clazz) {
          return add$2(element, "class", clazz);
        };
        var remove$3 = function(element, clazz) {
          return remove$4(element, "class", clazz);
        };
        var add3 = function(element, clazz) {
          if (supports(element)) {
            element.dom.classList.add(clazz);
          } else {
            add$1(element, clazz);
          }
        };
        var cleanClass = function(element) {
          var classList = supports(element) ? element.dom.classList : get$5(element);
          if (classList.length === 0) {
            remove$7(element, "class");
          }
        };
        var remove$2 = function(element, clazz) {
          if (supports(element)) {
            var classList = element.dom.classList;
            classList.remove(clazz);
          } else {
            remove$3(element, clazz);
          }
          cleanClass(element);
        };
        var has = function(element, clazz) {
          return supports(element) && element.dom.classList.contains(clazz);
        };
        var css = function(namespace) {
          var dashNamespace = namespace.replace(/\./g, "-");
          var resolve3 = function(str) {
            return dashNamespace + "-" + str;
          };
          return { resolve: resolve3 };
        };
        var styles$1 = css("ephox-dragster");
        var resolve$1 = styles$1.resolve;
        var Blocker = function(options) {
          var settings = __assign({ layerClass: resolve$1("blocker") }, options);
          var div = SugarElement.fromTag("div");
          set$2(div, "role", "presentation");
          setAll(div, {
            position: "fixed",
            left: "0px",
            top: "0px",
            width: "100%",
            height: "100%"
          });
          add3(div, resolve$1("blocker"));
          add3(div, settings.layerClass);
          var element = constant(div);
          var destroy2 = function() {
            remove$5(div);
          };
          return {
            element,
            destroy: destroy2
          };
        };
        var compare = function(old, nu2) {
          return SugarPosition(nu2.left - old.left, nu2.top - old.top);
        };
        var extract = function(event) {
          return Optional.some(SugarPosition(event.x, event.y));
        };
        var mutate = function(mutation, info) {
          mutation.mutate(info.left, info.top);
        };
        var sink = function(dragApi, settings) {
          var blocker = Blocker(settings);
          var mdown = bind(blocker.element(), "mousedown", dragApi.forceDrop);
          var mup = bind(blocker.element(), "mouseup", dragApi.drop);
          var mmove = bind(blocker.element(), "mousemove", dragApi.move);
          var mout = bind(blocker.element(), "mouseout", dragApi.delayDrop);
          var destroy2 = function() {
            blocker.destroy();
            mup.unbind();
            mmove.unbind();
            mout.unbind();
            mdown.unbind();
          };
          var start4 = function(parent2) {
            append$1(parent2, blocker.element());
          };
          var stop = function() {
            remove$5(blocker.element());
          };
          return DragSink({
            element: blocker.element,
            start: start4,
            stop,
            destroy: destroy2
          });
        };
        var MouseDrag = DragMode({
          compare,
          extract,
          sink,
          mutate
        });
        var transform$1 = function(mutation, settings) {
          if (settings === void 0) {
            settings = {};
          }
          var mode = settings.mode !== void 0 ? settings.mode : MouseDrag;
          return setup(mutation, mode, settings);
        };
        var closest = function(target) {
          return closest$1(target, "[contenteditable]");
        };
        var isEditable$1 = function(element, assumeEditable) {
          if (assumeEditable === void 0) {
            assumeEditable = false;
          }
          if (!detect$3().browser.isIE() && inBody(element)) {
            return element.dom.isContentEditable;
          } else {
            return closest(element).fold(constant(assumeEditable), function(editable) {
              return getRaw(editable) === "true";
            });
          }
        };
        var getRaw = function(element) {
          return element.dom.contentEditable;
        };
        var styles = css("ephox-snooker");
        var resolve2 = styles.resolve;
        var Mutation = function() {
          var events = create$4({
            drag: Event2([
              "xDelta",
              "yDelta"
            ])
          });
          var mutate2 = function(x2, y2) {
            events.trigger.drag(x2, y2);
          };
          return {
            mutate: mutate2,
            events: events.registry
          };
        };
        var BarMutation = function() {
          var events = create$4({
            drag: Event2([
              "xDelta",
              "yDelta",
              "target"
            ])
          });
          var target = Optional.none();
          var delegate = Mutation();
          delegate.events.drag.bind(function(event) {
            target.each(function(t2) {
              events.trigger.drag(event.xDelta, event.yDelta, t2);
            });
          });
          var assign2 = function(t2) {
            target = Optional.some(t2);
          };
          var get2 = function() {
            return target;
          };
          return {
            assign: assign2,
            get: get2,
            mutate: delegate.mutate,
            events: events.registry
          };
        };
        var col = function(column, x2, y2, w2, h3) {
          var bar = SugarElement.fromTag("div");
          setAll(bar, {
            position: "absolute",
            left: x2 - w2 / 2 + "px",
            top: y2 + "px",
            height: h3 + "px",
            width: w2 + "px"
          });
          setAll$1(bar, {
            "data-column": column,
            "role": "presentation"
          });
          return bar;
        };
        var row = function(r3, x2, y2, w2, h3) {
          var bar = SugarElement.fromTag("div");
          setAll(bar, {
            position: "absolute",
            left: x2 + "px",
            top: y2 - h3 / 2 + "px",
            height: h3 + "px",
            width: w2 + "px"
          });
          setAll$1(bar, {
            "data-row": r3,
            "role": "presentation"
          });
          return bar;
        };
        var resizeBar = resolve2("resizer-bar");
        var resizeRowBar = resolve2("resizer-rows");
        var resizeColBar = resolve2("resizer-cols");
        var BAR_THICKNESS = 7;
        var resizableRows = function(warehouse, isResizable2) {
          return bind$2(warehouse.all, function(row2, i2) {
            return isResizable2(row2.element) ? [i2] : [];
          });
        };
        var resizableColumns = function(warehouse, isResizable2) {
          var resizableCols = [];
          range$1(warehouse.grid.columns, function(index) {
            var colElmOpt = Warehouse.getColumnAt(warehouse, index).map(function(col2) {
              return col2.element;
            });
            if (colElmOpt.forall(isResizable2)) {
              resizableCols.push(index);
            }
          });
          return filter$2(resizableCols, function(colIndex) {
            var columnCells = Warehouse.filterItems(warehouse, function(cell2) {
              return cell2.column === colIndex;
            });
            return forall(columnCells, function(cell2) {
              return isResizable2(cell2.element);
            });
          });
        };
        var destroy = function(wire) {
          var previous = descendants(wire.parent(), "." + resizeBar);
          each$2(previous, remove$5);
        };
        var drawBar = function(wire, positions2, create2) {
          var origin = wire.origin();
          each$2(positions2, function(cpOption) {
            cpOption.each(function(cp) {
              var bar = create2(origin, cp);
              add3(bar, resizeBar);
              append$1(wire.parent(), bar);
            });
          });
        };
        var refreshCol = function(wire, colPositions, position, tableHeight) {
          drawBar(wire, colPositions, function(origin, cp) {
            var colBar = col(cp.col, cp.x - origin.left, position.top - origin.top, BAR_THICKNESS, tableHeight);
            add3(colBar, resizeColBar);
            return colBar;
          });
        };
        var refreshRow = function(wire, rowPositions, position, tableWidth) {
          drawBar(wire, rowPositions, function(origin, cp) {
            var rowBar = row(cp.row, position.left - origin.left, cp.y - origin.top, tableWidth, BAR_THICKNESS);
            add3(rowBar, resizeRowBar);
            return rowBar;
          });
        };
        var refreshGrid = function(warhouse, wire, table2, rows2, cols) {
          var position = absolute(table2);
          var isResizable2 = wire.isResizable;
          var rowPositions = rows2.length > 0 ? height.positions(rows2, table2) : [];
          var resizableRowBars = rowPositions.length > 0 ? resizableRows(warhouse, isResizable2) : [];
          var resizableRowPositions = filter$2(rowPositions, function(_pos, i2) {
            return exists(resizableRowBars, function(barIndex) {
              return i2 === barIndex;
            });
          });
          refreshRow(wire, resizableRowPositions, position, getOuter$2(table2));
          var colPositions = cols.length > 0 ? width.positions(cols, table2) : [];
          var resizableColBars = colPositions.length > 0 ? resizableColumns(warhouse, isResizable2) : [];
          var resizableColPositions = filter$2(colPositions, function(_pos, i2) {
            return exists(resizableColBars, function(barIndex) {
              return i2 === barIndex;
            });
          });
          refreshCol(wire, resizableColPositions, position, getOuter$1(table2));
        };
        var refresh = function(wire, table2) {
          destroy(wire);
          if (wire.isResizable(table2)) {
            var warehouse = Warehouse.fromTable(table2);
            var rows$12 = rows(warehouse);
            var cols = columns(warehouse);
            refreshGrid(warehouse, wire, table2, rows$12, cols);
          }
        };
        var each2 = function(wire, f2) {
          var bars = descendants(wire.parent(), "." + resizeBar);
          each$2(bars, f2);
        };
        var hide2 = function(wire) {
          each2(wire, function(bar) {
            set$1(bar, "display", "none");
          });
        };
        var show = function(wire) {
          each2(wire, function(bar) {
            set$1(bar, "display", "block");
          });
        };
        var isRowBar = function(element) {
          return has(element, resizeRowBar);
        };
        var isColBar = function(element) {
          return has(element, resizeColBar);
        };
        var resizeBarDragging = resolve2("resizer-bar-dragging");
        var BarManager = function(wire) {
          var mutation = BarMutation();
          var resizing = transform$1(mutation, {});
          var hoverTable = Optional.none();
          var getResizer = function(element, type2) {
            return Optional.from(get$b(element, type2));
          };
          mutation.events.drag.bind(function(event) {
            getResizer(event.target, "data-row").each(function(_dataRow) {
              var currentRow = getCssValue(event.target, "top");
              set$1(event.target, "top", currentRow + event.yDelta + "px");
            });
            getResizer(event.target, "data-column").each(function(_dataCol) {
              var currentCol = getCssValue(event.target, "left");
              set$1(event.target, "left", currentCol + event.xDelta + "px");
            });
          });
          var getDelta = function(target, dir) {
            var newX = getCssValue(target, dir);
            var oldX = getAttrValue(target, "data-initial-" + dir, 0);
            return newX - oldX;
          };
          resizing.events.stop.bind(function() {
            mutation.get().each(function(target) {
              hoverTable.each(function(table2) {
                getResizer(target, "data-row").each(function(row2) {
                  var delta = getDelta(target, "top");
                  remove$7(target, "data-initial-top");
                  events.trigger.adjustHeight(table2, delta, parseInt(row2, 10));
                });
                getResizer(target, "data-column").each(function(column) {
                  var delta = getDelta(target, "left");
                  remove$7(target, "data-initial-left");
                  events.trigger.adjustWidth(table2, delta, parseInt(column, 10));
                });
                refresh(wire, table2);
              });
            });
          });
          var handler = function(target, dir) {
            events.trigger.startAdjust();
            mutation.assign(target);
            set$2(target, "data-initial-" + dir, getCssValue(target, dir));
            add3(target, resizeBarDragging);
            set$1(target, "opacity", "0.2");
            resizing.go(wire.parent());
          };
          var mousedown = bind(wire.parent(), "mousedown", function(event) {
            if (isRowBar(event.target)) {
              handler(event.target, "top");
            }
            if (isColBar(event.target)) {
              handler(event.target, "left");
            }
          });
          var isRoot = function(e2) {
            return eq$1(e2, wire.view());
          };
          var findClosestEditableTable = function(target) {
            return closest$1(target, "table", isRoot).filter(isEditable$1);
          };
          var mouseover = bind(wire.view(), "mouseover", function(event) {
            findClosestEditableTable(event.target).fold(function() {
              if (inBody(event.target)) {
                destroy(wire);
              }
            }, function(table2) {
              hoverTable = Optional.some(table2);
              refresh(wire, table2);
            });
          });
          var destroy$1 = function() {
            mousedown.unbind();
            mouseover.unbind();
            resizing.destroy();
            destroy(wire);
          };
          var refresh$1 = function(tbl) {
            refresh(wire, tbl);
          };
          var events = create$4({
            adjustHeight: Event2([
              "table",
              "delta",
              "row"
            ]),
            adjustWidth: Event2([
              "table",
              "delta",
              "column"
            ]),
            startAdjust: Event2([])
          });
          return {
            destroy: destroy$1,
            refresh: refresh$1,
            on: resizing.on,
            off: resizing.off,
            hideBars: curry(hide2, wire),
            showBars: curry(show, wire),
            events: events.registry
          };
        };
        var create$3 = function(wire, resizing, lazySizing) {
          var hdirection = height;
          var vdirection = width;
          var manager = BarManager(wire);
          var events = create$4({
            beforeResize: Event2([
              "table",
              "type"
            ]),
            afterResize: Event2([
              "table",
              "type"
            ]),
            startDrag: Event2([])
          });
          manager.events.adjustHeight.bind(function(event) {
            var table2 = event.table;
            events.trigger.beforeResize(table2, "row");
            var delta = hdirection.delta(event.delta, table2);
            adjustHeight(table2, delta, event.row, hdirection);
            events.trigger.afterResize(table2, "row");
          });
          manager.events.startAdjust.bind(function(_event) {
            events.trigger.startDrag();
          });
          manager.events.adjustWidth.bind(function(event) {
            var table2 = event.table;
            events.trigger.beforeResize(table2, "col");
            var delta = vdirection.delta(event.delta, table2);
            var tableSize = lazySizing(table2);
            adjustWidth(table2, delta, event.column, resizing, tableSize);
            events.trigger.afterResize(table2, "col");
          });
          return {
            on: manager.on,
            off: manager.off,
            hideBars: manager.hideBars,
            showBars: manager.showBars,
            destroy: manager.destroy,
            events: events.registry
          };
        };
        var TableResize = { create: create$3 };
        var fireNewRow = function(editor, row2) {
          return editor.fire("newrow", { node: row2 });
        };
        var fireNewCell = function(editor, cell2) {
          return editor.fire("newcell", { node: cell2 });
        };
        var fireObjectResizeStart = function(editor, target, width2, height2, origin) {
          editor.fire("ObjectResizeStart", {
            target,
            width: width2,
            height: height2,
            origin
          });
        };
        var fireObjectResized = function(editor, target, width2, height2, origin) {
          editor.fire("ObjectResized", {
            target,
            width: width2,
            height: height2,
            origin
          });
        };
        var fireTableSelectionChange = function(editor, cells2, start4, finish, otherCells) {
          editor.fire("TableSelectionChange", {
            cells: cells2,
            start: start4,
            finish,
            otherCells
          });
        };
        var fireTableSelectionClear = function(editor) {
          editor.fire("TableSelectionClear");
        };
        var fireTableModified = function(editor, table2, data) {
          editor.fire("TableModified", __assign(__assign({}, data), { table: table2 }));
        };
        var styleModified = {
          structure: false,
          style: true
        };
        var structureModified = {
          structure: true,
          style: false
        };
        var styleAndStructureModified = {
          structure: true,
          style: true
        };
        var defaultTableToolbar = "tableprops tabledelete | tableinsertrowbefore tableinsertrowafter tabledeleterow | tableinsertcolbefore tableinsertcolafter tabledeletecol";
        var defaultStyles = {
          "border-collapse": "collapse",
          "width": "100%"
        };
        var defaultCellBorderWidths = range$1(5, function(i2) {
          var size2 = i2 + 1 + "px";
          return {
            title: size2,
            value: size2
          };
        });
        var defaultCellBorderStyles = map$12([
          "Solid",
          "Dotted",
          "Dashed",
          "Double",
          "Groove",
          "Ridge",
          "Inset",
          "Outset",
          "None",
          "Hidden"
        ], function(type2) {
          return {
            title: type2,
            value: type2.toLowerCase()
          };
        });
        var determineDefaultStyles = function(editor) {
          var _a;
          if (isPixelsForced(editor)) {
            var dom = editor.dom;
            var parentBlock = (_a = dom.getParent(editor.selection.getStart(), dom.isBlock)) !== null && _a !== void 0 ? _a : editor.getBody();
            var contentWidth = getInner(SugarElement.fromDom(parentBlock));
            return __assign(__assign({}, defaultStyles), { width: contentWidth + "px" });
          } else if (isResponsiveForced(editor)) {
            return filter$1(defaultStyles, function(_value, key2) {
              return key2 !== "width";
            });
          } else {
            return defaultStyles;
          }
        };
        var defaultAttributes = { border: "1" };
        var defaultColumnResizingBehaviour = "preservetable";
        var getTableSizingMode = function(editor) {
          return editor.getParam("table_sizing_mode", "auto");
        };
        var getTableResponseWidth = function(editor) {
          return editor.getParam("table_responsive_width");
        };
        var getTableBorderWidths = function(editor) {
          return editor.getParam("table_border_widths", defaultCellBorderWidths, "array");
        };
        var getTableBorderStyles = function(editor) {
          return editor.getParam("table_border_styles", defaultCellBorderStyles, "array");
        };
        var getDefaultAttributes = function(editor) {
          return editor.getParam("table_default_attributes", defaultAttributes, "object");
        };
        var getDefaultStyles = function(editor) {
          return editor.getParam("table_default_styles", determineDefaultStyles(editor), "object");
        };
        var hasTableResizeBars = function(editor) {
          return editor.getParam("table_resize_bars", true, "boolean");
        };
        var hasTabNavigation = function(editor) {
          return editor.getParam("table_tab_navigation", true, "boolean");
        };
        var hasAdvancedCellTab = function(editor) {
          return editor.getParam("table_cell_advtab", true, "boolean");
        };
        var hasAdvancedRowTab = function(editor) {
          return editor.getParam("table_row_advtab", true, "boolean");
        };
        var hasAdvancedTableTab = function(editor) {
          return editor.getParam("table_advtab", true, "boolean");
        };
        var hasAppearanceOptions = function(editor) {
          return editor.getParam("table_appearance_options", true, "boolean");
        };
        var hasTableGrid = function(editor) {
          return editor.getParam("table_grid", true, "boolean");
        };
        var shouldStyleWithCss = function(editor) {
          return editor.getParam("table_style_by_css", false, "boolean");
        };
        var getCellClassList = function(editor) {
          return editor.getParam("table_cell_class_list", [], "array");
        };
        var getRowClassList = function(editor) {
          return editor.getParam("table_row_class_list", [], "array");
        };
        var getTableClassList = function(editor) {
          return editor.getParam("table_class_list", [], "array");
        };
        var isPercentagesForced = function(editor) {
          return getTableSizingMode(editor) === "relative" || getTableResponseWidth(editor) === true;
        };
        var isPixelsForced = function(editor) {
          return getTableSizingMode(editor) === "fixed" || getTableResponseWidth(editor) === false;
        };
        var isResponsiveForced = function(editor) {
          return getTableSizingMode(editor) === "responsive";
        };
        var getToolbar = function(editor) {
          return editor.getParam("table_toolbar", defaultTableToolbar);
        };
        var useColumnGroup = function(editor) {
          return editor.getParam("table_use_colgroups", false, "boolean");
        };
        var getTableHeaderType = function(editor) {
          var defaultValue = "section";
          var value2 = editor.getParam("table_header_type", defaultValue, "string");
          var validValues = [
            "section",
            "cells",
            "sectionCells",
            "auto"
          ];
          if (!contains$2(validValues, value2)) {
            return defaultValue;
          } else {
            return value2;
          }
        };
        var getColumnResizingBehaviour = function(editor) {
          var validModes = [
            "preservetable",
            "resizetable"
          ];
          var givenMode = editor.getParam("table_column_resizing", defaultColumnResizingBehaviour, "string");
          return find$1(validModes, function(mode) {
            return mode === givenMode;
          }).getOr(defaultColumnResizingBehaviour);
        };
        var isPreserveTableColumnResizing = function(editor) {
          return getColumnResizingBehaviour(editor) === "preservetable";
        };
        var isResizeTableColumnResizing = function(editor) {
          return getColumnResizingBehaviour(editor) === "resizetable";
        };
        var getCloneElements = function(editor) {
          var cloneElements = editor.getParam("table_clone_elements");
          if (isString(cloneElements)) {
            return Optional.some(cloneElements.split(/[ ,]/));
          } else if (Array.isArray(cloneElements)) {
            return Optional.some(cloneElements);
          } else {
            return Optional.none();
          }
        };
        var hasObjectResizing = function(editor) {
          var objectResizing = editor.getParam("object_resizing", true);
          return isString(objectResizing) ? objectResizing === "table" : objectResizing;
        };
        var getTableBackgroundColorMap = function(editor) {
          return editor.getParam("table_background_color_map", [], "array");
        };
        var getTableBorderColorMap = function(editor) {
          return editor.getParam("table_border_color_map", [], "array");
        };
        var get$4 = function(editor, table2) {
          if (isPercentagesForced(editor)) {
            return TableSize.percentageSize(table2);
          } else if (isPixelsForced(editor)) {
            return TableSize.pixelSize(table2);
          } else {
            return TableSize.getTableSize(table2);
          }
        };
        var cleanupLegacyAttributes = function(element) {
          remove$7(element, "width");
        };
        var convertToPercentSize = function(table2) {
          var newWidth = getPercentTableWidth(table2);
          redistribute(table2, Optional.some(newWidth), Optional.none());
          cleanupLegacyAttributes(table2);
        };
        var convertToPixelSize = function(table2) {
          var newWidth = getPixelTableWidth(table2);
          redistribute(table2, Optional.some(newWidth), Optional.none());
          cleanupLegacyAttributes(table2);
        };
        var convertToNoneSize = function(table2) {
          remove$6(table2, "width");
          var columns2 = columns$1(table2);
          var rowElements = columns2.length > 0 ? columns2 : cells$1(table2);
          each$2(rowElements, function(cell2) {
            remove$6(cell2, "width");
            cleanupLegacyAttributes(cell2);
          });
          cleanupLegacyAttributes(table2);
        };
        var enforcePercentage = convertToPercentSize;
        var enforcePixels = convertToPixelSize;
        var enforceNone = convertToNoneSize;
        var syncPixels = function(table2) {
          var warehouse = Warehouse.fromTable(table2);
          if (!Warehouse.hasColumns(warehouse)) {
            each$2(cells$1(table2), function(cell2) {
              var computedWidth = get$a(cell2, "width");
              set$1(cell2, "width", computedWidth);
              remove$7(cell2, "width");
            });
          }
        };
        var createContainer = function() {
          var container = SugarElement.fromTag("div");
          setAll(container, {
            position: "static",
            height: "0",
            width: "0",
            padding: "0",
            margin: "0",
            border: "0"
          });
          append$1(body$1(), container);
          return container;
        };
        var get$3 = function(editor, isResizable2) {
          return editor.inline ? ResizeWire.body(getBody(editor), createContainer(), isResizable2) : ResizeWire.only(SugarElement.fromDom(editor.getDoc()), isResizable2);
        };
        var remove$1 = function(editor, wire) {
          if (editor.inline) {
            remove$5(wire.parent());
          }
        };
        var barResizerPrefix = "bar-";
        var isResizable = function(elm) {
          return get$b(elm, "data-mce-resize") !== "false";
        };
        var getResizeHandler = function(editor) {
          var selectionRng = Optional.none();
          var resize2 = Optional.none();
          var wire = Optional.none();
          var startW;
          var startRawW;
          var isTable = function(elm) {
            return elm.nodeName === "TABLE";
          };
          var lazyResize = function() {
            return resize2;
          };
          var lazyWire = function() {
            return wire.getOr(ResizeWire.only(SugarElement.fromDom(editor.getBody()), isResizable));
          };
          var lazySizing = function(table2) {
            return get$4(editor, table2);
          };
          var lazyResizingBehaviour = function() {
            return isPreserveTableColumnResizing(editor) ? preserveTable() : resizeTable();
          };
          var getNumColumns = function(table2) {
            return getGridSize(table2).columns;
          };
          var afterCornerResize = function(table2, origin, width2) {
            var isRightEdgeResize = endsWith(origin, "e");
            if (startRawW === "") {
              enforcePercentage(table2);
            }
            if (width2 !== startW && startRawW !== "") {
              set$1(table2, "width", startRawW);
              var resizing = lazyResizingBehaviour();
              var tableSize = lazySizing(table2);
              var col2 = isPreserveTableColumnResizing(editor) || isRightEdgeResize ? getNumColumns(table2) - 1 : 0;
              adjustWidth(table2, width2 - startW, col2, resizing, tableSize);
            } else if (isPercentage$1(startRawW)) {
              var percentW = parseFloat(startRawW.replace("%", ""));
              var targetPercentW = width2 * percentW / startW;
              set$1(table2, "width", targetPercentW + "%");
            }
            if (isPixel(startRawW)) {
              syncPixels(table2);
            }
          };
          var destroy2 = function() {
            resize2.each(function(sz) {
              sz.destroy();
            });
            wire.each(function(w2) {
              remove$1(editor, w2);
            });
          };
          editor.on("init", function() {
            var rawWire = get$3(editor, isResizable);
            wire = Optional.some(rawWire);
            if (hasObjectResizing(editor) && hasTableResizeBars(editor)) {
              var resizing = lazyResizingBehaviour();
              var sz = TableResize.create(rawWire, resizing, lazySizing);
              sz.on();
              sz.events.startDrag.bind(function(_event) {
                selectionRng = Optional.some(editor.selection.getRng());
              });
              sz.events.beforeResize.bind(function(event) {
                var rawTable = event.table.dom;
                fireObjectResizeStart(editor, rawTable, getPixelWidth(rawTable), getPixelHeight(rawTable), barResizerPrefix + event.type);
              });
              sz.events.afterResize.bind(function(event) {
                var table2 = event.table;
                var rawTable = table2.dom;
                removeDataStyle(table2);
                selectionRng.each(function(rng) {
                  editor.selection.setRng(rng);
                  editor.focus();
                });
                fireObjectResized(editor, rawTable, getPixelWidth(rawTable), getPixelHeight(rawTable), barResizerPrefix + event.type);
                editor.undoManager.add();
              });
              resize2 = Optional.some(sz);
            }
          });
          editor.on("ObjectResizeStart", function(e2) {
            var targetElm = e2.target;
            if (isTable(targetElm)) {
              var table2 = SugarElement.fromDom(targetElm);
              each$2(editor.dom.select(".mce-clonedresizable"), function(clone3) {
                editor.dom.addClass(clone3, "mce-" + getColumnResizingBehaviour(editor) + "-columns");
              });
              if (!isPixelSizing(table2) && isPixelsForced(editor)) {
                enforcePixels(table2);
              } else if (!isPercentSizing(table2) && isPercentagesForced(editor)) {
                enforcePercentage(table2);
              }
              if (isNoneSizing(table2) && startsWith(e2.origin, barResizerPrefix)) {
                enforcePercentage(table2);
              }
              startW = e2.width;
              startRawW = isResponsiveForced(editor) ? "" : getRawWidth(editor, targetElm).getOr("");
            }
          });
          editor.on("ObjectResized", function(e2) {
            var targetElm = e2.target;
            if (isTable(targetElm)) {
              var table2 = SugarElement.fromDom(targetElm);
              var origin_1 = e2.origin;
              if (startsWith(origin_1, "corner-")) {
                afterCornerResize(table2, origin_1, e2.width);
              }
              removeDataStyle(table2);
              fireTableModified(editor, table2.dom, styleModified);
            }
          });
          editor.on("SwitchMode", function() {
            lazyResize().each(function(resize3) {
              if (editor.mode.isReadOnly()) {
                resize3.hideBars();
              } else {
                resize3.showBars();
              }
            });
          });
          return {
            lazyResize,
            lazyWire,
            destroy: destroy2
          };
        };
        var point = function(element, offset2) {
          return {
            element,
            offset: offset2
          };
        };
        var scan$1 = function(universe2, element, direction) {
          if (universe2.property().isText(element) && universe2.property().getText(element).trim().length === 0 || universe2.property().isComment(element)) {
            return direction(element).bind(function(elem) {
              return scan$1(universe2, elem, direction).orThunk(function() {
                return Optional.some(elem);
              });
            });
          } else {
            return Optional.none();
          }
        };
        var toEnd = function(universe2, element) {
          if (universe2.property().isText(element)) {
            return universe2.property().getText(element).length;
          }
          var children2 = universe2.property().children(element);
          return children2.length;
        };
        var freefallRtl$2 = function(universe2, element) {
          var candidate = scan$1(universe2, element, universe2.query().prevSibling).getOr(element);
          if (universe2.property().isText(candidate)) {
            return point(candidate, toEnd(universe2, candidate));
          }
          var children2 = universe2.property().children(candidate);
          return children2.length > 0 ? freefallRtl$2(universe2, children2[children2.length - 1]) : point(candidate, toEnd(universe2, candidate));
        };
        var freefallRtl$1 = freefallRtl$2;
        var universe$2 = DomUniverse();
        var freefallRtl = function(element) {
          return freefallRtl$1(universe$2, element);
        };
        var halve = function(main2, other) {
          var colspan = getSpan(main2, "colspan");
          if (colspan === 1) {
            var width2 = getGenericWidth(main2);
            width2.each(function(w2) {
              var newWidth = w2.value / 2;
              setGenericWidth(main2, newWidth, w2.unit);
              setGenericWidth(other, newWidth, w2.unit);
            });
          }
        };
        var isHeaderCell = isTag("th");
        var isHeaderCells = function(cells2) {
          return forall(cells2, function(cell2) {
            return isHeaderCell(cell2.element);
          });
        };
        var getRowHeaderType = function(isHeaderRow, isHeaderCells2) {
          if (isHeaderRow && isHeaderCells2) {
            return "sectionCells";
          } else if (isHeaderRow) {
            return "section";
          } else {
            return "cells";
          }
        };
        var getRowType$1 = function(row2) {
          var isHeaderRow = row2.section === "thead";
          var isHeaderCells2 = is(findCommonCellType(row2.cells), "th");
          if (isHeaderRow || isHeaderCells2) {
            return {
              type: "header",
              subType: getRowHeaderType(isHeaderRow, isHeaderCells2)
            };
          } else if (row2.section === "tfoot") {
            return { type: "footer" };
          } else {
            return { type: "body" };
          }
        };
        var findCommonCellType = function(cells2) {
          var headerCells = filter$2(cells2, function(cell2) {
            return isHeaderCell(cell2.element);
          });
          if (headerCells.length === 0) {
            return Optional.some("td");
          } else if (headerCells.length === cells2.length) {
            return Optional.some("th");
          } else {
            return Optional.none();
          }
        };
        var findCommonRowType = function(rows2) {
          var rowTypes = map$12(rows2, function(row2) {
            return getRowType$1(row2).type;
          });
          var hasHeader = contains$2(rowTypes, "header");
          var hasFooter = contains$2(rowTypes, "footer");
          if (!hasHeader && !hasFooter) {
            return Optional.some("body");
          } else {
            var hasBody = contains$2(rowTypes, "body");
            if (hasHeader && !hasBody && !hasFooter) {
              return Optional.some("header");
            } else if (!hasHeader && !hasBody && hasFooter) {
              return Optional.some("footer");
            } else {
              return Optional.none();
            }
          }
        };
        var findTableRowHeaderType = function(warehouse) {
          return findMap(warehouse.all, function(row2) {
            var rowType = getRowType$1(row2);
            return rowType.type === "header" ? Optional.from(rowType.subType) : Optional.none();
          });
        };
        var transformCell = function(cell2, comparator, substitution) {
          return elementnew(substitution(cell2.element, comparator), true, cell2.isLocked);
        };
        var transformRow = function(row2, section2) {
          return row2.section !== section2 ? rowcells(row2.element, row2.cells, section2, row2.isNew) : row2;
        };
        var section = function() {
          return {
            transformRow,
            transformCell: function(cell2, comparator, substitution) {
              var newCell = substitution(cell2.element, comparator);
              var fixedCell = name(newCell) !== "td" ? mutate$1(newCell, "td") : newCell;
              return elementnew(fixedCell, cell2.isNew, cell2.isLocked);
            }
          };
        };
        var sectionCells = function() {
          return {
            transformRow,
            transformCell
          };
        };
        var cells = function() {
          return {
            transformRow: function(row2, section2) {
              var newSection = section2 === "thead" ? "tbody" : section2;
              return transformRow(row2, newSection);
            },
            transformCell
          };
        };
        var fallback = function() {
          return {
            transformRow: identity,
            transformCell
          };
        };
        var getTableSectionType = function(table2, fallback2) {
          var warehouse = Warehouse.fromTable(table2);
          var type2 = findTableRowHeaderType(warehouse).getOr(fallback2);
          switch (type2) {
            case "section":
              return section();
            case "sectionCells":
              return sectionCells();
            case "cells":
              return cells();
          }
        };
        var TableSection = {
          getTableSectionType,
          section,
          sectionCells,
          cells,
          fallback
        };
        var setIfNot = function(element, property, value2, ignore) {
          if (value2 === ignore) {
            remove$7(element, property);
          } else {
            set$2(element, property, value2);
          }
        };
        var insert$1 = function(table2, selector, element) {
          last$2(children$1(table2, selector)).fold(function() {
            return prepend(table2, element);
          }, function(child2) {
            return after$5(child2, element);
          });
        };
        var generateSection = function(table2, sectionName) {
          var section2 = child$1(table2, sectionName).getOrThunk(function() {
            var newSection = SugarElement.fromTag(sectionName, owner(table2).dom);
            if (sectionName === "thead") {
              insert$1(table2, "caption,colgroup", newSection);
            } else if (sectionName === "colgroup") {
              insert$1(table2, "caption", newSection);
            } else {
              append$1(table2, newSection);
            }
            return newSection;
          });
          empty(section2);
          return section2;
        };
        var render$1 = function(table2, grid2) {
          var newRows = [];
          var newCells = [];
          var syncRows = function(gridSection) {
            return map$12(gridSection, function(row2) {
              if (row2.isNew) {
                newRows.push(row2.element);
              }
              var tr = row2.element;
              empty(tr);
              each$2(row2.cells, function(cell2) {
                if (cell2.isNew) {
                  newCells.push(cell2.element);
                }
                setIfNot(cell2.element, "colspan", cell2.colspan, 1);
                setIfNot(cell2.element, "rowspan", cell2.rowspan, 1);
                append$1(tr, cell2.element);
              });
              return tr;
            });
          };
          var syncColGroup = function(gridSection) {
            return bind$2(gridSection, function(colGroup) {
              return map$12(colGroup.cells, function(col2) {
                setIfNot(col2.element, "span", col2.colspan, 1);
                return col2.element;
              });
            });
          };
          var renderSection = function(gridSection, sectionName) {
            var section2 = generateSection(table2, sectionName);
            var sync2 = sectionName === "colgroup" ? syncColGroup : syncRows;
            var sectionElems = sync2(gridSection);
            append(section2, sectionElems);
          };
          var removeSection = function(sectionName) {
            child$1(table2, sectionName).each(remove$5);
          };
          var renderOrRemoveSection = function(gridSection, sectionName) {
            if (gridSection.length > 0) {
              renderSection(gridSection, sectionName);
            } else {
              removeSection(sectionName);
            }
          };
          var headSection = [];
          var bodySection = [];
          var footSection = [];
          var columnGroupsSection = [];
          each$2(grid2, function(row2) {
            switch (row2.section) {
              case "thead":
                headSection.push(row2);
                break;
              case "tbody":
                bodySection.push(row2);
                break;
              case "tfoot":
                footSection.push(row2);
                break;
              case "colgroup":
                columnGroupsSection.push(row2);
                break;
            }
          });
          renderOrRemoveSection(columnGroupsSection, "colgroup");
          renderOrRemoveSection(headSection, "thead");
          renderOrRemoveSection(bodySection, "tbody");
          renderOrRemoveSection(footSection, "tfoot");
          return {
            newRows,
            newCells
          };
        };
        var copy = function(grid2) {
          return map$12(grid2, function(row2) {
            var tr = shallow(row2.element);
            each$2(row2.cells, function(cell2) {
              var clonedCell = deep(cell2.element);
              setIfNot(clonedCell, "colspan", cell2.colspan, 1);
              setIfNot(clonedCell, "rowspan", cell2.rowspan, 1);
              append$1(tr, clonedCell);
            });
            return tr;
          });
        };
        var getColumn = function(grid2, index) {
          return map$12(grid2, function(row2) {
            return getCell(row2, index);
          });
        };
        var getRow = function(grid2, index) {
          return grid2[index];
        };
        var findDiff = function(xs, comp) {
          if (xs.length === 0) {
            return 0;
          }
          var first2 = xs[0];
          var index = findIndex2(xs, function(x2) {
            return !comp(first2.element, x2.element);
          });
          return index.getOr(xs.length);
        };
        var subgrid = function(grid2, row2, column, comparator) {
          var gridRow = getRow(grid2, row2);
          var isColRow = gridRow.section === "colgroup";
          var colspan = findDiff(gridRow.cells.slice(column), comparator);
          var rowspan = isColRow ? 1 : findDiff(getColumn(grid2.slice(row2), column), comparator);
          return {
            colspan,
            rowspan
          };
        };
        var toDetails = function(grid2, comparator) {
          var seen = map$12(grid2, function(row2) {
            return map$12(row2.cells, never);
          });
          var updateSeen = function(rowIndex, columnIndex, rowspan, colspan) {
            for (var row2 = rowIndex; row2 < rowIndex + rowspan; row2++) {
              for (var column = columnIndex; column < columnIndex + colspan; column++) {
                seen[row2][column] = true;
              }
            }
          };
          return map$12(grid2, function(row2, rowIndex) {
            var details = bind$2(row2.cells, function(cell2, columnIndex) {
              if (seen[rowIndex][columnIndex] === false) {
                var result = subgrid(grid2, rowIndex, columnIndex, comparator);
                updateSeen(rowIndex, columnIndex, result.rowspan, result.colspan);
                return [detailnew(cell2.element, result.rowspan, result.colspan, cell2.isNew)];
              } else {
                return [];
              }
            });
            return rowdetailnew(row2.element, details, row2.section, row2.isNew);
          });
        };
        var toGrid = function(warehouse, generators, isNew) {
          var grid2 = [];
          each$2(warehouse.colgroups, function(colgroup2) {
            var colgroupCols = [];
            for (var columnIndex2 = 0; columnIndex2 < warehouse.grid.columns; columnIndex2++) {
              var element2 = Warehouse.getColumnAt(warehouse, columnIndex2).map(function(column) {
                return elementnew(column.element, isNew, false);
              }).getOrThunk(function() {
                return elementnew(generators.colGap(), true, false);
              });
              colgroupCols.push(element2);
            }
            grid2.push(rowcells(colgroup2.element, colgroupCols, "colgroup", isNew));
          });
          for (var rowIndex = 0; rowIndex < warehouse.grid.rows; rowIndex++) {
            var rowCells = [];
            for (var columnIndex = 0; columnIndex < warehouse.grid.columns; columnIndex++) {
              var element = Warehouse.getAt(warehouse, rowIndex, columnIndex).map(function(item) {
                return elementnew(item.element, isNew, item.isLocked);
              }).getOrThunk(function() {
                return elementnew(generators.gap(), true, false);
              });
              rowCells.push(element);
            }
            var rowDetail = warehouse.all[rowIndex];
            var row2 = rowcells(rowDetail.element, rowCells, rowDetail.section, isNew);
            grid2.push(row2);
          }
          return grid2;
        };
        var fromWarehouse = function(warehouse, generators) {
          return toGrid(warehouse, generators, false);
        };
        var toDetailList = function(grid2) {
          return toDetails(grid2, eq$1);
        };
        var findInWarehouse = function(warehouse, element) {
          return findMap(warehouse.all, function(r3) {
            return find$1(r3.cells, function(e2) {
              return eq$1(element, e2.element);
            });
          });
        };
        var extractCells = function(warehouse, target, predicate) {
          var details = map$12(target.selection, function(cell$1) {
            return cell(cell$1).bind(function(lc) {
              return findInWarehouse(warehouse, lc);
            }).filter(predicate);
          });
          var cells2 = cat(details);
          return someIf(cells2.length > 0, cells2);
        };
        var run = function(operation, extract2, adjustment, postAction, genWrappers) {
          return function(wire, table2, target, generators, behaviours) {
            var warehouse = Warehouse.fromTable(table2);
            var tableSection = Optional.from(behaviours === null || behaviours === void 0 ? void 0 : behaviours.section).getOrThunk(TableSection.fallback);
            var output = extract2(warehouse, target).map(function(info) {
              var model = fromWarehouse(warehouse, generators);
              var result = operation(model, info, eq$1, genWrappers(generators), tableSection);
              var lockedColumns = getLockedColumnsFromGrid(result.grid);
              var grid2 = toDetailList(result.grid);
              return {
                info,
                grid: grid2,
                cursor: result.cursor,
                lockedColumns
              };
            });
            return output.bind(function(out) {
              var newElements = render$1(table2, out.grid);
              var tableSizing = Optional.from(behaviours === null || behaviours === void 0 ? void 0 : behaviours.sizing).getOrThunk(function() {
                return TableSize.getTableSize(table2);
              });
              var resizing = Optional.from(behaviours === null || behaviours === void 0 ? void 0 : behaviours.resize).getOrThunk(preserveTable);
              adjustment(table2, out.grid, out.info, {
                sizing: tableSizing,
                resize: resizing,
                section: tableSection
              });
              postAction(table2);
              refresh(wire, table2);
              remove$7(table2, LOCKED_COL_ATTR);
              if (out.lockedColumns.length > 0) {
                set$2(table2, LOCKED_COL_ATTR, out.lockedColumns.join(","));
              }
              return Optional.some({
                cursor: out.cursor,
                newRows: newElements.newRows,
                newCells: newElements.newCells
              });
            });
          };
        };
        var onPaste = function(warehouse, target) {
          return cell(target.element).bind(function(cell2) {
            return findInWarehouse(warehouse, cell2).map(function(details) {
              var value2 = __assign(__assign({}, details), {
                generators: target.generators,
                clipboard: target.clipboard
              });
              return value2;
            });
          });
        };
        var onPasteByEditor = function(warehouse, target) {
          return extractCells(warehouse, target, always).map(function(cells2) {
            return {
              cells: cells2,
              generators: target.generators,
              clipboard: target.clipboard
            };
          });
        };
        var onMergable = function(_warehouse, target) {
          return target.mergable;
        };
        var onUnmergable = function(_warehouse, target) {
          return target.unmergable;
        };
        var onCells = function(warehouse, target) {
          return extractCells(warehouse, target, always);
        };
        var onUnlockedCells = function(warehouse, target) {
          return extractCells(warehouse, target, function(detail2) {
            return !detail2.isLocked;
          });
        };
        var isUnlockedTableCell = function(warehouse, cell2) {
          return findInWarehouse(warehouse, cell2).exists(function(detail2) {
            return !detail2.isLocked;
          });
        };
        var allUnlocked = function(warehouse, cells2) {
          return forall(cells2, function(cell2) {
            return isUnlockedTableCell(warehouse, cell2);
          });
        };
        var onUnlockedMergable = function(warehouse, target) {
          return onMergable(warehouse, target).filter(function(mergeable) {
            return allUnlocked(warehouse, mergeable.cells);
          });
        };
        var onUnlockedUnmergable = function(warehouse, target) {
          return onUnmergable(warehouse, target).filter(function(cells2) {
            return allUnlocked(warehouse, cells2);
          });
        };
        var merge$2 = function(grid2, bounds2, comparator, substitution) {
          var rows2 = extractGridDetails(grid2).rows;
          if (rows2.length === 0) {
            return grid2;
          }
          for (var i2 = bounds2.startRow; i2 <= bounds2.finishRow; i2++) {
            for (var j2 = bounds2.startCol; j2 <= bounds2.finishCol; j2++) {
              var row2 = rows2[i2];
              var isLocked = getCell(row2, j2).isLocked;
              mutateCell(row2, j2, elementnew(substitution(), false, isLocked));
            }
          }
          return grid2;
        };
        var unmerge = function(grid2, target, comparator, substitution) {
          var rows2 = extractGridDetails(grid2).rows;
          var first2 = true;
          for (var i2 = 0; i2 < rows2.length; i2++) {
            for (var j2 = 0; j2 < cellLength(rows2[0]); j2++) {
              var row2 = rows2[i2];
              var currentCell = getCell(row2, j2);
              var currentCellElm = currentCell.element;
              var isToReplace = comparator(currentCellElm, target);
              if (isToReplace === true && first2 === false) {
                mutateCell(row2, j2, elementnew(substitution(), true, currentCell.isLocked));
              } else if (isToReplace === true) {
                first2 = false;
              }
            }
          }
          return grid2;
        };
        var uniqueCells = function(row2, comparator) {
          return foldl(row2, function(rest, cell2) {
            return exists(rest, function(currentCell) {
              return comparator(currentCell.element, cell2.element);
            }) ? rest : rest.concat([cell2]);
          }, []);
        };
        var splitCols = function(grid2, index, comparator, substitution) {
          if (index > 0 && index < grid2[0].cells.length) {
            each$2(grid2, function(row2) {
              var prevCell = row2.cells[index - 1];
              var current = row2.cells[index];
              var isToReplace = comparator(current.element, prevCell.element);
              if (isToReplace) {
                mutateCell(row2, index, elementnew(substitution(), true, current.isLocked));
              }
            });
          }
          return grid2;
        };
        var splitRows = function(grid2, index, comparator, substitution) {
          var rows2 = extractGridDetails(grid2).rows;
          if (index > 0 && index < rows2.length) {
            var rowPrevCells = rows2[index - 1].cells;
            var cells2 = uniqueCells(rowPrevCells, comparator);
            each$2(cells2, function(cell2) {
              var replacement = Optional.none();
              for (var i2 = index; i2 < rows2.length; i2++) {
                var _loop_1 = function(j3) {
                  var row2 = rows2[i2];
                  var current = getCell(row2, j3);
                  var isToReplace = comparator(current.element, cell2.element);
                  if (isToReplace) {
                    if (replacement.isNone()) {
                      replacement = Optional.some(substitution());
                    }
                    replacement.each(function(sub) {
                      mutateCell(row2, j3, elementnew(sub, true, current.isLocked));
                    });
                  }
                };
                for (var j2 = 0; j2 < cellLength(rows2[0]); j2++) {
                  _loop_1(j2);
                }
              }
            });
          }
          return grid2;
        };
        var value$1 = function(o2) {
          var or = function(_opt) {
            return value$1(o2);
          };
          var orThunk = function(_f) {
            return value$1(o2);
          };
          var map4 = function(f2) {
            return value$1(f2(o2));
          };
          var mapError = function(_f) {
            return value$1(o2);
          };
          var each3 = function(f2) {
            f2(o2);
          };
          var bind2 = function(f2) {
            return f2(o2);
          };
          var fold = function(_2, onValue) {
            return onValue(o2);
          };
          var exists2 = function(f2) {
            return f2(o2);
          };
          var forall2 = function(f2) {
            return f2(o2);
          };
          var toOptional = function() {
            return Optional.some(o2);
          };
          return {
            isValue: always,
            isError: never,
            getOr: constant(o2),
            getOrThunk: constant(o2),
            getOrDie: constant(o2),
            or,
            orThunk,
            fold,
            map: map4,
            mapError,
            each: each3,
            bind: bind2,
            exists: exists2,
            forall: forall2,
            toOptional
          };
        };
        var error3 = function(message) {
          var getOrThunk = function(f2) {
            return f2();
          };
          var getOrDie = function() {
            return die(String(message))();
          };
          var or = identity;
          var orThunk = function(f2) {
            return f2();
          };
          var map4 = function(_f) {
            return error3(message);
          };
          var mapError = function(f2) {
            return error3(f2(message));
          };
          var bind2 = function(_f) {
            return error3(message);
          };
          var fold = function(onError, _2) {
            return onError(message);
          };
          return {
            isValue: never,
            isError: always,
            getOr: identity,
            getOrThunk,
            getOrDie,
            or,
            orThunk,
            fold,
            map: map4,
            mapError,
            each: noop3,
            bind: bind2,
            exists: never,
            forall: always,
            toOptional: Optional.none
          };
        };
        var fromOption = function(opt, err) {
          return opt.fold(function() {
            return error3(err);
          }, value$1);
        };
        var Result = {
          value: value$1,
          error: error3,
          fromOption
        };
        var measure = function(startAddress, gridA, gridB) {
          if (startAddress.row >= gridA.length || startAddress.column > cellLength(gridA[0])) {
            return Result.error("invalid start address out of table bounds, row: " + startAddress.row + ", column: " + startAddress.column);
          }
          var rowRemainder = gridA.slice(startAddress.row);
          var colRemainder = rowRemainder[0].cells.slice(startAddress.column);
          var colRequired = cellLength(gridB[0]);
          var rowRequired = gridB.length;
          return Result.value({
            rowDelta: rowRemainder.length - rowRequired,
            colDelta: colRemainder.length - colRequired
          });
        };
        var measureWidth = function(gridA, gridB) {
          var colLengthA = cellLength(gridA[0]);
          var colLengthB = cellLength(gridB[0]);
          return {
            rowDelta: 0,
            colDelta: colLengthA - colLengthB
          };
        };
        var measureHeight = function(gridA, gridB) {
          var rowLengthA = gridA.length;
          var rowLengthB = gridB.length;
          return {
            rowDelta: rowLengthA - rowLengthB,
            colDelta: 0
          };
        };
        var generateElements = function(amount, row2, generators, isLocked) {
          var generator = row2.section === "colgroup" ? generators.col : generators.cell;
          return range$1(amount, function(idx) {
            return elementnew(generator(), true, isLocked(idx));
          });
        };
        var rowFill = function(grid2, amount, generators, lockedColumns) {
          var exampleRow = grid2[grid2.length - 1];
          return grid2.concat(range$1(amount, function() {
            var generator = exampleRow.section === "colgroup" ? generators.colgroup : generators.row;
            var row2 = clone$12(exampleRow, generator, identity);
            var elements2 = generateElements(row2.cells.length, row2, generators, function(idx) {
              return has$1(lockedColumns, idx.toString());
            });
            return setCells(row2, elements2);
          }));
        };
        var colFill = function(grid2, amount, generators, startIndex) {
          return map$12(grid2, function(row2) {
            var newChildren = generateElements(amount, row2, generators, never);
            return addCells(row2, startIndex, newChildren);
          });
        };
        var lockedColFill = function(grid2, generators, lockedColumns) {
          return map$12(grid2, function(row2) {
            return foldl(lockedColumns, function(acc, colNum) {
              var newChild = generateElements(1, row2, generators, always)[0];
              return addCell(acc, colNum, newChild);
            }, row2);
          });
        };
        var tailor = function(gridA, delta, generators) {
          var fillCols = delta.colDelta < 0 ? colFill : identity;
          var fillRows = delta.rowDelta < 0 ? rowFill : identity;
          var lockedColumns = getLockedColumnsFromGrid(gridA);
          var gridWidth = cellLength(gridA[0]);
          var isLastColLocked = exists(lockedColumns, function(locked) {
            return locked === gridWidth - 1;
          });
          var modifiedCols = fillCols(gridA, Math.abs(delta.colDelta), generators, isLastColLocked ? gridWidth - 1 : gridWidth);
          var newLockedColumns = getLockedColumnsFromGrid(modifiedCols);
          return fillRows(modifiedCols, Math.abs(delta.rowDelta), generators, mapToObject(newLockedColumns, always));
        };
        var isSpanning = function(grid2, row2, col2, comparator) {
          var candidate = getCell(grid2[row2], col2);
          var matching = curry(comparator, candidate.element);
          var currentRow = grid2[row2];
          return grid2.length > 1 && cellLength(currentRow) > 1 && (col2 > 0 && matching(getCellElement(currentRow, col2 - 1)) || col2 < currentRow.cells.length - 1 && matching(getCellElement(currentRow, col2 + 1)) || row2 > 0 && matching(getCellElement(grid2[row2 - 1], col2)) || row2 < grid2.length - 1 && matching(getCellElement(grid2[row2 + 1], col2)));
        };
        var mergeTables = function(startAddress, gridA, gridB, generator, comparator, lockedColumns) {
          var startRow = startAddress.row;
          var startCol = startAddress.column;
          var mergeHeight = gridB.length;
          var mergeWidth = cellLength(gridB[0]);
          var endRow = startRow + mergeHeight;
          var endCol = startCol + mergeWidth + lockedColumns.length;
          var lockedColumnObj = mapToObject(lockedColumns, always);
          for (var r3 = startRow; r3 < endRow; r3++) {
            var skippedCol = 0;
            for (var c2 = startCol; c2 < endCol; c2++) {
              if (lockedColumnObj[c2]) {
                skippedCol++;
                continue;
              }
              if (isSpanning(gridA, r3, c2, comparator)) {
                unmerge(gridA, getCellElement(gridA[r3], c2), comparator, generator.cell);
              }
              var gridBColIndex = c2 - startCol - skippedCol;
              var newCell = getCell(gridB[r3 - startRow], gridBColIndex);
              var newCellElm = newCell.element;
              var replacement = generator.replace(newCellElm);
              mutateCell(gridA[r3], c2, elementnew(replacement, true, newCell.isLocked));
            }
          }
          return gridA;
        };
        var getValidStartAddress = function(currentStartAddress, grid2, lockedColumns) {
          var gridColLength = cellLength(grid2[0]);
          var adjustedRowAddress = extractGridDetails(grid2).cols.length + currentStartAddress.row;
          var possibleColAddresses = range$1(gridColLength - currentStartAddress.column, function(num) {
            return num + currentStartAddress.column;
          });
          var validColAddress = find$1(possibleColAddresses, function(num) {
            return forall(lockedColumns, function(col2) {
              return col2 !== num;
            });
          }).getOr(gridColLength - 1);
          return {
            row: adjustedRowAddress,
            column: validColAddress
          };
        };
        var getLockedColumnsWithinBounds = function(startAddress, grid2, lockedColumns) {
          return filter$2(lockedColumns, function(colNum) {
            return colNum >= startAddress.column && colNum <= cellLength(grid2[0]) + startAddress.column;
          });
        };
        var merge$1 = function(startAddress, gridA, gridB, generator, comparator) {
          var lockedColumns = getLockedColumnsFromGrid(gridA);
          var validStartAddress = getValidStartAddress(startAddress, gridA, lockedColumns);
          var gridBRows = extractGridDetails(gridB).rows;
          var lockedColumnsWithinBounds = getLockedColumnsWithinBounds(validStartAddress, gridBRows, lockedColumns);
          var result = measure(validStartAddress, gridA, gridBRows);
          return result.map(function(diff) {
            var delta = __assign(__assign({}, diff), { colDelta: diff.colDelta - lockedColumnsWithinBounds.length });
            var fittedGrid = tailor(gridA, delta, generator);
            var newLockedColumns = getLockedColumnsFromGrid(fittedGrid);
            var newLockedColumnsWithinBounds = getLockedColumnsWithinBounds(validStartAddress, gridBRows, newLockedColumns);
            return mergeTables(validStartAddress, fittedGrid, gridBRows, generator, comparator, newLockedColumnsWithinBounds);
          });
        };
        var insertCols = function(index, gridA, gridB, generator, comparator) {
          splitCols(gridA, index, comparator, generator.cell);
          var delta = measureHeight(gridB, gridA);
          var fittedNewGrid = tailor(gridB, delta, generator);
          var secondDelta = measureHeight(gridA, fittedNewGrid);
          var fittedOldGrid = tailor(gridA, secondDelta, generator);
          return map$12(fittedOldGrid, function(gridRow, i2) {
            return addCells(gridRow, index, fittedNewGrid[i2].cells);
          });
        };
        var insertRows = function(index, gridA, gridB, generator, comparator) {
          splitRows(gridA, index, comparator, generator.cell);
          var locked = getLockedColumnsFromGrid(gridA);
          var diff = measureWidth(gridA, gridB);
          var delta = __assign(__assign({}, diff), { colDelta: diff.colDelta - locked.length });
          var fittedOldGrid = tailor(gridA, delta, generator);
          var _a = extractGridDetails(fittedOldGrid), oldCols = _a.cols, oldRows = _a.rows;
          var newLocked = getLockedColumnsFromGrid(fittedOldGrid);
          var secondDiff = measureWidth(gridB, gridA);
          var secondDelta = __assign(__assign({}, secondDiff), { colDelta: secondDiff.colDelta + newLocked.length });
          var fittedGridB = lockedColFill(gridB, generator, newLocked);
          var fittedNewGrid = tailor(fittedGridB, secondDelta, generator);
          return oldCols.concat(oldRows.slice(0, index)).concat(fittedNewGrid).concat(oldRows.slice(index, oldRows.length));
        };
        var cloneRow = function(row2, cloneCell, comparator, substitution) {
          return clone$12(row2, function(elem) {
            return substitution(elem, comparator);
          }, cloneCell);
        };
        var insertRowAt = function(grid2, index, example, comparator, substitution) {
          var _a = extractGridDetails(grid2), rows2 = _a.rows, cols = _a.cols;
          var before2 = rows2.slice(0, index);
          var after2 = rows2.slice(index);
          var newRow = cloneRow(rows2[example], function(ex, c2) {
            var withinSpan = index > 0 && index < rows2.length && comparator(getCellElement(rows2[index - 1], c2), getCellElement(rows2[index], c2));
            var ret = withinSpan ? getCell(rows2[index], c2) : elementnew(substitution(ex.element, comparator), true, ex.isLocked);
            return ret;
          }, comparator, substitution);
          return cols.concat(before2).concat([newRow]).concat(after2);
        };
        var getElementFor = function(row2, column, section2, withinSpan, example, comparator, substitution) {
          if (section2 === "colgroup" || !withinSpan) {
            var cell2 = getCell(row2, example);
            return elementnew(substitution(cell2.element, comparator), true, false);
          } else {
            return getCell(row2, column);
          }
        };
        var insertColumnAt = function(grid2, index, example, comparator, substitution) {
          return map$12(grid2, function(row2) {
            var withinSpan = index > 0 && index < cellLength(row2) && comparator(getCellElement(row2, index - 1), getCellElement(row2, index));
            var sub = getElementFor(row2, index, row2.section, withinSpan, example, comparator, substitution);
            return addCell(row2, index, sub);
          });
        };
        var deleteColumnsAt = function(grid2, columns2) {
          return bind$2(grid2, function(row2) {
            var existingCells = row2.cells;
            var cells2 = foldr(columns2, function(acc, column) {
              return column >= 0 && column < acc.length ? acc.slice(0, column).concat(acc.slice(column + 1)) : acc;
            }, existingCells);
            return cells2.length > 0 ? [rowcells(row2.element, cells2, row2.section, row2.isNew)] : [];
          });
        };
        var deleteRowsAt = function(grid2, start4, finish) {
          var _a = extractGridDetails(grid2), rows2 = _a.rows, cols = _a.cols;
          return cols.concat(rows2.slice(0, start4)).concat(rows2.slice(finish + 1));
        };
        var notInStartRow = function(grid2, rowIndex, colIndex, comparator) {
          return getCellElement(grid2[rowIndex], colIndex) !== void 0 && (rowIndex > 0 && comparator(getCellElement(grid2[rowIndex - 1], colIndex), getCellElement(grid2[rowIndex], colIndex)));
        };
        var notInStartColumn = function(row2, index, comparator) {
          return index > 0 && comparator(getCellElement(row2, index - 1), getCellElement(row2, index));
        };
        var isDuplicatedCell = function(grid2, rowIndex, colIndex, comparator) {
          return notInStartRow(grid2, rowIndex, colIndex, comparator) || notInStartColumn(grid2[rowIndex], colIndex, comparator);
        };
        var rowReplacerPredicate = function(targetRow, columnHeaders) {
          var entireTableIsHeader = forall(columnHeaders, identity) && isHeaderCells(targetRow.cells);
          return entireTableIsHeader ? always : function(cell2, _rowIndex, colIndex) {
            var type2 = name(cell2.element);
            return !(type2 === "th" && columnHeaders[colIndex]);
          };
        };
        var columnReplacePredicate = function(targetColumn, rowHeaders) {
          var entireTableIsHeader = forall(rowHeaders, identity) && isHeaderCells(targetColumn);
          return entireTableIsHeader ? always : function(cell2, rowIndex, _colIndex) {
            var type2 = name(cell2.element);
            return !(type2 === "th" && rowHeaders[rowIndex]);
          };
        };
        var determineScope = function(applyScope, element, newScope, isInHeader) {
          var hasSpan = function(scope) {
            return scope === "row" ? hasRowspan(element) : hasColspan(element);
          };
          var getScope2 = function(scope) {
            return hasSpan(scope) ? scope + "group" : scope;
          };
          if (applyScope) {
            return isHeaderCell(element) ? getScope2(newScope) : null;
          } else if (isInHeader && isHeaderCell(element)) {
            var oppositeScope = newScope === "row" ? "col" : "row";
            return getScope2(oppositeScope);
          } else {
            return null;
          }
        };
        var rowScopeGenerator = function(applyScope, columnHeaders) {
          return function(cell2, rowIndex, columnIndex) {
            return Optional.some(determineScope(applyScope, cell2.element, "col", columnHeaders[columnIndex]));
          };
        };
        var columnScopeGenerator = function(applyScope, rowHeaders) {
          return function(cell2, rowIndex) {
            return Optional.some(determineScope(applyScope, cell2.element, "row", rowHeaders[rowIndex]));
          };
        };
        var replace = function(cell2, comparator, substitute) {
          return elementnew(substitute(cell2.element, comparator), true, cell2.isLocked);
        };
        var replaceIn = function(grid2, targets, comparator, substitute, replacer, genScope, shouldReplace) {
          var isTarget = function(cell2) {
            return exists(targets, function(target) {
              return comparator(cell2.element, target.element);
            });
          };
          return map$12(grid2, function(row2, rowIndex) {
            return mapCells(row2, function(cell2, colIndex) {
              if (isTarget(cell2)) {
                var newCell_1 = shouldReplace(cell2, rowIndex, colIndex) ? replacer(cell2, comparator, substitute) : cell2;
                genScope(newCell_1, rowIndex, colIndex).each(function(scope) {
                  setOptions(newCell_1.element, { scope: Optional.from(scope) });
                });
                return newCell_1;
              } else {
                return cell2;
              }
            });
          });
        };
        var getColumnCells = function(rows2, columnIndex, comparator) {
          return bind$2(rows2, function(row2, i2) {
            return isDuplicatedCell(rows2, i2, columnIndex, comparator) ? [] : [getCell(row2, columnIndex)];
          });
        };
        var getRowCells = function(rows2, rowIndex, comparator) {
          var targetRow = rows2[rowIndex];
          return bind$2(targetRow.cells, function(item, i2) {
            return isDuplicatedCell(rows2, rowIndex, i2, comparator) ? [] : [item];
          });
        };
        var replaceColumns = function(grid2, indexes, applyScope, comparator, substitution) {
          var rows2 = extractGridDetails(grid2).rows;
          var targets = bind$2(indexes, function(index) {
            return getColumnCells(rows2, index, comparator);
          });
          var rowHeaders = map$12(grid2, function(row2) {
            return isHeaderCells(row2.cells);
          });
          var shouldReplaceCell = columnReplacePredicate(targets, rowHeaders);
          var scopeGenerator = columnScopeGenerator(applyScope, rowHeaders);
          return replaceIn(grid2, targets, comparator, substitution, replace, scopeGenerator, shouldReplaceCell);
        };
        var replaceRows = function(grid2, indexes, section2, applyScope, comparator, substitution, tableSection) {
          var _a = extractGridDetails(grid2), cols = _a.cols, rows2 = _a.rows;
          var targetRow = rows2[indexes[0]];
          var targets = bind$2(indexes, function(index) {
            return getRowCells(rows2, index, comparator);
          });
          var columnHeaders = map$12(targetRow.cells, function(_cell, index) {
            return isHeaderCells(getColumnCells(rows2, index, comparator));
          });
          var newRows = __spreadArray([], rows2, true);
          each$2(indexes, function(index) {
            newRows[index] = tableSection.transformRow(rows2[index], section2);
          });
          var newGrid = cols.concat(newRows);
          var shouldReplaceCell = rowReplacerPredicate(targetRow, columnHeaders);
          var scopeGenerator = rowScopeGenerator(applyScope, columnHeaders);
          return replaceIn(newGrid, targets, comparator, substitution, tableSection.transformCell, scopeGenerator, shouldReplaceCell);
        };
        var replaceCells = function(grid2, details, comparator, substitution) {
          var rows2 = extractGridDetails(grid2).rows;
          var targetCells = map$12(details, function(detail2) {
            return getCell(rows2[detail2.row], detail2.column);
          });
          return replaceIn(grid2, targetCells, comparator, substitution, replace, Optional.none, always);
        };
        var uniqueColumns = function(details) {
          var uniqueCheck = function(rest, detail2) {
            var columnExists = exists(rest, function(currentDetail) {
              return currentDetail.column === detail2.column;
            });
            return columnExists ? rest : rest.concat([detail2]);
          };
          return foldl(details, uniqueCheck, []).sort(function(detailA, detailB) {
            return detailA.column - detailB.column;
          });
        };
        var isCol = isTag("col");
        var isColgroup = isTag("colgroup");
        var isRow$1 = function(element) {
          return name(element) === "tr" || isColgroup(element);
        };
        var elementToData = function(element) {
          var colspan = getAttrValue(element, "colspan", 1);
          var rowspan = getAttrValue(element, "rowspan", 1);
          return {
            element,
            colspan,
            rowspan
          };
        };
        var modification = function(generators, toData) {
          if (toData === void 0) {
            toData = elementToData;
          }
          var nuCell = function(data) {
            return isCol(data.element) ? generators.col(data) : generators.cell(data);
          };
          var nuRow = function(data) {
            return isColgroup(data.element) ? generators.colgroup(data) : generators.row(data);
          };
          var add4 = function(element) {
            if (isRow$1(element)) {
              return nuRow({ element });
            } else {
              var replacement = nuCell(toData(element));
              recent = Optional.some({
                item: element,
                replacement
              });
              return replacement;
            }
          };
          var recent = Optional.none();
          var getOrInit = function(element, comparator) {
            return recent.fold(function() {
              return add4(element);
            }, function(p2) {
              return comparator(element, p2.item) ? p2.replacement : add4(element);
            });
          };
          return { getOrInit };
        };
        var transform = function(tag) {
          return function(generators) {
            var list = [];
            var find2 = function(element, comparator) {
              return find$1(list, function(x2) {
                return comparator(x2.item, element);
              });
            };
            var makeNew = function(element) {
              var attrs = tag === "td" ? { scope: null } : {};
              var cell2 = generators.replace(element, tag, attrs);
              list.push({
                item: element,
                sub: cell2
              });
              return cell2;
            };
            var replaceOrInit = function(element, comparator) {
              if (isRow$1(element) || isCol(element)) {
                return element;
              } else {
                return find2(element, comparator).fold(function() {
                  return makeNew(element);
                }, function(p2) {
                  return comparator(element, p2.item) ? p2.sub : makeNew(element);
                });
              }
            };
            return { replaceOrInit };
          };
        };
        var getScopeAttribute = function(cell2) {
          return getOpt(cell2, "scope").map(function(attribute) {
            return attribute.substr(0, 3);
          });
        };
        var merging = function(generators) {
          var unmerge2 = function(cell2) {
            var scope = getScopeAttribute(cell2);
            scope.each(function(attribute) {
              return set$2(cell2, "scope", attribute);
            });
            return function() {
              var raw = generators.cell({
                element: cell2,
                colspan: 1,
                rowspan: 1
              });
              remove$6(raw, "width");
              remove$6(cell2, "width");
              scope.each(function(attribute) {
                return set$2(raw, "scope", attribute);
              });
              return raw;
            };
          };
          var merge3 = function(cells2) {
            var getScopeProperty = function() {
              var stringAttributes = cat(map$12(cells2, getScopeAttribute));
              if (stringAttributes.length === 0) {
                return Optional.none();
              } else {
                var baseScope_1 = stringAttributes[0];
                var scopes_1 = [
                  "row",
                  "col"
                ];
                var isMixed = exists(stringAttributes, function(attribute) {
                  return attribute !== baseScope_1 && contains$2(scopes_1, attribute);
                });
                return isMixed ? Optional.none() : Optional.from(baseScope_1);
              }
            };
            remove$6(cells2[0], "width");
            getScopeProperty().fold(function() {
              return remove$7(cells2[0], "scope");
            }, function(attribute) {
              return set$2(cells2[0], "scope", attribute + "group");
            });
            return constant(cells2[0]);
          };
          return {
            unmerge: unmerge2,
            merge: merge3
          };
        };
        var Generators = {
          modification,
          transform,
          merging
        };
        var blockList = [
          "body",
          "p",
          "div",
          "article",
          "aside",
          "figcaption",
          "figure",
          "footer",
          "header",
          "nav",
          "section",
          "ol",
          "ul",
          "table",
          "thead",
          "tfoot",
          "tbody",
          "caption",
          "tr",
          "td",
          "th",
          "h1",
          "h2",
          "h3",
          "h4",
          "h5",
          "h6",
          "blockquote",
          "pre",
          "address"
        ];
        var isList$1 = function(universe2, item) {
          var tagName = universe2.property().name(item);
          return contains$2([
            "ol",
            "ul"
          ], tagName);
        };
        var isBlock$1 = function(universe2, item) {
          var tagName = universe2.property().name(item);
          return contains$2(blockList, tagName);
        };
        var isEmptyTag$1 = function(universe2, item) {
          return contains$2([
            "br",
            "img",
            "hr",
            "input"
          ], universe2.property().name(item));
        };
        var universe$1 = DomUniverse();
        var isBlock = function(element) {
          return isBlock$1(universe$1, element);
        };
        var isList = function(element) {
          return isList$1(universe$1, element);
        };
        var isEmptyTag = function(element) {
          return isEmptyTag$1(universe$1, element);
        };
        var merge2 = function(cells2) {
          var isBr2 = function(el) {
            return name(el) === "br";
          };
          var advancedBr = function(children2) {
            return forall(children2, function(c2) {
              return isBr2(c2) || isText(c2) && get$9(c2).trim().length === 0;
            });
          };
          var isListItem = function(el) {
            return name(el) === "li" || ancestor$2(el, isList).isSome();
          };
          var siblingIsBlock = function(el) {
            return nextSibling(el).map(function(rightSibling) {
              if (isBlock(rightSibling)) {
                return true;
              }
              if (isEmptyTag(rightSibling)) {
                return name(rightSibling) === "img" ? false : true;
              }
              return false;
            }).getOr(false);
          };
          var markCell = function(cell2) {
            return last$1(cell2).bind(function(rightEdge) {
              var rightSiblingIsBlock = siblingIsBlock(rightEdge);
              return parent(rightEdge).map(function(parent2) {
                return rightSiblingIsBlock === true || isListItem(parent2) || isBr2(rightEdge) || isBlock(parent2) && !eq$1(cell2, parent2) ? [] : [SugarElement.fromTag("br")];
              });
            }).getOr([]);
          };
          var markContent = function() {
            var content = bind$2(cells2, function(cell2) {
              var children2 = children$3(cell2);
              return advancedBr(children2) ? [] : children2.concat(markCell(cell2));
            });
            return content.length === 0 ? [SugarElement.fromTag("br")] : content;
          };
          var contents = markContent();
          empty(cells2[0]);
          append(cells2[0], contents);
        };
        var isEditable = function(elem) {
          return isEditable$1(elem, true);
        };
        var prune3 = function(table2) {
          var cells2 = cells$1(table2);
          if (cells2.length === 0) {
            remove$5(table2);
          }
        };
        var outcome = function(grid2, cursor) {
          return {
            grid: grid2,
            cursor
          };
        };
        var findEditableCursorPosition = function(rows2) {
          return findMap(rows2, function(row2) {
            return findMap(row2.cells, function(cell2) {
              var elem = cell2.element;
              return someIf(isEditable(elem), elem);
            });
          });
        };
        var elementFromGrid = function(grid2, row2, column) {
          var _a, _b;
          var rows2 = extractGridDetails(grid2).rows;
          return Optional.from((_b = (_a = rows2[row2]) === null || _a === void 0 ? void 0 : _a.cells[column]) === null || _b === void 0 ? void 0 : _b.element).filter(isEditable).orThunk(function() {
            return findEditableCursorPosition(rows2);
          });
        };
        var bundle = function(grid2, row2, column) {
          var cursorElement = elementFromGrid(grid2, row2, column);
          return outcome(grid2, cursorElement);
        };
        var uniqueRows = function(details) {
          var rowCompilation = function(rest, detail2) {
            var rowExists = exists(rest, function(currentDetail) {
              return currentDetail.row === detail2.row;
            });
            return rowExists ? rest : rest.concat([detail2]);
          };
          return foldl(details, rowCompilation, []).sort(function(detailA, detailB) {
            return detailA.row - detailB.row;
          });
        };
        var opInsertRowsBefore = function(grid2, details, comparator, genWrappers) {
          var targetIndex = details[0].row;
          var rows2 = uniqueRows(details);
          var newGrid = foldr(rows2, function(acc, row2) {
            var newG = insertRowAt(acc.grid, targetIndex, row2.row + acc.delta, comparator, genWrappers.getOrInit);
            return {
              grid: newG,
              delta: acc.delta + 1
            };
          }, {
            grid: grid2,
            delta: 0
          }).grid;
          return bundle(newGrid, targetIndex, details[0].column);
        };
        var opInsertRowsAfter = function(grid2, details, comparator, genWrappers) {
          var rows2 = uniqueRows(details);
          var target = rows2[rows2.length - 1];
          var targetIndex = target.row + target.rowspan;
          var newGrid = foldr(rows2, function(newG, row2) {
            return insertRowAt(newG, targetIndex, row2.row, comparator, genWrappers.getOrInit);
          }, grid2);
          return bundle(newGrid, targetIndex, details[0].column);
        };
        var opInsertColumnsBefore = function(grid2, extractDetail, comparator, genWrappers) {
          var details = extractDetail.details;
          var columns2 = uniqueColumns(details);
          var targetIndex = columns2[0].column;
          var newGrid = foldr(columns2, function(acc, col2) {
            var newG = insertColumnAt(acc.grid, targetIndex, col2.column + acc.delta, comparator, genWrappers.getOrInit);
            return {
              grid: newG,
              delta: acc.delta + 1
            };
          }, {
            grid: grid2,
            delta: 0
          }).grid;
          return bundle(newGrid, details[0].row, targetIndex);
        };
        var opInsertColumnsAfter = function(grid2, extractDetail, comparator, genWrappers) {
          var details = extractDetail.details;
          var target = details[details.length - 1];
          var targetIndex = target.column + target.colspan;
          var columns2 = uniqueColumns(details);
          var newGrid = foldr(columns2, function(newG, col2) {
            return insertColumnAt(newG, targetIndex, col2.column, comparator, genWrappers.getOrInit);
          }, grid2);
          return bundle(newGrid, details[0].row, targetIndex);
        };
        var opMakeColumnsHeader = function(initialGrid, details, comparator, genWrappers) {
          var columns2 = uniqueColumns(details);
          var columnIndexes = map$12(columns2, function(detail2) {
            return detail2.column;
          });
          var newGrid = replaceColumns(initialGrid, columnIndexes, true, comparator, genWrappers.replaceOrInit);
          return bundle(newGrid, details[0].row, details[0].column);
        };
        var opMakeCellsHeader = function(initialGrid, details, comparator, genWrappers) {
          var newGrid = replaceCells(initialGrid, details, comparator, genWrappers.replaceOrInit);
          return bundle(newGrid, details[0].row, details[0].column);
        };
        var opUnmakeColumnsHeader = function(initialGrid, details, comparator, genWrappers) {
          var columns2 = uniqueColumns(details);
          var columnIndexes = map$12(columns2, function(detail2) {
            return detail2.column;
          });
          var newGrid = replaceColumns(initialGrid, columnIndexes, false, comparator, genWrappers.replaceOrInit);
          return bundle(newGrid, details[0].row, details[0].column);
        };
        var opUnmakeCellsHeader = function(initialGrid, details, comparator, genWrappers) {
          var newGrid = replaceCells(initialGrid, details, comparator, genWrappers.replaceOrInit);
          return bundle(newGrid, details[0].row, details[0].column);
        };
        var makeRowsSection = function(section2, applyScope) {
          return function(initialGrid, details, comparator, genWrappers, tableSection) {
            var rows2 = uniqueRows(details);
            var rowIndexes = map$12(rows2, function(detail2) {
              return detail2.row;
            });
            var newGrid = replaceRows(initialGrid, rowIndexes, section2, applyScope, comparator, genWrappers.replaceOrInit, tableSection);
            return bundle(newGrid, details[0].row, details[0].column);
          };
        };
        var opMakeRowsHeader = makeRowsSection("thead", true);
        var opMakeRowsBody = makeRowsSection("tbody", false);
        var opMakeRowsFooter = makeRowsSection("tfoot", false);
        var opEraseColumns = function(grid2, extractDetail, _comparator, _genWrappers) {
          var columns2 = uniqueColumns(extractDetail.details);
          var newGrid = deleteColumnsAt(grid2, map$12(columns2, function(column) {
            return column.column;
          }));
          var maxColIndex = newGrid.length > 0 ? newGrid[0].cells.length - 1 : 0;
          return bundle(newGrid, columns2[0].row, Math.min(columns2[0].column, maxColIndex));
        };
        var opEraseRows = function(grid2, details, _comparator, _genWrappers) {
          var rows2 = uniqueRows(details);
          var newGrid = deleteRowsAt(grid2, rows2[0].row, rows2[rows2.length - 1].row);
          var maxRowIndex = newGrid.length > 0 ? newGrid.length - 1 : 0;
          return bundle(newGrid, Math.min(details[0].row, maxRowIndex), details[0].column);
        };
        var opMergeCells = function(grid2, mergable2, comparator, genWrappers) {
          var cells2 = mergable2.cells;
          merge2(cells2);
          var newGrid = merge$2(grid2, mergable2.bounds, comparator, genWrappers.merge(cells2));
          return outcome(newGrid, Optional.from(cells2[0]));
        };
        var opUnmergeCells = function(grid2, unmergable2, comparator, genWrappers) {
          var unmerge$1 = function(b2, cell2) {
            return unmerge(b2, cell2, comparator, genWrappers.unmerge(cell2));
          };
          var newGrid = foldr(unmergable2, unmerge$1, grid2);
          return outcome(newGrid, Optional.from(unmergable2[0]));
        };
        var opPasteCells = function(grid2, pasteDetails, comparator, _genWrappers) {
          var gridify = function(table2, generators) {
            var wh = Warehouse.fromTable(table2);
            return toGrid(wh, generators, true);
          };
          var gridB = gridify(pasteDetails.clipboard, pasteDetails.generators);
          var startAddress = address(pasteDetails.row, pasteDetails.column);
          var mergedGrid = merge$1(startAddress, grid2, gridB, pasteDetails.generators, comparator);
          return mergedGrid.fold(function() {
            return outcome(grid2, Optional.some(pasteDetails.element));
          }, function(newGrid) {
            return bundle(newGrid, pasteDetails.row, pasteDetails.column);
          });
        };
        var gridifyRows = function(rows2, generators, context) {
          var pasteDetails = fromPastedRows(rows2, context.section);
          var wh = Warehouse.generate(pasteDetails);
          return toGrid(wh, generators, true);
        };
        var opPasteColsBefore = function(grid2, pasteDetails, comparator, _genWrappers) {
          var rows2 = extractGridDetails(grid2).rows;
          var index = pasteDetails.cells[0].column;
          var context = rows2[pasteDetails.cells[0].row];
          var gridB = gridifyRows(pasteDetails.clipboard, pasteDetails.generators, context);
          var mergedGrid = insertCols(index, grid2, gridB, pasteDetails.generators, comparator);
          return bundle(mergedGrid, pasteDetails.cells[0].row, pasteDetails.cells[0].column);
        };
        var opPasteColsAfter = function(grid2, pasteDetails, comparator, _genWrappers) {
          var rows2 = extractGridDetails(grid2).rows;
          var index = pasteDetails.cells[pasteDetails.cells.length - 1].column + pasteDetails.cells[pasteDetails.cells.length - 1].colspan;
          var context = rows2[pasteDetails.cells[0].row];
          var gridB = gridifyRows(pasteDetails.clipboard, pasteDetails.generators, context);
          var mergedGrid = insertCols(index, grid2, gridB, pasteDetails.generators, comparator);
          return bundle(mergedGrid, pasteDetails.cells[0].row, pasteDetails.cells[0].column);
        };
        var opPasteRowsBefore = function(grid2, pasteDetails, comparator, _genWrappers) {
          var rows2 = extractGridDetails(grid2).rows;
          var index = pasteDetails.cells[0].row;
          var context = rows2[index];
          var gridB = gridifyRows(pasteDetails.clipboard, pasteDetails.generators, context);
          var mergedGrid = insertRows(index, grid2, gridB, pasteDetails.generators, comparator);
          return bundle(mergedGrid, pasteDetails.cells[0].row, pasteDetails.cells[0].column);
        };
        var opPasteRowsAfter = function(grid2, pasteDetails, comparator, _genWrappers) {
          var rows2 = extractGridDetails(grid2).rows;
          var index = pasteDetails.cells[pasteDetails.cells.length - 1].row + pasteDetails.cells[pasteDetails.cells.length - 1].rowspan;
          var context = rows2[pasteDetails.cells[0].row];
          var gridB = gridifyRows(pasteDetails.clipboard, pasteDetails.generators, context);
          var mergedGrid = insertRows(index, grid2, gridB, pasteDetails.generators, comparator);
          return bundle(mergedGrid, pasteDetails.cells[0].row, pasteDetails.cells[0].column);
        };
        var opGetColumnsType = function(table2, target) {
          var house = Warehouse.fromTable(table2);
          var details = onCells(house, target);
          return details.bind(function(selectedCells) {
            var lastSelectedCell = selectedCells[selectedCells.length - 1];
            var minColRange = selectedCells[0].column;
            var maxColRange = lastSelectedCell.column + lastSelectedCell.colspan;
            var selectedColumnCells = flatten$1(map$12(house.all, function(row2) {
              return filter$2(row2.cells, function(cell2) {
                return cell2.column >= minColRange && cell2.column < maxColRange;
              });
            }));
            return findCommonCellType(selectedColumnCells);
          }).getOr("");
        };
        var opGetCellsType = function(table2, target) {
          var house = Warehouse.fromTable(table2);
          var details = onCells(house, target);
          return details.bind(findCommonCellType).getOr("");
        };
        var opGetRowsType = function(table2, target) {
          var house = Warehouse.fromTable(table2);
          var details = onCells(house, target);
          return details.bind(function(selectedCells) {
            var lastSelectedCell = selectedCells[selectedCells.length - 1];
            var minRowRange = selectedCells[0].row;
            var maxRowRange = lastSelectedCell.row + lastSelectedCell.rowspan;
            var selectedRows = house.all.slice(minRowRange, maxRowRange);
            return findCommonRowType(selectedRows);
          }).getOr("");
        };
        var resize = function(table2, list, details, behaviours) {
          return adjustWidthTo(table2, list, details, behaviours.sizing);
        };
        var adjustAndRedistributeWidths = function(table2, list, details, behaviours) {
          return adjustAndRedistributeWidths$1(table2, list, details, behaviours.sizing, behaviours.resize);
        };
        var firstColumnIsLocked = function(_warehouse, details) {
          return exists(details, function(detail2) {
            return detail2.column === 0 && detail2.isLocked;
          });
        };
        var lastColumnIsLocked = function(warehouse, details) {
          return exists(details, function(detail2) {
            return detail2.column + detail2.colspan >= warehouse.grid.columns && detail2.isLocked;
          });
        };
        var getColumnsWidth = function(warehouse, details) {
          var columns$12 = columns(warehouse);
          var uniqueCols = uniqueColumns(details);
          return foldl(uniqueCols, function(acc, detail2) {
            var column = columns$12[detail2.column];
            var colWidth = column.map(getOuter$2).getOr(0);
            return acc + colWidth;
          }, 0);
        };
        var insertColumnsExtractor = function(before2) {
          return function(warehouse, target) {
            return onCells(warehouse, target).filter(function(details) {
              var checkLocked = before2 ? firstColumnIsLocked : lastColumnIsLocked;
              return !checkLocked(warehouse, details);
            }).map(function(details) {
              return {
                details,
                pixelDelta: getColumnsWidth(warehouse, details)
              };
            });
          };
        };
        var eraseColumnsExtractor = function(warehouse, target) {
          return onUnlockedCells(warehouse, target).map(function(details) {
            return {
              details,
              pixelDelta: -getColumnsWidth(warehouse, details)
            };
          });
        };
        var pasteColumnsExtractor = function(before2) {
          return function(warehouse, target) {
            return onPasteByEditor(warehouse, target).filter(function(details) {
              var checkLocked = before2 ? firstColumnIsLocked : lastColumnIsLocked;
              return !checkLocked(warehouse, details.cells);
            });
          };
        };
        var headerCellGenerator = Generators.transform("th");
        var bodyCellGenerator = Generators.transform("td");
        var insertRowsBefore = run(opInsertRowsBefore, onCells, noop3, noop3, Generators.modification);
        var insertRowsAfter = run(opInsertRowsAfter, onCells, noop3, noop3, Generators.modification);
        var insertColumnsBefore = run(opInsertColumnsBefore, insertColumnsExtractor(true), adjustAndRedistributeWidths, noop3, Generators.modification);
        var insertColumnsAfter = run(opInsertColumnsAfter, insertColumnsExtractor(false), adjustAndRedistributeWidths, noop3, Generators.modification);
        var eraseColumns = run(opEraseColumns, eraseColumnsExtractor, adjustAndRedistributeWidths, prune3, Generators.modification);
        var eraseRows = run(opEraseRows, onCells, noop3, prune3, Generators.modification);
        var makeColumnsHeader = run(opMakeColumnsHeader, onUnlockedCells, noop3, noop3, headerCellGenerator);
        var unmakeColumnsHeader = run(opUnmakeColumnsHeader, onUnlockedCells, noop3, noop3, bodyCellGenerator);
        var makeRowsHeader = run(opMakeRowsHeader, onUnlockedCells, noop3, noop3, headerCellGenerator);
        var makeRowsBody = run(opMakeRowsBody, onUnlockedCells, noop3, noop3, bodyCellGenerator);
        var makeRowsFooter = run(opMakeRowsFooter, onUnlockedCells, noop3, noop3, bodyCellGenerator);
        var makeCellsHeader = run(opMakeCellsHeader, onUnlockedCells, noop3, noop3, headerCellGenerator);
        var unmakeCellsHeader = run(opUnmakeCellsHeader, onUnlockedCells, noop3, noop3, bodyCellGenerator);
        var mergeCells = run(opMergeCells, onUnlockedMergable, resize, noop3, Generators.merging);
        var unmergeCells = run(opUnmergeCells, onUnlockedUnmergable, resize, noop3, Generators.merging);
        var pasteCells = run(opPasteCells, onPaste, resize, noop3, Generators.modification);
        var pasteColsBefore = run(opPasteColsBefore, pasteColumnsExtractor(true), noop3, noop3, Generators.modification);
        var pasteColsAfter = run(opPasteColsAfter, pasteColumnsExtractor(false), noop3, noop3, Generators.modification);
        var pasteRowsBefore = run(opPasteRowsBefore, onPasteByEditor, noop3, noop3, Generators.modification);
        var pasteRowsAfter = run(opPasteRowsAfter, onPasteByEditor, noop3, noop3, Generators.modification);
        var getColumnsType = opGetColumnsType;
        var getCellsType = opGetCellsType;
        var getRowsType = opGetRowsType;
        var TableActions = function(editor, cellSelection, lazyWire) {
          var isTableBody = function(editor2) {
            return name(getBody(editor2)) === "table";
          };
          var lastRowGuard = function(table2) {
            return isTableBody(editor) === false || getGridSize(table2).rows > 1;
          };
          var lastColumnGuard = function(table2) {
            return isTableBody(editor) === false || getGridSize(table2).columns > 1;
          };
          var cloneFormats2 = getCloneElements(editor);
          var colMutationOp = isResizeTableColumnResizing(editor) ? noop3 : halve;
          var getTableSectionType2 = function(table2) {
            switch (getTableHeaderType(editor)) {
              case "section":
                return TableSection.section();
              case "sectionCells":
                return TableSection.sectionCells();
              case "cells":
                return TableSection.cells();
              default:
                return TableSection.getTableSectionType(table2, "section");
            }
          };
          var setSelectionFromAction = function(table2, result) {
            return result.cursor.fold(function() {
              var cells2 = cells$1(table2);
              return head(cells2).filter(inBody).map(function(firstCell) {
                cellSelection.clear(table2);
                var rng = editor.dom.createRng();
                rng.selectNode(firstCell.dom);
                editor.selection.setRng(rng);
                set$2(firstCell, "data-mce-selected", "1");
                return rng;
              });
            }, function(cell2) {
              var des = freefallRtl(cell2);
              var rng = editor.dom.createRng();
              rng.setStart(des.element.dom, des.offset);
              rng.setEnd(des.element.dom, des.offset);
              editor.selection.setRng(rng);
              cellSelection.clear(table2);
              return Optional.some(rng);
            });
          };
          var execute2 = function(operation, guard, mutate2, lazyWire2, effect4) {
            return function(table2, target, noEvents) {
              if (noEvents === void 0) {
                noEvents = false;
              }
              removeDataStyle(table2);
              var wire = lazyWire2();
              var doc = SugarElement.fromDom(editor.getDoc());
              var generators = cellOperations(mutate2, doc, cloneFormats2);
              var behaviours = {
                sizing: get$4(editor, table2),
                resize: isResizeTableColumnResizing(editor) ? resizeTable() : preserveTable(),
                section: getTableSectionType2(table2)
              };
              return guard(table2) ? operation(wire, table2, target, generators, behaviours).bind(function(result) {
                each$2(result.newRows, function(row2) {
                  fireNewRow(editor, row2.dom);
                });
                each$2(result.newCells, function(cell2) {
                  fireNewCell(editor, cell2.dom);
                });
                var range2 = setSelectionFromAction(table2, result);
                if (inBody(table2)) {
                  removeDataStyle(table2);
                  if (!noEvents) {
                    fireTableModified(editor, table2.dom, effect4);
                  }
                }
                return range2.map(function(rng) {
                  return {
                    rng,
                    effect: effect4
                  };
                });
              }) : Optional.none();
            };
          };
          var deleteRow = execute2(eraseRows, lastRowGuard, noop3, lazyWire, structureModified);
          var deleteColumn = execute2(eraseColumns, lastColumnGuard, noop3, lazyWire, structureModified);
          var insertRowsBefore$1 = execute2(insertRowsBefore, always, noop3, lazyWire, structureModified);
          var insertRowsAfter$1 = execute2(insertRowsAfter, always, noop3, lazyWire, structureModified);
          var insertColumnsBefore$1 = execute2(insertColumnsBefore, always, colMutationOp, lazyWire, structureModified);
          var insertColumnsAfter$1 = execute2(insertColumnsAfter, always, colMutationOp, lazyWire, structureModified);
          var mergeCells$1 = execute2(mergeCells, always, noop3, lazyWire, structureModified);
          var unmergeCells$1 = execute2(unmergeCells, always, noop3, lazyWire, structureModified);
          var pasteColsBefore$1 = execute2(pasteColsBefore, always, noop3, lazyWire, structureModified);
          var pasteColsAfter$1 = execute2(pasteColsAfter, always, noop3, lazyWire, structureModified);
          var pasteRowsBefore$1 = execute2(pasteRowsBefore, always, noop3, lazyWire, structureModified);
          var pasteRowsAfter$1 = execute2(pasteRowsAfter, always, noop3, lazyWire, structureModified);
          var pasteCells$1 = execute2(pasteCells, always, noop3, lazyWire, styleAndStructureModified);
          var makeCellsHeader$1 = execute2(makeCellsHeader, always, noop3, lazyWire, structureModified);
          var unmakeCellsHeader$1 = execute2(unmakeCellsHeader, always, noop3, lazyWire, structureModified);
          var makeColumnsHeader$1 = execute2(makeColumnsHeader, always, noop3, lazyWire, structureModified);
          var unmakeColumnsHeader$1 = execute2(unmakeColumnsHeader, always, noop3, lazyWire, structureModified);
          var makeRowsHeader$1 = execute2(makeRowsHeader, always, noop3, lazyWire, structureModified);
          var makeRowsBody$1 = execute2(makeRowsBody, always, noop3, lazyWire, structureModified);
          var makeRowsFooter$1 = execute2(makeRowsFooter, always, noop3, lazyWire, structureModified);
          var getTableCellType = getCellsType;
          var getTableColType = getColumnsType;
          var getTableRowType = getRowsType;
          return {
            deleteRow,
            deleteColumn,
            insertRowsBefore: insertRowsBefore$1,
            insertRowsAfter: insertRowsAfter$1,
            insertColumnsBefore: insertColumnsBefore$1,
            insertColumnsAfter: insertColumnsAfter$1,
            mergeCells: mergeCells$1,
            unmergeCells: unmergeCells$1,
            pasteColsBefore: pasteColsBefore$1,
            pasteColsAfter: pasteColsAfter$1,
            pasteRowsBefore: pasteRowsBefore$1,
            pasteRowsAfter: pasteRowsAfter$1,
            pasteCells: pasteCells$1,
            makeCellsHeader: makeCellsHeader$1,
            unmakeCellsHeader: unmakeCellsHeader$1,
            makeColumnsHeader: makeColumnsHeader$1,
            unmakeColumnsHeader: unmakeColumnsHeader$1,
            makeRowsHeader: makeRowsHeader$1,
            makeRowsBody: makeRowsBody$1,
            makeRowsFooter: makeRowsFooter$1,
            getTableRowType,
            getTableCellType,
            getTableColType
          };
        };
        var DefaultRenderOptions = {
          styles: {
            "border-collapse": "collapse",
            "width": "100%"
          },
          attributes: { border: "1" },
          colGroups: false
        };
        var tableHeaderCell = function() {
          return SugarElement.fromTag("th");
        };
        var tableCell = function() {
          return SugarElement.fromTag("td");
        };
        var tableColumn = function() {
          return SugarElement.fromTag("col");
        };
        var createRow = function(columns2, rowHeaders, columnHeaders, rowIndex) {
          var tr = SugarElement.fromTag("tr");
          for (var j2 = 0; j2 < columns2; j2++) {
            var td = rowIndex < rowHeaders || j2 < columnHeaders ? tableHeaderCell() : tableCell();
            if (j2 < columnHeaders) {
              set$2(td, "scope", "row");
            }
            if (rowIndex < rowHeaders) {
              set$2(td, "scope", "col");
            }
            append$1(td, SugarElement.fromTag("br"));
            append$1(tr, td);
          }
          return tr;
        };
        var createGroupRow = function(columns2) {
          var columnGroup = SugarElement.fromTag("colgroup");
          range$1(columns2, function() {
            return append$1(columnGroup, tableColumn());
          });
          return columnGroup;
        };
        var createRows = function(rows2, columns2, rowHeaders, columnHeaders) {
          return range$1(rows2, function(r3) {
            return createRow(columns2, rowHeaders, columnHeaders, r3);
          });
        };
        var render = function(rows2, columns2, rowHeaders, columnHeaders, headerType, renderOpts) {
          if (renderOpts === void 0) {
            renderOpts = DefaultRenderOptions;
          }
          var table2 = SugarElement.fromTag("table");
          var rowHeadersGoInThead = headerType !== "cells";
          setAll(table2, renderOpts.styles);
          setAll$1(table2, renderOpts.attributes);
          if (renderOpts.colGroups) {
            append$1(table2, createGroupRow(columns2));
          }
          var actualRowHeaders = Math.min(rows2, rowHeaders);
          if (rowHeadersGoInThead && rowHeaders > 0) {
            var thead = SugarElement.fromTag("thead");
            append$1(table2, thead);
            var theadRowHeaders = headerType === "sectionCells" ? actualRowHeaders : 0;
            var theadRows = createRows(rowHeaders, columns2, theadRowHeaders, columnHeaders);
            append(thead, theadRows);
          }
          var tbody = SugarElement.fromTag("tbody");
          append$1(table2, tbody);
          var numRows = rowHeadersGoInThead ? rows2 - actualRowHeaders : rows2;
          var numRowHeaders = rowHeadersGoInThead ? 0 : rowHeaders;
          var tbodyRows = createRows(numRows, columns2, numRowHeaders, columnHeaders);
          append(tbody, tbodyRows);
          return table2;
        };
        var get$2 = function(element) {
          return element.dom.innerHTML;
        };
        var getOuter = function(element) {
          var container = SugarElement.fromTag("div");
          var clone3 = SugarElement.fromDom(element.dom.cloneNode(true));
          append$1(container, clone3);
          return get$2(container);
        };
        var placeCaretInCell = function(editor, cell2) {
          editor.selection.select(cell2.dom, true);
          editor.selection.collapse(true);
        };
        var selectFirstCellInTable = function(editor, tableElm) {
          descendant(tableElm, "td,th").each(curry(placeCaretInCell, editor));
        };
        var fireEvents = function(editor, table2) {
          each$2(descendants(table2, "tr"), function(row2) {
            fireNewRow(editor, row2.dom);
            each$2(descendants(row2, "th,td"), function(cell2) {
              fireNewCell(editor, cell2.dom);
            });
          });
        };
        var isPercentage = function(width2) {
          return isString(width2) && width2.indexOf("%") !== -1;
        };
        var insert = function(editor, columns2, rows2, colHeaders, rowHeaders) {
          var defaultStyles2 = getDefaultStyles(editor);
          var options = {
            styles: defaultStyles2,
            attributes: getDefaultAttributes(editor),
            colGroups: useColumnGroup(editor)
          };
          editor.undoManager.ignore(function() {
            var table2 = render(rows2, columns2, rowHeaders, colHeaders, getTableHeaderType(editor), options);
            set$2(table2, "data-mce-id", "__mce");
            var html = getOuter(table2);
            editor.insertContent(html);
            editor.addVisual();
          });
          return descendant(getBody(editor), 'table[data-mce-id="__mce"]').map(function(table2) {
            if (isPixelsForced(editor)) {
              enforcePixels(table2);
            } else if (isResponsiveForced(editor)) {
              enforceNone(table2);
            } else if (isPercentagesForced(editor) || isPercentage(defaultStyles2.width)) {
              enforcePercentage(table2);
            }
            removeDataStyle(table2);
            remove$7(table2, "data-mce-id");
            fireEvents(editor, table2);
            selectFirstCellInTable(editor, table2);
            return table2.dom;
          }).getOr(null);
        };
        var insertTableWithDataValidation = function(editor, rows2, columns2, options, errorMsg) {
          if (options === void 0) {
            options = {};
          }
          var checkInput = function(val) {
            return isNumber2(val) && val > 0;
          };
          if (checkInput(rows2) && checkInput(columns2)) {
            var headerRows = options.headerRows || 0;
            var headerColumns = options.headerColumns || 0;
            return insert(editor, columns2, rows2, headerColumns, headerRows);
          } else {
            console.error(errorMsg);
            return null;
          }
        };
        var getClipboardElements = function(getClipboard) {
          return function() {
            return getClipboard().fold(function() {
              return [];
            }, function(elems) {
              return map$12(elems, function(e2) {
                return e2.dom;
              });
            });
          };
        };
        var setClipboardElements = function(setClipboard) {
          return function(elems) {
            var elmsOpt = elems.length > 0 ? Optional.some(fromDom(elems)) : Optional.none();
            setClipboard(elmsOpt);
          };
        };
        var insertTable = function(editor) {
          return function(columns2, rows2, options) {
            if (options === void 0) {
              options = {};
            }
            var table2 = insertTableWithDataValidation(editor, rows2, columns2, options, "Invalid values for insertTable - rows and columns values are required to insert a table.");
            editor.undoManager.add();
            return table2;
          };
        };
        var getApi = function(editor, clipboard, resizeHandler, selectionTargets) {
          return {
            insertTable: insertTable(editor),
            setClipboardRows: setClipboardElements(clipboard.setRows),
            getClipboardRows: getClipboardElements(clipboard.getRows),
            setClipboardCols: setClipboardElements(clipboard.setColumns),
            getClipboardCols: getClipboardElements(clipboard.getColumns),
            resizeHandler,
            selectionTargets
          };
        };
        var constrainSpan = function(element, property, value2) {
          var currentColspan = getAttrValue(element, property, 1);
          if (value2 === 1 || currentColspan <= 1) {
            remove$7(element, property);
          } else {
            set$2(element, property, Math.min(value2, currentColspan));
          }
        };
        var generateColGroup = function(house, minColRange, maxColRange) {
          if (Warehouse.hasColumns(house)) {
            var colsToCopy = filter$2(Warehouse.justColumns(house), function(col2) {
              return col2.column >= minColRange && col2.column < maxColRange;
            });
            var copiedCols = map$12(colsToCopy, function(c2) {
              var clonedCol = deep(c2.element);
              constrainSpan(clonedCol, "span", maxColRange - minColRange);
              return clonedCol;
            });
            var fakeColgroup = SugarElement.fromTag("colgroup");
            append(fakeColgroup, copiedCols);
            return [fakeColgroup];
          } else {
            return [];
          }
        };
        var generateRows = function(house, minColRange, maxColRange) {
          return map$12(house.all, function(row2) {
            var cellsToCopy = filter$2(row2.cells, function(cell2) {
              return cell2.column >= minColRange && cell2.column < maxColRange;
            });
            var copiedCells = map$12(cellsToCopy, function(cell2) {
              var clonedCell = deep(cell2.element);
              constrainSpan(clonedCell, "colspan", maxColRange - minColRange);
              return clonedCell;
            });
            var fakeTR = SugarElement.fromTag("tr");
            append(fakeTR, copiedCells);
            return fakeTR;
          });
        };
        var copyCols = function(table2, target) {
          var house = Warehouse.fromTable(table2);
          var details = onUnlockedCells(house, target);
          return details.map(function(selectedCells) {
            var lastSelectedCell = selectedCells[selectedCells.length - 1];
            var minColRange = selectedCells[0].column;
            var maxColRange = lastSelectedCell.column + lastSelectedCell.colspan;
            var fakeColGroups = generateColGroup(house, minColRange, maxColRange);
            var fakeRows = generateRows(house, minColRange, maxColRange);
            return __spreadArray(__spreadArray([], fakeColGroups, true), fakeRows, true);
          });
        };
        var copyRows = function(table2, target, generators) {
          var warehouse = Warehouse.fromTable(table2);
          var details = onCells(warehouse, target);
          return details.bind(function(selectedCells) {
            var grid2 = toGrid(warehouse, generators, false);
            var rows2 = extractGridDetails(grid2).rows;
            var slicedGrid = rows2.slice(selectedCells[0].row, selectedCells[selectedCells.length - 1].row + selectedCells[selectedCells.length - 1].rowspan);
            var filteredGrid = bind$2(slicedGrid, function(row2) {
              var newCells = filter$2(row2.cells, function(cell2) {
                return !cell2.isLocked;
              });
              return newCells.length > 0 ? [__assign(__assign({}, row2), { cells: newCells })] : [];
            });
            var slicedDetails = toDetailList(filteredGrid);
            return someIf(slicedDetails.length > 0, slicedDetails);
          }).map(function(slicedDetails) {
            return copy(slicedDetails);
          });
        };
        var global$2 = tinymce.util.Tools.resolve("tinymce.util.Tools");
        var getTDTHOverallStyle = function(dom, elm, name2) {
          var cells2 = dom.select("td,th", elm);
          var firstChildStyle;
          var checkChildren = function(firstChildStyle2, elms) {
            for (var i2 = 0; i2 < elms.length; i2++) {
              var currentStyle = dom.getStyle(elms[i2], name2);
              if (typeof firstChildStyle2 === "undefined") {
                firstChildStyle2 = currentStyle;
              }
              if (firstChildStyle2 !== currentStyle) {
                return "";
              }
            }
            return firstChildStyle2;
          };
          return checkChildren(firstChildStyle, cells2);
        };
        var applyAlign = function(editor, elm, name2) {
          if (name2) {
            editor.formatter.apply("align" + name2, {}, elm);
          }
        };
        var applyVAlign = function(editor, elm, name2) {
          if (name2) {
            editor.formatter.apply("valign" + name2, {}, elm);
          }
        };
        var unApplyAlign = function(editor, elm) {
          global$2.each("left center right".split(" "), function(name2) {
            editor.formatter.remove("align" + name2, {}, elm);
          });
        };
        var unApplyVAlign = function(editor, elm) {
          global$2.each("top middle bottom".split(" "), function(name2) {
            editor.formatter.remove("valign" + name2, {}, elm);
          });
        };
        var verticalAlignValues = [
          {
            text: "None",
            value: ""
          },
          {
            text: "Top",
            value: "top"
          },
          {
            text: "Middle",
            value: "middle"
          },
          {
            text: "Bottom",
            value: "bottom"
          }
        ];
        var hexColour = function(value2) {
          return { value: value2 };
        };
        var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
        var longformRegex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
        var isHexString = function(hex2) {
          return shorthandRegex.test(hex2) || longformRegex.test(hex2);
        };
        var normalizeHex = function(hex2) {
          return removeLeading(hex2, "#").toUpperCase();
        };
        var fromString$1 = function(hex2) {
          return isHexString(hex2) ? Optional.some({ value: normalizeHex(hex2) }) : Optional.none();
        };
        var toHex = function(component) {
          var hex2 = component.toString(16);
          return (hex2.length === 1 ? "0" + hex2 : hex2).toUpperCase();
        };
        var fromRgba = function(rgbaColour2) {
          var value2 = toHex(rgbaColour2.red) + toHex(rgbaColour2.green) + toHex(rgbaColour2.blue);
          return hexColour(value2);
        };
        var rgbRegex = /^rgb\((\d+),\s*(\d+),\s*(\d+)\)/;
        var rgbaRegex = /^rgba\((\d+),\s*(\d+),\s*(\d+),\s*(\d?(?:\.\d+)?)\)/;
        var rgbaColour = function(red, green, blue, alpha) {
          return {
            red,
            green,
            blue,
            alpha
          };
        };
        var fromStringValues = function(red, green, blue, alpha) {
          var r3 = parseInt(red, 10);
          var g2 = parseInt(green, 10);
          var b2 = parseInt(blue, 10);
          var a2 = parseFloat(alpha);
          return rgbaColour(r3, g2, b2, a2);
        };
        var fromString = function(rgbaString) {
          if (rgbaString === "transparent") {
            return Optional.some(rgbaColour(0, 0, 0, 0));
          }
          var rgbMatch = rgbRegex.exec(rgbaString);
          if (rgbMatch !== null) {
            return Optional.some(fromStringValues(rgbMatch[1], rgbMatch[2], rgbMatch[3], "1"));
          }
          var rgbaMatch = rgbaRegex.exec(rgbaString);
          if (rgbaMatch !== null) {
            return Optional.some(fromStringValues(rgbaMatch[1], rgbaMatch[2], rgbaMatch[3], rgbaMatch[4]));
          }
          return Optional.none();
        };
        var anyToHex = function(color2) {
          return fromString$1(color2).orThunk(function() {
            return fromString(color2).map(fromRgba);
          }).getOrThunk(function() {
            var canvas = document.createElement("canvas");
            canvas.height = 1;
            canvas.width = 1;
            var canvasContext = canvas.getContext("2d");
            canvasContext.clearRect(0, 0, canvas.width, canvas.height);
            canvasContext.fillStyle = "#FFFFFF";
            canvasContext.fillStyle = color2;
            canvasContext.fillRect(0, 0, 1, 1);
            var rgba = canvasContext.getImageData(0, 0, 1, 1).data;
            var r3 = rgba[0];
            var g2 = rgba[1];
            var b2 = rgba[2];
            var a2 = rgba[3];
            return fromRgba(rgbaColour(r3, g2, b2, a2));
          });
        };
        var Cell = function(initial) {
          var value2 = initial;
          var get2 = function() {
            return value2;
          };
          var set3 = function(v2) {
            value2 = v2;
          };
          return {
            get: get2,
            set: set3
          };
        };
        var singleton = function(doRevoke) {
          var subject = Cell(Optional.none());
          var revoke = function() {
            return subject.get().each(doRevoke);
          };
          var clear2 = function() {
            revoke();
            subject.set(Optional.none());
          };
          var isSet = function() {
            return subject.get().isSome();
          };
          var get2 = function() {
            return subject.get();
          };
          var set3 = function(s2) {
            revoke();
            subject.set(Optional.some(s2));
          };
          return {
            clear: clear2,
            isSet,
            get: get2,
            set: set3
          };
        };
        var unbindable = function() {
          return singleton(function(s2) {
            return s2.unbind();
          });
        };
        var value = function() {
          var subject = singleton(noop3);
          var on3 = function(f2) {
            return subject.get().each(f2);
          };
          return __assign(__assign({}, subject), { on: on3 });
        };
        var onSetupToggle = function(editor, selections, formatName, formatValue) {
          return function(api2) {
            var boundCallback = unbindable();
            var isNone = isEmpty$1(formatValue);
            var init = function() {
              var selectedCells = getCellsFromSelection(selections);
              var checkNode = function(cell2) {
                return editor.formatter.match(formatName, { value: formatValue }, cell2.dom, isNone);
              };
              if (isNone) {
                api2.setActive(!exists(selectedCells, checkNode));
                boundCallback.set(editor.formatter.formatChanged(formatName, function(match2) {
                  return api2.setActive(!match2);
                }, true));
              } else {
                api2.setActive(forall(selectedCells, checkNode));
                boundCallback.set(editor.formatter.formatChanged(formatName, api2.setActive, false, { value: formatValue }));
              }
            };
            editor.initialized ? init() : editor.on("init", init);
            return boundCallback.clear;
          };
        };
        var isListGroup = function(item) {
          return hasNonNullableKey(item, "menu");
        };
        var buildListItems = function(items) {
          return map$12(items, function(item) {
            var text = item.text || item.title;
            if (isListGroup(item)) {
              return {
                text,
                items: buildListItems(item.menu)
              };
            } else {
              return {
                text,
                value: item.value
              };
            }
          });
        };
        var buildMenuItems = function(editor, selections, items, format3, onAction) {
          return map$12(items, function(item) {
            var text = item.text || item.title;
            if (isListGroup(item)) {
              return {
                type: "nestedmenuitem",
                text,
                getSubmenuItems: function() {
                  return buildMenuItems(editor, selections, item.menu, format3, onAction);
                }
              };
            } else {
              return {
                text,
                type: "togglemenuitem",
                onAction: function() {
                  return onAction(item.value);
                },
                onSetup: onSetupToggle(editor, selections, format3, item.value)
              };
            }
          });
        };
        var applyTableCellStyle = function(editor, style) {
          return function(value2) {
            var _a;
            editor.execCommand("mceTableApplyCellStyle", false, (_a = {}, _a[style] = value2, _a));
          };
        };
        var filterNoneItem = function(list) {
          return bind$2(list, function(item) {
            if (isListGroup(item)) {
              return [__assign(__assign({}, item), { menu: filterNoneItem(item.menu) })];
            } else {
              return isNotEmpty(item.value) ? [item] : [];
            }
          });
        };
        var generateMenuItemsCallback = function(editor, selections, items, format3, onAction) {
          return function(callback2) {
            return callback2(buildMenuItems(editor, selections, items, format3, onAction));
          };
        };
        var buildColorMenu = function(editor, colorList, style) {
          var colorMap = map$12(colorList, function(entry) {
            return {
              text: entry.title,
              value: "#" + anyToHex(entry.value).value,
              type: "choiceitem"
            };
          });
          return [{
            type: "fancymenuitem",
            fancytype: "colorswatch",
            initData: {
              colors: colorMap.length > 0 ? colorMap : void 0,
              allowCustomColors: false
            },
            onAction: function(data) {
              var _a;
              var value2 = data.value === "remove" ? "" : data.value;
              editor.execCommand("mceTableApplyCellStyle", false, (_a = {}, _a[style] = value2, _a));
            }
          }];
        };
        var changeRowHeader = function(editor) {
          return function() {
            var currentType = editor.queryCommandValue("mceTableRowType");
            var newType = currentType === "header" ? "body" : "header";
            editor.execCommand("mceTableRowType", false, { type: newType });
          };
        };
        var changeColumnHeader = function(editor) {
          return function() {
            var currentType = editor.queryCommandValue("mceTableColType");
            var newType = currentType === "th" ? "td" : "th";
            editor.execCommand("mceTableColType", false, { type: newType });
          };
        };
        var getClassList$1 = function(editor) {
          var classes = buildListItems(getCellClassList(editor));
          if (classes.length > 0) {
            return Optional.some({
              name: "class",
              type: "listbox",
              label: "Class",
              items: classes
            });
          }
          return Optional.none();
        };
        var children = [
          {
            name: "width",
            type: "input",
            label: "Width"
          },
          {
            name: "height",
            type: "input",
            label: "Height"
          },
          {
            name: "celltype",
            type: "listbox",
            label: "Cell type",
            items: [
              {
                text: "Cell",
                value: "td"
              },
              {
                text: "Header cell",
                value: "th"
              }
            ]
          },
          {
            name: "scope",
            type: "listbox",
            label: "Scope",
            items: [
              {
                text: "None",
                value: ""
              },
              {
                text: "Row",
                value: "row"
              },
              {
                text: "Column",
                value: "col"
              },
              {
                text: "Row group",
                value: "rowgroup"
              },
              {
                text: "Column group",
                value: "colgroup"
              }
            ]
          },
          {
            name: "halign",
            type: "listbox",
            label: "Horizontal align",
            items: [
              {
                text: "None",
                value: ""
              },
              {
                text: "Left",
                value: "left"
              },
              {
                text: "Center",
                value: "center"
              },
              {
                text: "Right",
                value: "right"
              }
            ]
          },
          {
            name: "valign",
            type: "listbox",
            label: "Vertical align",
            items: verticalAlignValues
          }
        ];
        var getItems$2 = function(editor) {
          return children.concat(getClassList$1(editor).toArray());
        };
        var getAdvancedTab = function(editor, dialogName) {
          var emptyBorderStyle = [{
            text: "Select...",
            value: ""
          }];
          var advTabItems = [
            {
              name: "borderstyle",
              type: "listbox",
              label: "Border style",
              items: emptyBorderStyle.concat(buildListItems(getTableBorderStyles(editor)))
            },
            {
              name: "bordercolor",
              type: "colorinput",
              label: "Border color"
            },
            {
              name: "backgroundcolor",
              type: "colorinput",
              label: "Background color"
            }
          ];
          var borderWidth = {
            name: "borderwidth",
            type: "input",
            label: "Border width"
          };
          var items = dialogName === "cell" ? [borderWidth].concat(advTabItems) : advTabItems;
          return {
            title: "Advanced",
            name: "advanced",
            items
          };
        };
        var modifiers = function(testTruthy) {
          return function(editor, node) {
            var dom = editor.dom;
            var setAttrib = function(attr, value2) {
              if (!testTruthy || value2) {
                dom.setAttrib(node, attr, value2);
              }
            };
            var setStyle2 = function(prop, value2) {
              if (!testTruthy || value2) {
                dom.setStyle(node, prop, value2);
              }
            };
            var setFormat = function(formatName, value2) {
              if (!testTruthy || value2) {
                if (value2 === "") {
                  editor.formatter.remove(formatName, { value: null }, node, true);
                } else {
                  editor.formatter.apply(formatName, { value: value2 }, node);
                }
              }
            };
            return {
              setAttrib,
              setStyle: setStyle2,
              setFormat
            };
          };
        };
        var DomModifier = {
          normal: modifiers(false),
          ifTruthy: modifiers(true)
        };
        var rgbToHex = function(dom) {
          return function(value2) {
            return startsWith(value2, "rgb") ? dom.toHex(value2) : value2;
          };
        };
        var extractAdvancedStyles = function(dom, elm) {
          var element = SugarElement.fromDom(elm);
          return {
            borderwidth: getRaw$2(element, "border-width").getOr(""),
            borderstyle: getRaw$2(element, "border-style").getOr(""),
            bordercolor: getRaw$2(element, "border-color").map(rgbToHex(dom)).getOr(""),
            backgroundcolor: getRaw$2(element, "background-color").map(rgbToHex(dom)).getOr("")
          };
        };
        var getSharedValues = function(data) {
          var baseData = data[0];
          var comparisonData = data.slice(1);
          each$2(comparisonData, function(items) {
            each$2(keys(baseData), function(key2) {
              each$1(items, function(itemValue, itemKey) {
                var comparisonValue = baseData[key2];
                if (comparisonValue !== "" && key2 === itemKey) {
                  if (comparisonValue !== itemValue) {
                    baseData[key2] = "";
                  }
                }
              });
            });
          });
          return baseData;
        };
        var getAlignment = function(formats, formatName, editor, elm) {
          return find$1(formats, function(name2) {
            return !isUndefined(editor.formatter.matchNode(elm, formatName + name2));
          }).getOr("");
        };
        var getHAlignment = curry(getAlignment, [
          "left",
          "center",
          "right"
        ], "align");
        var getVAlignment = curry(getAlignment, [
          "top",
          "middle",
          "bottom"
        ], "valign");
        var extractDataFromSettings = function(editor, hasAdvTableTab) {
          var style = getDefaultStyles(editor);
          var attrs = getDefaultAttributes(editor);
          var extractAdvancedStyleData = function(dom) {
            return {
              borderstyle: get$c(style, "border-style").getOr(""),
              bordercolor: rgbToHex(dom)(get$c(style, "border-color").getOr("")),
              backgroundcolor: rgbToHex(dom)(get$c(style, "background-color").getOr(""))
            };
          };
          var defaultData = {
            height: "",
            width: "100%",
            cellspacing: "",
            cellpadding: "",
            caption: false,
            class: "",
            align: "",
            border: ""
          };
          var getBorder = function() {
            var borderWidth = style["border-width"];
            if (shouldStyleWithCss(editor) && borderWidth) {
              return { border: borderWidth };
            }
            return get$c(attrs, "border").fold(function() {
              return {};
            }, function(border) {
              return { border };
            });
          };
          var advStyle = hasAdvTableTab ? extractAdvancedStyleData(editor.dom) : {};
          var getCellPaddingCellSpacing = function() {
            var spacing = get$c(style, "border-spacing").or(get$c(attrs, "cellspacing")).fold(function() {
              return {};
            }, function(cellspacing) {
              return { cellspacing };
            });
            var padding = get$c(style, "border-padding").or(get$c(attrs, "cellpadding")).fold(function() {
              return {};
            }, function(cellpadding) {
              return { cellpadding };
            });
            return __assign(__assign({}, spacing), padding);
          };
          var data = __assign(__assign(__assign(__assign(__assign(__assign({}, defaultData), style), attrs), advStyle), getBorder()), getCellPaddingCellSpacing());
          return data;
        };
        var getRowType = function(elm) {
          return table(SugarElement.fromDom(elm)).map(function(table2) {
            var target = { selection: fromDom(elm.cells) };
            return getRowsType(table2, target);
          }).getOr("");
        };
        var extractDataFromTableElement = function(editor, elm, hasAdvTableTab) {
          var getBorder = function(dom2, elm2) {
            var optBorderWidth = getRaw$2(SugarElement.fromDom(elm2), "border-width");
            if (shouldStyleWithCss(editor) && optBorderWidth.isSome()) {
              return optBorderWidth.getOr("");
            }
            return dom2.getAttrib(elm2, "border") || getTDTHOverallStyle(editor.dom, elm2, "border-width") || getTDTHOverallStyle(editor.dom, elm2, "border");
          };
          var dom = editor.dom;
          var cellspacing = shouldStyleWithCss(editor) ? dom.getStyle(elm, "border-spacing") || dom.getAttrib(elm, "cellspacing") : dom.getAttrib(elm, "cellspacing") || dom.getStyle(elm, "border-spacing");
          var cellpadding = shouldStyleWithCss(editor) ? getTDTHOverallStyle(dom, elm, "padding") || dom.getAttrib(elm, "cellpadding") : dom.getAttrib(elm, "cellpadding") || getTDTHOverallStyle(dom, elm, "padding");
          return __assign({
            width: dom.getStyle(elm, "width") || dom.getAttrib(elm, "width"),
            height: dom.getStyle(elm, "height") || dom.getAttrib(elm, "height"),
            cellspacing,
            cellpadding,
            border: getBorder(dom, elm),
            caption: !!dom.select("caption", elm)[0],
            class: dom.getAttrib(elm, "class", ""),
            align: getHAlignment(editor, elm)
          }, hasAdvTableTab ? extractAdvancedStyles(dom, elm) : {});
        };
        var extractDataFromRowElement = function(editor, elm, hasAdvancedRowTab2) {
          var dom = editor.dom;
          return __assign({
            height: dom.getStyle(elm, "height") || dom.getAttrib(elm, "height"),
            class: dom.getAttrib(elm, "class", ""),
            type: getRowType(elm),
            align: getHAlignment(editor, elm)
          }, hasAdvancedRowTab2 ? extractAdvancedStyles(dom, elm) : {});
        };
        var extractDataFromCellElement = function(editor, cell2, hasAdvancedCellTab2, column) {
          var dom = editor.dom;
          var colElm = column.getOr(cell2);
          var getStyle2 = function(element, style) {
            return dom.getStyle(element, style) || dom.getAttrib(element, style);
          };
          return __assign({
            width: getStyle2(colElm, "width"),
            height: getStyle2(cell2, "height"),
            scope: dom.getAttrib(cell2, "scope"),
            celltype: getNodeName2(cell2),
            class: dom.getAttrib(cell2, "class", ""),
            halign: getHAlignment(editor, cell2),
            valign: getVAlignment(editor, cell2)
          }, hasAdvancedCellTab2 ? extractAdvancedStyles(dom, cell2) : {});
        };
        var getSelectedCells = function(table2, cells2) {
          var warehouse = Warehouse.fromTable(table2);
          var allCells = Warehouse.justCells(warehouse);
          var filtered = filter$2(allCells, function(cellA) {
            return exists(cells2, function(cellB) {
              return eq$1(cellA.element, cellB);
            });
          });
          return map$12(filtered, function(cell2) {
            return {
              element: cell2.element.dom,
              column: Warehouse.getColumnAt(warehouse, cell2.column).map(function(col2) {
                return col2.element.dom;
              })
            };
          });
        };
        var updateSimpleProps$1 = function(modifier, colModifier, data) {
          modifier.setAttrib("scope", data.scope);
          modifier.setAttrib("class", data.class);
          modifier.setStyle("height", addPxSuffix(data.height));
          colModifier.setStyle("width", addPxSuffix(data.width));
        };
        var updateAdvancedProps$1 = function(modifier, data) {
          modifier.setFormat("tablecellbackgroundcolor", data.backgroundcolor);
          modifier.setFormat("tablecellbordercolor", data.bordercolor);
          modifier.setFormat("tablecellborderstyle", data.borderstyle);
          modifier.setFormat("tablecellborderwidth", addPxSuffix(data.borderwidth));
        };
        var applyStyleData$1 = function(editor, cells2, data) {
          var isSingleCell = cells2.length === 1;
          each$2(cells2, function(item) {
            var cellElm = item.element;
            var modifier = isSingleCell ? DomModifier.normal(editor, cellElm) : DomModifier.ifTruthy(editor, cellElm);
            var colModifier = item.column.map(function(col2) {
              return isSingleCell ? DomModifier.normal(editor, col2) : DomModifier.ifTruthy(editor, col2);
            }).getOr(modifier);
            updateSimpleProps$1(modifier, colModifier, data);
            if (hasAdvancedCellTab(editor)) {
              updateAdvancedProps$1(modifier, data);
            }
            if (isSingleCell) {
              unApplyAlign(editor, cellElm);
              unApplyVAlign(editor, cellElm);
            }
            if (data.halign) {
              applyAlign(editor, cellElm, data.halign);
            }
            if (data.valign) {
              applyVAlign(editor, cellElm, data.valign);
            }
          });
        };
        var applyStructureData$1 = function(editor, data) {
          editor.execCommand("mceTableCellType", false, {
            type: data.celltype,
            no_events: true
          });
        };
        var applyCellData = function(editor, cells2, oldData, data) {
          var modifiedData = filter$1(data, function(value2, key2) {
            return oldData[key2] !== value2;
          });
          if (size(modifiedData) > 0 && cells2.length >= 1) {
            table(cells2[0]).each(function(table2) {
              var selectedCells = getSelectedCells(table2, cells2);
              var styleModified2 = size(filter$1(modifiedData, function(_value, key2) {
                return key2 !== "scope" && key2 !== "celltype";
              })) > 0;
              var structureModified2 = has$1(modifiedData, "celltype");
              if (styleModified2 || has$1(modifiedData, "scope")) {
                applyStyleData$1(editor, selectedCells, data);
              }
              if (structureModified2) {
                applyStructureData$1(editor, data);
              }
              fireTableModified(editor, table2.dom, {
                structure: structureModified2,
                style: styleModified2
              });
            });
          }
        };
        var onSubmitCellForm = function(editor, cells2, oldData, api2) {
          var data = api2.getData();
          api2.close();
          editor.undoManager.transact(function() {
            applyCellData(editor, cells2, oldData, data);
            editor.focus();
          });
        };
        var getData = function(editor, cells2) {
          var cellsData = table(cells2[0]).map(function(table2) {
            return map$12(getSelectedCells(table2, cells2), function(item) {
              return extractDataFromCellElement(editor, item.element, hasAdvancedCellTab(editor), item.column);
            });
          });
          return getSharedValues(cellsData.getOrDie());
        };
        var open$2 = function(editor, selections) {
          var cells2 = getCellsFromSelection(selections);
          if (cells2.length === 0) {
            return;
          }
          var data = getData(editor, cells2);
          var dialogTabPanel = {
            type: "tabpanel",
            tabs: [
              {
                title: "General",
                name: "general",
                items: getItems$2(editor)
              },
              getAdvancedTab(editor, "cell")
            ]
          };
          var dialogPanel = {
            type: "panel",
            items: [{
              type: "grid",
              columns: 2,
              items: getItems$2(editor)
            }]
          };
          editor.windowManager.open({
            title: "Cell Properties",
            size: "normal",
            body: hasAdvancedCellTab(editor) ? dialogTabPanel : dialogPanel,
            buttons: [
              {
                type: "cancel",
                name: "cancel",
                text: "Cancel"
              },
              {
                type: "submit",
                name: "save",
                text: "Save",
                primary: true
              }
            ],
            initialData: data,
            onSubmit: curry(onSubmitCellForm, editor, cells2, data)
          });
        };
        var getClassList = function(editor) {
          var classes = buildListItems(getRowClassList(editor));
          if (classes.length > 0) {
            return Optional.some({
              name: "class",
              type: "listbox",
              label: "Class",
              items: classes
            });
          }
          return Optional.none();
        };
        var formChildren = [
          {
            type: "listbox",
            name: "type",
            label: "Row type",
            items: [
              {
                text: "Header",
                value: "header"
              },
              {
                text: "Body",
                value: "body"
              },
              {
                text: "Footer",
                value: "footer"
              }
            ]
          },
          {
            type: "listbox",
            name: "align",
            label: "Alignment",
            items: [
              {
                text: "None",
                value: ""
              },
              {
                text: "Left",
                value: "left"
              },
              {
                text: "Center",
                value: "center"
              },
              {
                text: "Right",
                value: "right"
              }
            ]
          },
          {
            label: "Height",
            name: "height",
            type: "input"
          }
        ];
        var getItems$1 = function(editor) {
          return formChildren.concat(getClassList(editor).toArray());
        };
        var updateSimpleProps = function(modifier, data) {
          modifier.setAttrib("class", data.class);
          modifier.setStyle("height", addPxSuffix(data.height));
        };
        var updateAdvancedProps = function(modifier, data) {
          modifier.setStyle("background-color", data.backgroundcolor);
          modifier.setStyle("border-color", data.bordercolor);
          modifier.setStyle("border-style", data.borderstyle);
        };
        var applyStyleData = function(editor, rows2, data, oldData) {
          var isSingleRow = rows2.length === 1;
          each$2(rows2, function(rowElm) {
            var modifier = isSingleRow ? DomModifier.normal(editor, rowElm) : DomModifier.ifTruthy(editor, rowElm);
            updateSimpleProps(modifier, data);
            if (hasAdvancedRowTab(editor)) {
              updateAdvancedProps(modifier, data);
            }
            if (data.align !== oldData.align) {
              unApplyAlign(editor, rowElm);
              applyAlign(editor, rowElm, data.align);
            }
          });
        };
        var applyStructureData = function(editor, data) {
          editor.execCommand("mceTableRowType", false, {
            type: data.type,
            no_events: true
          });
        };
        var applyRowData = function(editor, rows2, oldData, data) {
          var modifiedData = filter$1(data, function(value2, key2) {
            return oldData[key2] !== value2;
          });
          if (size(modifiedData) > 0) {
            var typeModified_1 = has$1(modifiedData, "type");
            var styleModified_1 = typeModified_1 ? size(modifiedData) > 1 : true;
            if (styleModified_1) {
              applyStyleData(editor, rows2, data, oldData);
            }
            if (typeModified_1) {
              applyStructureData(editor, data);
            }
            table(SugarElement.fromDom(rows2[0])).each(function(table2) {
              return fireTableModified(editor, table2.dom, {
                structure: typeModified_1,
                style: styleModified_1
              });
            });
          }
        };
        var onSubmitRowForm = function(editor, rows2, oldData, api2) {
          var data = api2.getData();
          api2.close();
          editor.undoManager.transact(function() {
            applyRowData(editor, rows2, oldData, data);
            editor.focus();
          });
        };
        var open$1 = function(editor) {
          var rows2 = getRowsFromSelection(getSelectionStart(editor), ephemera.selected);
          if (rows2.length === 0) {
            return;
          }
          var rowsData = map$12(rows2, function(rowElm) {
            return extractDataFromRowElement(editor, rowElm.dom, hasAdvancedRowTab(editor));
          });
          var data = getSharedValues(rowsData);
          var dialogTabPanel = {
            type: "tabpanel",
            tabs: [
              {
                title: "General",
                name: "general",
                items: getItems$1(editor)
              },
              getAdvancedTab(editor, "row")
            ]
          };
          var dialogPanel = {
            type: "panel",
            items: [{
              type: "grid",
              columns: 2,
              items: getItems$1(editor)
            }]
          };
          editor.windowManager.open({
            title: "Row Properties",
            size: "normal",
            body: hasAdvancedRowTab(editor) ? dialogTabPanel : dialogPanel,
            buttons: [
              {
                type: "cancel",
                name: "cancel",
                text: "Cancel"
              },
              {
                type: "submit",
                name: "save",
                text: "Save",
                primary: true
              }
            ],
            initialData: data,
            onSubmit: curry(onSubmitRowForm, editor, map$12(rows2, function(r3) {
              return r3.dom;
            }), data)
          });
        };
        var getItems = function(editor, classes, insertNewTable) {
          var rowColCountItems = !insertNewTable ? [] : [
            {
              type: "input",
              name: "cols",
              label: "Cols",
              inputMode: "numeric"
            },
            {
              type: "input",
              name: "rows",
              label: "Rows",
              inputMode: "numeric"
            }
          ];
          var alwaysItems = [
            {
              type: "input",
              name: "width",
              label: "Width"
            },
            {
              type: "input",
              name: "height",
              label: "Height"
            }
          ];
          var appearanceItems = hasAppearanceOptions(editor) ? [
            {
              type: "input",
              name: "cellspacing",
              label: "Cell spacing",
              inputMode: "numeric"
            },
            {
              type: "input",
              name: "cellpadding",
              label: "Cell padding",
              inputMode: "numeric"
            },
            {
              type: "input",
              name: "border",
              label: "Border width"
            },
            {
              type: "label",
              label: "Caption",
              items: [{
                type: "checkbox",
                name: "caption",
                label: "Show caption"
              }]
            }
          ] : [];
          var alignmentItem = [{
            type: "listbox",
            name: "align",
            label: "Alignment",
            items: [
              {
                text: "None",
                value: ""
              },
              {
                text: "Left",
                value: "left"
              },
              {
                text: "Center",
                value: "center"
              },
              {
                text: "Right",
                value: "right"
              }
            ]
          }];
          var classListItem = classes.length > 0 ? [{
            type: "listbox",
            name: "class",
            label: "Class",
            items: classes
          }] : [];
          return rowColCountItems.concat(alwaysItems).concat(appearanceItems).concat(alignmentItem).concat(classListItem);
        };
        var styleTDTH = function(dom, elm, name2, value2) {
          if (elm.tagName === "TD" || elm.tagName === "TH") {
            if (isString(name2)) {
              dom.setStyle(elm, name2, value2);
            } else {
              dom.setStyle(elm, name2);
            }
          } else {
            if (elm.children) {
              for (var i2 = 0; i2 < elm.children.length; i2++) {
                styleTDTH(dom, elm.children[i2], name2, value2);
              }
            }
          }
        };
        var applyDataToElement = function(editor, tableElm, data) {
          var dom = editor.dom;
          var attrs = {};
          var styles2 = {};
          attrs.class = data.class;
          styles2.height = addPxSuffix(data.height);
          if (dom.getAttrib(tableElm, "width") && !shouldStyleWithCss(editor)) {
            attrs.width = removePxSuffix(data.width);
          } else {
            styles2.width = addPxSuffix(data.width);
          }
          if (shouldStyleWithCss(editor)) {
            styles2["border-width"] = addPxSuffix(data.border);
            styles2["border-spacing"] = addPxSuffix(data.cellspacing);
          } else {
            attrs.border = data.border;
            attrs.cellpadding = data.cellpadding;
            attrs.cellspacing = data.cellspacing;
          }
          if (shouldStyleWithCss(editor) && tableElm.children) {
            for (var i2 = 0; i2 < tableElm.children.length; i2++) {
              styleTDTH(dom, tableElm.children[i2], {
                "border-width": addPxSuffix(data.border),
                "padding": addPxSuffix(data.cellpadding)
              });
              if (hasAdvancedTableTab(editor)) {
                styleTDTH(dom, tableElm.children[i2], { "border-color": data.bordercolor });
              }
            }
          }
          if (hasAdvancedTableTab(editor)) {
            styles2["background-color"] = data.backgroundcolor;
            styles2["border-color"] = data.bordercolor;
            styles2["border-style"] = data.borderstyle;
          }
          attrs.style = dom.serializeStyle(__assign(__assign({}, getDefaultStyles(editor)), styles2));
          dom.setAttribs(tableElm, __assign(__assign({}, getDefaultAttributes(editor)), attrs));
        };
        var onSubmitTableForm = function(editor, tableElm, oldData, api2) {
          var dom = editor.dom;
          var data = api2.getData();
          var modifiedData = filter$1(data, function(value2, key2) {
            return oldData[key2] !== value2;
          });
          api2.close();
          if (data.class === "") {
            delete data.class;
          }
          editor.undoManager.transact(function() {
            if (!tableElm) {
              var cols = parseInt(data.cols, 10) || 1;
              var rows2 = parseInt(data.rows, 10) || 1;
              tableElm = insert(editor, cols, rows2, 0, 0);
            }
            if (size(modifiedData) > 0) {
              applyDataToElement(editor, tableElm, data);
              var captionElm = dom.select("caption", tableElm)[0];
              if (captionElm && !data.caption || !captionElm && data.caption) {
                editor.execCommand("mceTableToggleCaption");
              }
              if (data.align === "") {
                unApplyAlign(editor, tableElm);
              } else {
                applyAlign(editor, tableElm, data.align);
              }
            }
            editor.focus();
            editor.addVisual();
            if (size(modifiedData) > 0) {
              var captionModified = has$1(modifiedData, "caption");
              var styleModified2 = captionModified ? size(modifiedData) > 1 : true;
              fireTableModified(editor, tableElm, {
                structure: captionModified,
                style: styleModified2
              });
            }
          });
        };
        var open = function(editor, insertNewTable) {
          var dom = editor.dom;
          var tableElm;
          var data = extractDataFromSettings(editor, hasAdvancedTableTab(editor));
          if (insertNewTable === false) {
            tableElm = dom.getParent(editor.selection.getStart(), "table", editor.getBody());
            if (tableElm) {
              data = extractDataFromTableElement(editor, tableElm, hasAdvancedTableTab(editor));
            } else {
              if (hasAdvancedTableTab(editor)) {
                data.borderstyle = "";
                data.bordercolor = "";
                data.backgroundcolor = "";
              }
            }
          } else {
            data.cols = "1";
            data.rows = "1";
            if (hasAdvancedTableTab(editor)) {
              data.borderstyle = "";
              data.bordercolor = "";
              data.backgroundcolor = "";
            }
          }
          var classes = buildListItems(getTableClassList(editor));
          if (classes.length > 0) {
            if (data.class) {
              data.class = data.class.replace(/\s*mce\-item\-table\s*/g, "");
            }
          }
          var generalPanel = {
            type: "grid",
            columns: 2,
            items: getItems(editor, classes, insertNewTable)
          };
          var nonAdvancedForm = function() {
            return {
              type: "panel",
              items: [generalPanel]
            };
          };
          var advancedForm = function() {
            return {
              type: "tabpanel",
              tabs: [
                {
                  title: "General",
                  name: "general",
                  items: [generalPanel]
                },
                getAdvancedTab(editor, "table")
              ]
            };
          };
          var dialogBody = hasAdvancedTableTab(editor) ? advancedForm() : nonAdvancedForm();
          editor.windowManager.open({
            title: "Table Properties",
            size: "normal",
            body: dialogBody,
            onSubmit: curry(onSubmitTableForm, editor, tableElm, data),
            buttons: [
              {
                type: "cancel",
                name: "cancel",
                text: "Cancel"
              },
              {
                type: "submit",
                name: "save",
                text: "Save",
                primary: true
              }
            ],
            initialData: data
          });
        };
        var getSelectionStartCellOrCaption = function(editor) {
          return getSelectionCellOrCaption(getSelectionStart(editor), getIsRoot(editor));
        };
        var getSelectionStartCell = function(editor) {
          return getSelectionCell(getSelectionStart(editor), getIsRoot(editor));
        };
        var registerCommands = function(editor, actions, cellSelection, selections, clipboard) {
          var isRoot = getIsRoot(editor);
          var eraseTable = function() {
            return getSelectionStartCellOrCaption(editor).each(function(cellOrCaption) {
              table(cellOrCaption, isRoot).filter(not(isRoot)).each(function(table2) {
                var cursor = SugarElement.fromText("");
                after$5(table2, cursor);
                remove$5(table2);
                if (editor.dom.isEmpty(editor.getBody())) {
                  editor.setContent("");
                  editor.selection.setCursorLocation();
                } else {
                  var rng = editor.dom.createRng();
                  rng.setStart(cursor.dom, 0);
                  rng.setEnd(cursor.dom, 0);
                  editor.selection.setRng(rng);
                  editor.nodeChanged();
                }
              });
            });
          };
          var setSizingMode = function(sizing) {
            return getSelectionStartCellOrCaption(editor).each(function(cellOrCaption) {
              var isForcedSizing = isResponsiveForced(editor) || isPixelsForced(editor) || isPercentagesForced(editor);
              if (!isForcedSizing) {
                table(cellOrCaption, isRoot).each(function(table2) {
                  if (sizing === "relative" && !isPercentSizing(table2)) {
                    enforcePercentage(table2);
                  } else if (sizing === "fixed" && !isPixelSizing(table2)) {
                    enforcePixels(table2);
                  } else if (sizing === "responsive" && !isNoneSizing(table2)) {
                    enforceNone(table2);
                  }
                  removeDataStyle(table2);
                  fireTableModified(editor, table2.dom, structureModified);
                });
              }
            });
          };
          var getTableFromCell = function(cell2) {
            return table(cell2, isRoot);
          };
          var performActionOnSelection = function(action) {
            return getSelectionStartCell(editor).bind(function(cell2) {
              return getTableFromCell(cell2).map(function(table2) {
                return action(table2, cell2);
              });
            });
          };
          var toggleTableClass = function(_ui, clazz) {
            performActionOnSelection(function(table2) {
              editor.formatter.toggle("tableclass", { value: clazz }, table2.dom);
              fireTableModified(editor, table2.dom, styleModified);
            });
          };
          var toggleTableCellClass = function(_ui, clazz) {
            performActionOnSelection(function(table2) {
              var selectedCells = getCellsFromSelection(selections);
              var allHaveClass = forall(selectedCells, function(cell2) {
                return editor.formatter.match("tablecellclass", { value: clazz }, cell2.dom);
              });
              var formatterAction = allHaveClass ? editor.formatter.remove : editor.formatter.apply;
              each$2(selectedCells, function(cell2) {
                return formatterAction("tablecellclass", { value: clazz }, cell2.dom);
              });
              fireTableModified(editor, table2.dom, styleModified);
            });
          };
          var toggleCaption = function() {
            getSelectionStartCellOrCaption(editor).each(function(cellOrCaption) {
              table(cellOrCaption, isRoot).each(function(table2) {
                child$1(table2, "caption").fold(function() {
                  var caption = SugarElement.fromTag("caption");
                  append$1(caption, SugarElement.fromText("Caption"));
                  appendAt(table2, caption, 0);
                  editor.selection.setCursorLocation(caption.dom, 0);
                }, function(caption) {
                  if (isTag("caption")(cellOrCaption)) {
                    one("td", table2).each(function(td) {
                      return editor.selection.setCursorLocation(td.dom, 0);
                    });
                  }
                  remove$5(caption);
                });
                fireTableModified(editor, table2.dom, structureModified);
              });
            });
          };
          var postExecute = function(_data) {
            editor.focus();
          };
          var actOnSelection = function(execute2, noEvents) {
            if (noEvents === void 0) {
              noEvents = false;
            }
            return performActionOnSelection(function(table2, startCell) {
              var targets = forMenu(selections, table2, startCell);
              execute2(table2, targets, noEvents).each(postExecute);
            });
          };
          var copyRowSelection = function() {
            return performActionOnSelection(function(table2, startCell) {
              var targets = forMenu(selections, table2, startCell);
              var generators = cellOperations(noop3, SugarElement.fromDom(editor.getDoc()), Optional.none());
              return copyRows(table2, targets, generators);
            });
          };
          var copyColSelection = function() {
            return performActionOnSelection(function(table2, startCell) {
              var targets = forMenu(selections, table2, startCell);
              return copyCols(table2, targets);
            });
          };
          var pasteOnSelection = function(execute2, getRows) {
            return getRows().each(function(rows2) {
              var clonedRows = map$12(rows2, function(row2) {
                return deep(row2);
              });
              performActionOnSelection(function(table2, startCell) {
                var generators = paste$1(SugarElement.fromDom(editor.getDoc()));
                var targets = pasteRows(selections, startCell, clonedRows, generators);
                execute2(table2, targets).each(postExecute);
              });
            });
          };
          var actOnType = function(getAction2) {
            return function(_ui, args) {
              return get$c(args, "type").each(function(type2) {
                actOnSelection(getAction2(type2), args.no_events);
              });
            };
          };
          each$1({
            mceTableSplitCells: function() {
              return actOnSelection(actions.unmergeCells);
            },
            mceTableMergeCells: function() {
              return actOnSelection(actions.mergeCells);
            },
            mceTableInsertRowBefore: function() {
              return actOnSelection(actions.insertRowsBefore);
            },
            mceTableInsertRowAfter: function() {
              return actOnSelection(actions.insertRowsAfter);
            },
            mceTableInsertColBefore: function() {
              return actOnSelection(actions.insertColumnsBefore);
            },
            mceTableInsertColAfter: function() {
              return actOnSelection(actions.insertColumnsAfter);
            },
            mceTableDeleteCol: function() {
              return actOnSelection(actions.deleteColumn);
            },
            mceTableDeleteRow: function() {
              return actOnSelection(actions.deleteRow);
            },
            mceTableCutCol: function() {
              return copyColSelection().each(function(selection2) {
                clipboard.setColumns(selection2);
                actOnSelection(actions.deleteColumn);
              });
            },
            mceTableCutRow: function() {
              return copyRowSelection().each(function(selection2) {
                clipboard.setRows(selection2);
                actOnSelection(actions.deleteRow);
              });
            },
            mceTableCopyCol: function() {
              return copyColSelection().each(function(selection2) {
                return clipboard.setColumns(selection2);
              });
            },
            mceTableCopyRow: function() {
              return copyRowSelection().each(function(selection2) {
                return clipboard.setRows(selection2);
              });
            },
            mceTablePasteColBefore: function() {
              return pasteOnSelection(actions.pasteColsBefore, clipboard.getColumns);
            },
            mceTablePasteColAfter: function() {
              return pasteOnSelection(actions.pasteColsAfter, clipboard.getColumns);
            },
            mceTablePasteRowBefore: function() {
              return pasteOnSelection(actions.pasteRowsBefore, clipboard.getRows);
            },
            mceTablePasteRowAfter: function() {
              return pasteOnSelection(actions.pasteRowsAfter, clipboard.getRows);
            },
            mceTableDelete: eraseTable,
            mceTableCellToggleClass: toggleTableCellClass,
            mceTableToggleClass: toggleTableClass,
            mceTableToggleCaption: toggleCaption,
            mceTableSizingMode: function(_ui, sizing) {
              return setSizingMode(sizing);
            },
            mceTableCellType: actOnType(function(type2) {
              return type2 === "th" ? actions.makeCellsHeader : actions.unmakeCellsHeader;
            }),
            mceTableColType: actOnType(function(type2) {
              return type2 === "th" ? actions.makeColumnsHeader : actions.unmakeColumnsHeader;
            }),
            mceTableRowType: actOnType(function(type2) {
              switch (type2) {
                case "header":
                  return actions.makeRowsHeader;
                case "footer":
                  return actions.makeRowsFooter;
                default:
                  return actions.makeRowsBody;
              }
            })
          }, function(func, name2) {
            return editor.addCommand(name2, func);
          });
          each$1({
            mceTableProps: curry(open, editor, false),
            mceTableRowProps: curry(open$1, editor),
            mceTableCellProps: curry(open$2, editor, selections)
          }, function(func, name2) {
            return editor.addCommand(name2, function() {
              return func();
            });
          });
          editor.addCommand("mceInsertTable", function(_ui, args) {
            if (isObject2(args) && keys(args).length > 0) {
              insertTableWithDataValidation(editor, args.rows, args.columns, args.options, "Invalid values for mceInsertTable - rows and columns values are required to insert a table.");
            } else {
              open(editor, true);
            }
          });
          editor.addCommand("mceTableApplyCellStyle", function(_ui, args) {
            var getFormatName = function(style) {
              return "tablecell" + style.toLowerCase().replace("-", "");
            };
            if (!isObject2(args)) {
              return;
            }
            var cells2 = getCellsFromSelection(selections);
            if (cells2.length === 0) {
              return;
            }
            var validArgs = filter$1(args, function(value2, style) {
              return editor.formatter.has(getFormatName(style)) && isString(value2);
            });
            if (isEmpty(validArgs)) {
              return;
            }
            each$1(validArgs, function(value2, style) {
              each$2(cells2, function(cell2) {
                DomModifier.normal(editor, cell2.dom).setFormat(getFormatName(style), value2);
              });
            });
            getTableFromCell(cells2[0]).each(function(table2) {
              return fireTableModified(editor, table2.dom, styleModified);
            });
          });
        };
        var registerQueryCommands = function(editor, actions, selections) {
          var isRoot = getIsRoot(editor);
          var lookupOnSelection = function(action) {
            return getSelectionCell(getSelectionStart(editor)).bind(function(cell2) {
              return table(cell2, isRoot).map(function(table2) {
                var targets = forMenu(selections, table2, cell2);
                return action(table2, targets);
              });
            }).getOr("");
          };
          each$1({
            mceTableRowType: function() {
              return lookupOnSelection(actions.getTableRowType);
            },
            mceTableCellType: function() {
              return lookupOnSelection(actions.getTableCellType);
            },
            mceTableColType: function() {
              return lookupOnSelection(actions.getTableColType);
            }
          }, function(func, name2) {
            return editor.addQueryValueHandler(name2, func);
          });
        };
        var Clipboard = function() {
          var rows2 = value();
          var cols = value();
          return {
            getRows: rows2.get,
            setRows: function(r3) {
              r3.fold(rows2.clear, rows2.set);
              cols.clear();
            },
            clearRows: rows2.clear,
            getColumns: cols.get,
            setColumns: function(c2) {
              c2.fold(cols.clear, cols.set);
              rows2.clear();
            },
            clearColumns: cols.clear
          };
        };
        var genericBase = {
          remove_similar: true,
          inherit: false
        };
        var cellBase = __assign({ selector: "td,th" }, genericBase);
        var cellFormats = {
          tablecellbackgroundcolor: __assign({ styles: { backgroundColor: "%value" } }, cellBase),
          tablecellverticalalign: __assign({ styles: { "vertical-align": "%value" } }, cellBase),
          tablecellbordercolor: __assign({ styles: { borderColor: "%value" } }, cellBase),
          tablecellclass: __assign({ classes: ["%value"] }, cellBase),
          tableclass: __assign({
            selector: "table",
            classes: ["%value"]
          }, genericBase),
          tablecellborderstyle: __assign({ styles: { borderStyle: "%value" } }, cellBase),
          tablecellborderwidth: __assign({ styles: { borderWidth: "%value" } }, cellBase)
        };
        var registerFormats = function(editor) {
          editor.formatter.register(cellFormats);
        };
        var adt$5 = Adt.generate([
          { none: ["current"] },
          { first: ["current"] },
          {
            middle: [
              "current",
              "target"
            ]
          },
          { last: ["current"] }
        ]);
        var none = function(current) {
          if (current === void 0) {
            current = void 0;
          }
          return adt$5.none(current);
        };
        var CellLocation = __assign(__assign({}, adt$5), { none });
        var walk2 = function(all2, current, index, direction, isEligible) {
          if (isEligible === void 0) {
            isEligible = always;
          }
          var forwards = direction === 1;
          if (!forwards && index <= 0) {
            return CellLocation.first(all2[0]);
          } else if (forwards && index >= all2.length - 1) {
            return CellLocation.last(all2[all2.length - 1]);
          } else {
            var newIndex = index + direction;
            var elem = all2[newIndex];
            return isEligible(elem) ? CellLocation.middle(current, elem) : walk2(all2, current, newIndex, direction, isEligible);
          }
        };
        var detect$1 = function(current, isRoot) {
          return table(current, isRoot).bind(function(table2) {
            var all2 = cells$1(table2);
            var index = findIndex2(all2, function(x2) {
              return eq$1(current, x2);
            });
            return index.map(function(index2) {
              return {
                index: index2,
                all: all2
              };
            });
          });
        };
        var next = function(current, isEligible, isRoot) {
          var detection = detect$1(current, isRoot);
          return detection.fold(function() {
            return CellLocation.none(current);
          }, function(info) {
            return walk2(info.all, current, info.index, 1, isEligible);
          });
        };
        var prev = function(current, isEligible, isRoot) {
          var detection = detect$1(current, isRoot);
          return detection.fold(function() {
            return CellLocation.none();
          }, function(info) {
            return walk2(info.all, current, info.index, -1, isEligible);
          });
        };
        var create$2 = function(start4, soffset, finish, foffset) {
          return {
            start: start4,
            soffset,
            finish,
            foffset
          };
        };
        var SimRange = { create: create$2 };
        var adt$4 = Adt.generate([
          { before: ["element"] },
          {
            on: [
              "element",
              "offset"
            ]
          },
          { after: ["element"] }
        ]);
        var cata$1 = function(subject, onBefore, onOn, onAfter) {
          return subject.fold(onBefore, onOn, onAfter);
        };
        var getStart$1 = function(situ) {
          return situ.fold(identity, identity, identity);
        };
        var before$2 = adt$4.before;
        var on2 = adt$4.on;
        var after$3 = adt$4.after;
        var Situ = {
          before: before$2,
          on: on2,
          after: after$3,
          cata: cata$1,
          getStart: getStart$1
        };
        var adt$3 = Adt.generate([
          { domRange: ["rng"] },
          {
            relative: [
              "startSitu",
              "finishSitu"
            ]
          },
          {
            exact: [
              "start",
              "soffset",
              "finish",
              "foffset"
            ]
          }
        ]);
        var exactFromRange = function(simRange) {
          return adt$3.exact(simRange.start, simRange.soffset, simRange.finish, simRange.foffset);
        };
        var getStart = function(selection2) {
          return selection2.match({
            domRange: function(rng) {
              return SugarElement.fromDom(rng.startContainer);
            },
            relative: function(startSitu, _finishSitu) {
              return Situ.getStart(startSitu);
            },
            exact: function(start4, _soffset, _finish, _foffset) {
              return start4;
            }
          });
        };
        var domRange = adt$3.domRange;
        var relative = adt$3.relative;
        var exact = adt$3.exact;
        var getWin = function(selection2) {
          var start4 = getStart(selection2);
          return defaultView(start4);
        };
        var range = SimRange.create;
        var SimSelection = {
          domRange,
          relative,
          exact,
          exactFromRange,
          getWin,
          range
        };
        var selectNode = function(win, element) {
          var rng = win.document.createRange();
          rng.selectNode(element.dom);
          return rng;
        };
        var selectNodeContents = function(win, element) {
          var rng = win.document.createRange();
          selectNodeContentsUsing(rng, element);
          return rng;
        };
        var selectNodeContentsUsing = function(rng, element) {
          return rng.selectNodeContents(element.dom);
        };
        var setStart = function(rng, situ) {
          situ.fold(function(e2) {
            rng.setStartBefore(e2.dom);
          }, function(e2, o2) {
            rng.setStart(e2.dom, o2);
          }, function(e2) {
            rng.setStartAfter(e2.dom);
          });
        };
        var setFinish = function(rng, situ) {
          situ.fold(function(e2) {
            rng.setEndBefore(e2.dom);
          }, function(e2, o2) {
            rng.setEnd(e2.dom, o2);
          }, function(e2) {
            rng.setEndAfter(e2.dom);
          });
        };
        var relativeToNative = function(win, startSitu, finishSitu) {
          var range2 = win.document.createRange();
          setStart(range2, startSitu);
          setFinish(range2, finishSitu);
          return range2;
        };
        var exactToNative = function(win, start4, soffset, finish, foffset) {
          var rng = win.document.createRange();
          rng.setStart(start4.dom, soffset);
          rng.setEnd(finish.dom, foffset);
          return rng;
        };
        var toRect = function(rect) {
          return {
            left: rect.left,
            top: rect.top,
            right: rect.right,
            bottom: rect.bottom,
            width: rect.width,
            height: rect.height
          };
        };
        var getFirstRect$1 = function(rng) {
          var rects = rng.getClientRects();
          var rect = rects.length > 0 ? rects[0] : rng.getBoundingClientRect();
          return rect.width > 0 || rect.height > 0 ? Optional.some(rect).map(toRect) : Optional.none();
        };
        var adt$2 = Adt.generate([
          {
            ltr: [
              "start",
              "soffset",
              "finish",
              "foffset"
            ]
          },
          {
            rtl: [
              "start",
              "soffset",
              "finish",
              "foffset"
            ]
          }
        ]);
        var fromRange = function(win, type2, range2) {
          return type2(SugarElement.fromDom(range2.startContainer), range2.startOffset, SugarElement.fromDom(range2.endContainer), range2.endOffset);
        };
        var getRanges = function(win, selection2) {
          return selection2.match({
            domRange: function(rng) {
              return {
                ltr: constant(rng),
                rtl: Optional.none
              };
            },
            relative: function(startSitu, finishSitu) {
              return {
                ltr: cached(function() {
                  return relativeToNative(win, startSitu, finishSitu);
                }),
                rtl: cached(function() {
                  return Optional.some(relativeToNative(win, finishSitu, startSitu));
                })
              };
            },
            exact: function(start4, soffset, finish, foffset) {
              return {
                ltr: cached(function() {
                  return exactToNative(win, start4, soffset, finish, foffset);
                }),
                rtl: cached(function() {
                  return Optional.some(exactToNative(win, finish, foffset, start4, soffset));
                })
              };
            }
          });
        };
        var doDiagnose = function(win, ranges) {
          var rng = ranges.ltr();
          if (rng.collapsed) {
            var reversed = ranges.rtl().filter(function(rev) {
              return rev.collapsed === false;
            });
            return reversed.map(function(rev) {
              return adt$2.rtl(SugarElement.fromDom(rev.endContainer), rev.endOffset, SugarElement.fromDom(rev.startContainer), rev.startOffset);
            }).getOrThunk(function() {
              return fromRange(win, adt$2.ltr, rng);
            });
          } else {
            return fromRange(win, adt$2.ltr, rng);
          }
        };
        var diagnose = function(win, selection2) {
          var ranges = getRanges(win, selection2);
          return doDiagnose(win, ranges);
        };
        var asLtrRange = function(win, selection2) {
          var diagnosis = diagnose(win, selection2);
          return diagnosis.match({
            ltr: function(start4, soffset, finish, foffset) {
              var rng = win.document.createRange();
              rng.setStart(start4.dom, soffset);
              rng.setEnd(finish.dom, foffset);
              return rng;
            },
            rtl: function(start4, soffset, finish, foffset) {
              var rng = win.document.createRange();
              rng.setStart(finish.dom, foffset);
              rng.setEnd(start4.dom, soffset);
              return rng;
            }
          });
        };
        adt$2.ltr;
        adt$2.rtl;
        var searchForPoint = function(rectForOffset, x2, y2, maxX, length) {
          if (length === 0) {
            return 0;
          } else if (x2 === maxX) {
            return length - 1;
          }
          var xDelta = maxX;
          for (var i2 = 1; i2 < length; i2++) {
            var rect = rectForOffset(i2);
            var curDeltaX = Math.abs(x2 - rect.left);
            if (y2 <= rect.bottom) {
              if (y2 < rect.top || curDeltaX > xDelta) {
                return i2 - 1;
              } else {
                xDelta = curDeltaX;
              }
            }
          }
          return 0;
        };
        var inRect = function(rect, x2, y2) {
          return x2 >= rect.left && x2 <= rect.right && y2 >= rect.top && y2 <= rect.bottom;
        };
        var locateOffset = function(doc, textnode, x2, y2, rect) {
          var rangeForOffset = function(o2) {
            var r3 = doc.dom.createRange();
            r3.setStart(textnode.dom, o2);
            r3.collapse(true);
            return r3;
          };
          var rectForOffset = function(o2) {
            var r3 = rangeForOffset(o2);
            return r3.getBoundingClientRect();
          };
          var length = get$9(textnode).length;
          var offset2 = searchForPoint(rectForOffset, x2, y2, rect.right, length);
          return rangeForOffset(offset2);
        };
        var locate$1 = function(doc, node, x2, y2) {
          var r3 = doc.dom.createRange();
          r3.selectNode(node.dom);
          var rects = r3.getClientRects();
          var foundRect = findMap(rects, function(rect) {
            return inRect(rect, x2, y2) ? Optional.some(rect) : Optional.none();
          });
          return foundRect.map(function(rect) {
            return locateOffset(doc, node, x2, y2, rect);
          });
        };
        var searchInChildren = function(doc, node, x2, y2) {
          var r3 = doc.dom.createRange();
          var nodes = children$3(node);
          return findMap(nodes, function(n2) {
            r3.selectNode(n2.dom);
            return inRect(r3.getBoundingClientRect(), x2, y2) ? locateNode(doc, n2, x2, y2) : Optional.none();
          });
        };
        var locateNode = function(doc, node, x2, y2) {
          return isText(node) ? locate$1(doc, node, x2, y2) : searchInChildren(doc, node, x2, y2);
        };
        var locate = function(doc, node, x2, y2) {
          var r3 = doc.dom.createRange();
          r3.selectNode(node.dom);
          var rect = r3.getBoundingClientRect();
          var boundedX = Math.max(rect.left, Math.min(rect.right, x2));
          var boundedY = Math.max(rect.top, Math.min(rect.bottom, y2));
          return locateNode(doc, node, boundedX, boundedY);
        };
        var COLLAPSE_TO_LEFT = true;
        var COLLAPSE_TO_RIGHT = false;
        var getCollapseDirection = function(rect, x2) {
          return x2 - rect.left < rect.right - x2 ? COLLAPSE_TO_LEFT : COLLAPSE_TO_RIGHT;
        };
        var createCollapsedNode = function(doc, target, collapseDirection) {
          var r3 = doc.dom.createRange();
          r3.selectNode(target.dom);
          r3.collapse(collapseDirection);
          return r3;
        };
        var locateInElement = function(doc, node, x2) {
          var cursorRange = doc.dom.createRange();
          cursorRange.selectNode(node.dom);
          var rect = cursorRange.getBoundingClientRect();
          var collapseDirection = getCollapseDirection(rect, x2);
          var f2 = collapseDirection === COLLAPSE_TO_LEFT ? first : last$1;
          return f2(node).map(function(target) {
            return createCollapsedNode(doc, target, collapseDirection);
          });
        };
        var locateInEmpty = function(doc, node, x2) {
          var rect = node.dom.getBoundingClientRect();
          var collapseDirection = getCollapseDirection(rect, x2);
          return Optional.some(createCollapsedNode(doc, node, collapseDirection));
        };
        var search = function(doc, node, x2) {
          var f2 = children$3(node).length === 0 ? locateInEmpty : locateInElement;
          return f2(doc, node, x2);
        };
        var caretPositionFromPoint = function(doc, x2, y2) {
          var _a, _b;
          return Optional.from((_b = (_a = doc.dom).caretPositionFromPoint) === null || _b === void 0 ? void 0 : _b.call(_a, x2, y2)).bind(function(pos) {
            if (pos.offsetNode === null) {
              return Optional.none();
            }
            var r3 = doc.dom.createRange();
            r3.setStart(pos.offsetNode, pos.offset);
            r3.collapse();
            return Optional.some(r3);
          });
        };
        var caretRangeFromPoint = function(doc, x2, y2) {
          var _a, _b;
          return Optional.from((_b = (_a = doc.dom).caretRangeFromPoint) === null || _b === void 0 ? void 0 : _b.call(_a, x2, y2));
        };
        var searchTextNodes = function(doc, node, x2, y2) {
          var r3 = doc.dom.createRange();
          r3.selectNode(node.dom);
          var rect = r3.getBoundingClientRect();
          var boundedX = Math.max(rect.left, Math.min(rect.right, x2));
          var boundedY = Math.max(rect.top, Math.min(rect.bottom, y2));
          return locate(doc, node, boundedX, boundedY);
        };
        var searchFromPoint = function(doc, x2, y2) {
          return SugarElement.fromPoint(doc, x2, y2).bind(function(elem) {
            var fallback2 = function() {
              return search(doc, elem, x2);
            };
            return children$3(elem).length === 0 ? fallback2() : searchTextNodes(doc, elem, x2, y2).orThunk(fallback2);
          });
        };
        var availableSearch = function() {
          if (document.caretPositionFromPoint) {
            return caretPositionFromPoint;
          } else if (document.caretRangeFromPoint) {
            return caretRangeFromPoint;
          } else {
            return searchFromPoint;
          }
        }();
        var fromPoint = function(win, x2, y2) {
          var doc = SugarElement.fromDom(win.document);
          return availableSearch(doc, x2, y2).map(function(rng) {
            return SimRange.create(SugarElement.fromDom(rng.startContainer), rng.startOffset, SugarElement.fromDom(rng.endContainer), rng.endOffset);
          });
        };
        var beforeSpecial = function(element, offset2) {
          var name$1 = name(element);
          if (name$1 === "input") {
            return Situ.after(element);
          } else if (!contains$2([
            "br",
            "img"
          ], name$1)) {
            return Situ.on(element, offset2);
          } else {
            return offset2 === 0 ? Situ.before(element) : Situ.after(element);
          }
        };
        var preprocessRelative = function(startSitu, finishSitu) {
          var start4 = startSitu.fold(Situ.before, beforeSpecial, Situ.after);
          var finish = finishSitu.fold(Situ.before, beforeSpecial, Situ.after);
          return SimSelection.relative(start4, finish);
        };
        var preprocessExact = function(start4, soffset, finish, foffset) {
          var startSitu = beforeSpecial(start4, soffset);
          var finishSitu = beforeSpecial(finish, foffset);
          return SimSelection.relative(startSitu, finishSitu);
        };
        var preprocess = function(selection2) {
          return selection2.match({
            domRange: function(rng) {
              var start4 = SugarElement.fromDom(rng.startContainer);
              var finish = SugarElement.fromDom(rng.endContainer);
              return preprocessExact(start4, rng.startOffset, finish, rng.endOffset);
            },
            relative: preprocessRelative,
            exact: preprocessExact
          });
        };
        var makeRange = function(start4, soffset, finish, foffset) {
          var doc = owner(start4);
          var rng = doc.dom.createRange();
          rng.setStart(start4.dom, soffset);
          rng.setEnd(finish.dom, foffset);
          return rng;
        };
        var after$2 = function(start4, soffset, finish, foffset) {
          var r3 = makeRange(start4, soffset, finish, foffset);
          var same = eq$1(start4, finish) && soffset === foffset;
          return r3.collapsed && !same;
        };
        var getNativeSelection = function(win) {
          return Optional.from(win.getSelection());
        };
        var doSetNativeRange = function(win, rng) {
          getNativeSelection(win).each(function(selection2) {
            selection2.removeAllRanges();
            selection2.addRange(rng);
          });
        };
        var doSetRange = function(win, start4, soffset, finish, foffset) {
          var rng = exactToNative(win, start4, soffset, finish, foffset);
          doSetNativeRange(win, rng);
        };
        var setLegacyRtlRange = function(win, selection2, start4, soffset, finish, foffset) {
          selection2.collapse(start4.dom, soffset);
          selection2.extend(finish.dom, foffset);
        };
        var setRangeFromRelative = function(win, relative2) {
          return diagnose(win, relative2).match({
            ltr: function(start4, soffset, finish, foffset) {
              doSetRange(win, start4, soffset, finish, foffset);
            },
            rtl: function(start4, soffset, finish, foffset) {
              getNativeSelection(win).each(function(selection2) {
                if (selection2.setBaseAndExtent) {
                  selection2.setBaseAndExtent(start4.dom, soffset, finish.dom, foffset);
                } else if (selection2.extend) {
                  try {
                    setLegacyRtlRange(win, selection2, start4, soffset, finish, foffset);
                  } catch (e2) {
                    doSetRange(win, finish, foffset, start4, soffset);
                  }
                } else {
                  doSetRange(win, finish, foffset, start4, soffset);
                }
              });
            }
          });
        };
        var setExact = function(win, start4, soffset, finish, foffset) {
          var relative2 = preprocessExact(start4, soffset, finish, foffset);
          setRangeFromRelative(win, relative2);
        };
        var setRelative = function(win, startSitu, finishSitu) {
          var relative2 = preprocessRelative(startSitu, finishSitu);
          setRangeFromRelative(win, relative2);
        };
        var toNative = function(selection2) {
          var win = SimSelection.getWin(selection2).dom;
          var getDomRange = function(start4, soffset, finish, foffset) {
            return exactToNative(win, start4, soffset, finish, foffset);
          };
          var filtered = preprocess(selection2);
          return diagnose(win, filtered).match({
            ltr: getDomRange,
            rtl: getDomRange
          });
        };
        var readRange = function(selection2) {
          if (selection2.rangeCount > 0) {
            var firstRng = selection2.getRangeAt(0);
            var lastRng = selection2.getRangeAt(selection2.rangeCount - 1);
            return Optional.some(SimRange.create(SugarElement.fromDom(firstRng.startContainer), firstRng.startOffset, SugarElement.fromDom(lastRng.endContainer), lastRng.endOffset));
          } else {
            return Optional.none();
          }
        };
        var doGetExact = function(selection2) {
          if (selection2.anchorNode === null || selection2.focusNode === null) {
            return readRange(selection2);
          } else {
            var anchor = SugarElement.fromDom(selection2.anchorNode);
            var focus_1 = SugarElement.fromDom(selection2.focusNode);
            return after$2(anchor, selection2.anchorOffset, focus_1, selection2.focusOffset) ? Optional.some(SimRange.create(anchor, selection2.anchorOffset, focus_1, selection2.focusOffset)) : readRange(selection2);
          }
        };
        var setToElement = function(win, element, selectNodeContents$1) {
          if (selectNodeContents$1 === void 0) {
            selectNodeContents$1 = true;
          }
          var rngGetter = selectNodeContents$1 ? selectNodeContents : selectNode;
          var rng = rngGetter(win, element);
          doSetNativeRange(win, rng);
        };
        var getExact = function(win) {
          return getNativeSelection(win).filter(function(sel) {
            return sel.rangeCount > 0;
          }).bind(doGetExact);
        };
        var get$1 = function(win) {
          return getExact(win).map(function(range2) {
            return SimSelection.exact(range2.start, range2.soffset, range2.finish, range2.foffset);
          });
        };
        var getFirstRect = function(win, selection2) {
          var rng = asLtrRange(win, selection2);
          return getFirstRect$1(rng);
        };
        var getAtPoint = function(win, x2, y2) {
          return fromPoint(win, x2, y2);
        };
        var clear = function(win) {
          getNativeSelection(win).each(function(selection2) {
            return selection2.removeAllRanges();
          });
        };
        var global$1 = tinymce.util.Tools.resolve("tinymce.util.VK");
        var forward = function(editor, isRoot, cell2) {
          return go$1(editor, isRoot, next(cell2, isEditable$1));
        };
        var backward = function(editor, isRoot, cell2) {
          return go$1(editor, isRoot, prev(cell2, isEditable$1));
        };
        var getCellFirstCursorPosition = function(editor, cell2) {
          var selection2 = SimSelection.exact(cell2, 0, cell2, 0);
          return toNative(selection2);
        };
        var go$1 = function(editor, isRoot, cell2) {
          return cell2.fold(Optional.none, Optional.none, function(current, next2) {
            return first(next2).map(function(cell3) {
              return getCellFirstCursorPosition(editor, cell3);
            });
          }, function(current) {
            editor.execCommand("mceTableInsertRowAfter");
            return forward(editor, isRoot, current);
          });
        };
        var rootElements = [
          "table",
          "li",
          "dl"
        ];
        var handle$1 = function(event, editor, cellSelection) {
          if (event.keyCode === global$1.TAB) {
            var body_1 = getBody(editor);
            var isRoot_1 = function(element) {
              var name$1 = name(element);
              return eq$1(element, body_1) || contains$2(rootElements, name$1);
            };
            var rng = editor.selection.getRng();
            var container = SugarElement.fromDom(event.shiftKey ? rng.startContainer : rng.endContainer);
            cell(container, isRoot_1).each(function(cell2) {
              event.preventDefault();
              table(cell2, isRoot_1).each(cellSelection.clear);
              editor.selection.collapse(event.shiftKey);
              var navigation = event.shiftKey ? backward : forward;
              var rng2 = navigation(editor, isRoot_1, cell2);
              rng2.each(function(range2) {
                editor.selection.setRng(range2);
              });
            });
          }
        };
        var create$1 = function(selection2, kill) {
          return {
            selection: selection2,
            kill
          };
        };
        var Response2 = { create: create$1 };
        var create = function(start4, soffset, finish, foffset) {
          return {
            start: Situ.on(start4, soffset),
            finish: Situ.on(finish, foffset)
          };
        };
        var Situs = { create };
        var convertToRange = function(win, selection2) {
          var rng = asLtrRange(win, selection2);
          return SimRange.create(SugarElement.fromDom(rng.startContainer), rng.startOffset, SugarElement.fromDom(rng.endContainer), rng.endOffset);
        };
        var makeSitus = Situs.create;
        var sync = function(container, isRoot, start4, soffset, finish, foffset, selectRange) {
          if (!(eq$1(start4, finish) && soffset === foffset)) {
            return closest$1(start4, "td,th", isRoot).bind(function(s2) {
              return closest$1(finish, "td,th", isRoot).bind(function(f2) {
                return detect(container, isRoot, s2, f2, selectRange);
              });
            });
          } else {
            return Optional.none();
          }
        };
        var detect = function(container, isRoot, start4, finish, selectRange) {
          if (!eq$1(start4, finish)) {
            return identify(start4, finish, isRoot).bind(function(cellSel) {
              var boxes = cellSel.boxes.getOr([]);
              if (boxes.length > 1) {
                selectRange(container, boxes, cellSel.start, cellSel.finish);
                return Optional.some(Response2.create(Optional.some(makeSitus(start4, 0, start4, getEnd(start4))), true));
              } else {
                return Optional.none();
              }
            });
          } else {
            return Optional.none();
          }
        };
        var update = function(rows2, columns2, container, selected, annotations) {
          var updateSelection = function(newSels) {
            annotations.clearBeforeUpdate(container);
            annotations.selectRange(container, newSels.boxes, newSels.start, newSels.finish);
            return newSels.boxes;
          };
          return shiftSelection(selected, rows2, columns2, annotations.firstSelectedSelector, annotations.lastSelectedSelector).map(updateSelection);
        };
        var traverse = function(item, mode) {
          return {
            item,
            mode
          };
        };
        var backtrack = function(universe2, item, _direction, transition) {
          if (transition === void 0) {
            transition = sidestep;
          }
          return universe2.property().parent(item).map(function(p2) {
            return traverse(p2, transition);
          });
        };
        var sidestep = function(universe2, item, direction, transition) {
          if (transition === void 0) {
            transition = advance;
          }
          return direction.sibling(universe2, item).map(function(p2) {
            return traverse(p2, transition);
          });
        };
        var advance = function(universe2, item, direction, transition) {
          if (transition === void 0) {
            transition = advance;
          }
          var children2 = universe2.property().children(item);
          var result = direction.first(children2);
          return result.map(function(r3) {
            return traverse(r3, transition);
          });
        };
        var successors = [
          {
            current: backtrack,
            next: sidestep,
            fallback: Optional.none()
          },
          {
            current: sidestep,
            next: advance,
            fallback: Optional.some(backtrack)
          },
          {
            current: advance,
            next: advance,
            fallback: Optional.some(sidestep)
          }
        ];
        var go = function(universe2, item, mode, direction, rules) {
          if (rules === void 0) {
            rules = successors;
          }
          var ruleOpt = find$1(rules, function(succ) {
            return succ.current === mode;
          });
          return ruleOpt.bind(function(rule) {
            return rule.current(universe2, item, direction, rule.next).orThunk(function() {
              return rule.fallback.bind(function(fb) {
                return go(universe2, item, fb, direction);
              });
            });
          });
        };
        var left$1 = function() {
          var sibling = function(universe2, item) {
            return universe2.query().prevSibling(item);
          };
          var first2 = function(children2) {
            return children2.length > 0 ? Optional.some(children2[children2.length - 1]) : Optional.none();
          };
          return {
            sibling,
            first: first2
          };
        };
        var right$1 = function() {
          var sibling = function(universe2, item) {
            return universe2.query().nextSibling(item);
          };
          var first2 = function(children2) {
            return children2.length > 0 ? Optional.some(children2[0]) : Optional.none();
          };
          return {
            sibling,
            first: first2
          };
        };
        var Walkers = {
          left: left$1,
          right: right$1
        };
        var hone = function(universe2, item, predicate, mode, direction, isRoot) {
          var next2 = go(universe2, item, mode, direction);
          return next2.bind(function(n2) {
            if (isRoot(n2.item)) {
              return Optional.none();
            } else {
              return predicate(n2.item) ? Optional.some(n2.item) : hone(universe2, n2.item, predicate, n2.mode, direction, isRoot);
            }
          });
        };
        var left2 = function(universe2, item, predicate, isRoot) {
          return hone(universe2, item, predicate, sidestep, Walkers.left(), isRoot);
        };
        var right2 = function(universe2, item, predicate, isRoot) {
          return hone(universe2, item, predicate, sidestep, Walkers.right(), isRoot);
        };
        var isLeaf = function(universe2) {
          return function(element) {
            return universe2.property().children(element).length === 0;
          };
        };
        var before$1 = function(universe2, item, isRoot) {
          return seekLeft$1(universe2, item, isLeaf(universe2), isRoot);
        };
        var after$1 = function(universe2, item, isRoot) {
          return seekRight$1(universe2, item, isLeaf(universe2), isRoot);
        };
        var seekLeft$1 = left2;
        var seekRight$1 = right2;
        var universe = DomUniverse();
        var before = function(element, isRoot) {
          return before$1(universe, element, isRoot);
        };
        var after = function(element, isRoot) {
          return after$1(universe, element, isRoot);
        };
        var seekLeft = function(element, predicate, isRoot) {
          return seekLeft$1(universe, element, predicate, isRoot);
        };
        var seekRight = function(element, predicate, isRoot) {
          return seekRight$1(universe, element, predicate, isRoot);
        };
        var ancestor = function(scope, predicate, isRoot) {
          return ancestor$2(scope, predicate, isRoot).isSome();
        };
        var adt$1 = Adt.generate([
          { none: ["message"] },
          { success: [] },
          { failedUp: ["cell"] },
          { failedDown: ["cell"] }
        ]);
        var isOverlapping = function(bridge, before2, after2) {
          var beforeBounds = bridge.getRect(before2);
          var afterBounds = bridge.getRect(after2);
          return afterBounds.right > beforeBounds.left && afterBounds.left < beforeBounds.right;
        };
        var isRow = function(elem) {
          return closest$1(elem, "tr");
        };
        var verify = function(bridge, before2, beforeOffset, after2, afterOffset, failure, isRoot) {
          return closest$1(after2, "td,th", isRoot).bind(function(afterCell) {
            return closest$1(before2, "td,th", isRoot).map(function(beforeCell) {
              if (!eq$1(afterCell, beforeCell)) {
                return sharedOne(isRow, [
                  afterCell,
                  beforeCell
                ]).fold(function() {
                  return isOverlapping(bridge, beforeCell, afterCell) ? adt$1.success() : failure(beforeCell);
                }, function(_sharedRow) {
                  return failure(beforeCell);
                });
              } else {
                return eq$1(after2, afterCell) && getEnd(afterCell) === afterOffset ? failure(beforeCell) : adt$1.none("in same cell");
              }
            });
          }).getOr(adt$1.none("default"));
        };
        var cata = function(subject, onNone, onSuccess, onFailedUp, onFailedDown) {
          return subject.fold(onNone, onSuccess, onFailedUp, onFailedDown);
        };
        var BeforeAfter = __assign(__assign({}, adt$1), {
          verify,
          cata
        });
        var inParent = function(parent2, children2, element, index) {
          return {
            parent: parent2,
            children: children2,
            element,
            index
          };
        };
        var indexInParent = function(element) {
          return parent(element).bind(function(parent2) {
            var children2 = children$3(parent2);
            return indexOf2(children2, element).map(function(index) {
              return inParent(parent2, children2, element, index);
            });
          });
        };
        var indexOf2 = function(elements2, element) {
          return findIndex2(elements2, curry(eq$1, element));
        };
        var isBr = function(elem) {
          return name(elem) === "br";
        };
        var gatherer = function(cand, gather, isRoot) {
          return gather(cand, isRoot).bind(function(target) {
            return isText(target) && get$9(target).trim().length === 0 ? gatherer(target, gather, isRoot) : Optional.some(target);
          });
        };
        var handleBr = function(isRoot, element, direction) {
          return direction.traverse(element).orThunk(function() {
            return gatherer(element, direction.gather, isRoot);
          }).map(direction.relative);
        };
        var findBr = function(element, offset2) {
          return child$3(element, offset2).filter(isBr).orThunk(function() {
            return child$3(element, offset2 - 1).filter(isBr);
          });
        };
        var handleParent = function(isRoot, element, offset2, direction) {
          return findBr(element, offset2).bind(function(br) {
            return direction.traverse(br).fold(function() {
              return gatherer(br, direction.gather, isRoot).map(direction.relative);
            }, function(adjacent) {
              return indexInParent(adjacent).map(function(info) {
                return Situ.on(info.parent, info.index);
              });
            });
          });
        };
        var tryBr = function(isRoot, element, offset2, direction) {
          var target = isBr(element) ? handleBr(isRoot, element, direction) : handleParent(isRoot, element, offset2, direction);
          return target.map(function(tgt) {
            return {
              start: tgt,
              finish: tgt
            };
          });
        };
        var process2 = function(analysis) {
          return BeforeAfter.cata(analysis, function(_message) {
            return Optional.none();
          }, function() {
            return Optional.none();
          }, function(cell2) {
            return Optional.some(point(cell2, 0));
          }, function(cell2) {
            return Optional.some(point(cell2, getEnd(cell2)));
          });
        };
        var moveDown = function(caret, amount) {
          return {
            left: caret.left,
            top: caret.top + amount,
            right: caret.right,
            bottom: caret.bottom + amount
          };
        };
        var moveUp = function(caret, amount) {
          return {
            left: caret.left,
            top: caret.top - amount,
            right: caret.right,
            bottom: caret.bottom - amount
          };
        };
        var translate = function(caret, xDelta, yDelta) {
          return {
            left: caret.left + xDelta,
            top: caret.top + yDelta,
            right: caret.right + xDelta,
            bottom: caret.bottom + yDelta
          };
        };
        var getTop = function(caret) {
          return caret.top;
        };
        var getBottom = function(caret) {
          return caret.bottom;
        };
        var getPartialBox = function(bridge, element, offset2) {
          if (offset2 >= 0 && offset2 < getEnd(element)) {
            return bridge.getRangedRect(element, offset2, element, offset2 + 1);
          } else if (offset2 > 0) {
            return bridge.getRangedRect(element, offset2 - 1, element, offset2);
          }
          return Optional.none();
        };
        var toCaret = function(rect) {
          return {
            left: rect.left,
            top: rect.top,
            right: rect.right,
            bottom: rect.bottom
          };
        };
        var getElemBox = function(bridge, element) {
          return Optional.some(bridge.getRect(element));
        };
        var getBoxAt = function(bridge, element, offset2) {
          if (isElement3(element)) {
            return getElemBox(bridge, element).map(toCaret);
          } else if (isText(element)) {
            return getPartialBox(bridge, element, offset2).map(toCaret);
          } else {
            return Optional.none();
          }
        };
        var getEntireBox = function(bridge, element) {
          if (isElement3(element)) {
            return getElemBox(bridge, element).map(toCaret);
          } else if (isText(element)) {
            return bridge.getRangedRect(element, 0, element, getEnd(element)).map(toCaret);
          } else {
            return Optional.none();
          }
        };
        var JUMP_SIZE = 5;
        var NUM_RETRIES = 100;
        var adt = Adt.generate([
          { none: [] },
          { retry: ["caret"] }
        ]);
        var isOutside = function(caret, box) {
          return caret.left < box.left || Math.abs(box.right - caret.left) < 1 || caret.left > box.right;
        };
        var inOutsideBlock = function(bridge, element, caret) {
          return closest$2(element, isBlock).fold(never, function(cell2) {
            return getEntireBox(bridge, cell2).exists(function(box) {
              return isOutside(caret, box);
            });
          });
        };
        var adjustDown = function(bridge, element, guessBox, original, caret) {
          var lowerCaret = moveDown(caret, JUMP_SIZE);
          if (Math.abs(guessBox.bottom - original.bottom) < 1) {
            return adt.retry(lowerCaret);
          } else if (guessBox.top > caret.bottom) {
            return adt.retry(lowerCaret);
          } else if (guessBox.top === caret.bottom) {
            return adt.retry(moveDown(caret, 1));
          } else {
            return inOutsideBlock(bridge, element, caret) ? adt.retry(translate(lowerCaret, JUMP_SIZE, 0)) : adt.none();
          }
        };
        var adjustUp = function(bridge, element, guessBox, original, caret) {
          var higherCaret = moveUp(caret, JUMP_SIZE);
          if (Math.abs(guessBox.top - original.top) < 1) {
            return adt.retry(higherCaret);
          } else if (guessBox.bottom < caret.top) {
            return adt.retry(higherCaret);
          } else if (guessBox.bottom === caret.top) {
            return adt.retry(moveUp(caret, 1));
          } else {
            return inOutsideBlock(bridge, element, caret) ? adt.retry(translate(higherCaret, JUMP_SIZE, 0)) : adt.none();
          }
        };
        var upMovement = {
          point: getTop,
          adjuster: adjustUp,
          move: moveUp,
          gather: before
        };
        var downMovement = {
          point: getBottom,
          adjuster: adjustDown,
          move: moveDown,
          gather: after
        };
        var isAtTable = function(bridge, x2, y2) {
          return bridge.elementFromPoint(x2, y2).filter(function(elm) {
            return name(elm) === "table";
          }).isSome();
        };
        var adjustForTable = function(bridge, movement, original, caret, numRetries) {
          return adjustTil(bridge, movement, original, movement.move(caret, JUMP_SIZE), numRetries);
        };
        var adjustTil = function(bridge, movement, original, caret, numRetries) {
          if (numRetries === 0) {
            return Optional.some(caret);
          }
          if (isAtTable(bridge, caret.left, movement.point(caret))) {
            return adjustForTable(bridge, movement, original, caret, numRetries - 1);
          }
          return bridge.situsFromPoint(caret.left, movement.point(caret)).bind(function(guess) {
            return guess.start.fold(Optional.none, function(element) {
              return getEntireBox(bridge, element).bind(function(guessBox) {
                return movement.adjuster(bridge, element, guessBox, original, caret).fold(Optional.none, function(newCaret) {
                  return adjustTil(bridge, movement, original, newCaret, numRetries - 1);
                });
              }).orThunk(function() {
                return Optional.some(caret);
              });
            }, Optional.none);
          });
        };
        var ieTryDown = function(bridge, caret) {
          return bridge.situsFromPoint(caret.left, caret.bottom + JUMP_SIZE);
        };
        var ieTryUp = function(bridge, caret) {
          return bridge.situsFromPoint(caret.left, caret.top - JUMP_SIZE);
        };
        var checkScroll = function(movement, adjusted, bridge) {
          if (movement.point(adjusted) > bridge.getInnerHeight()) {
            return Optional.some(movement.point(adjusted) - bridge.getInnerHeight());
          } else if (movement.point(adjusted) < 0) {
            return Optional.some(-movement.point(adjusted));
          } else {
            return Optional.none();
          }
        };
        var retry = function(movement, bridge, caret) {
          var moved = movement.move(caret, JUMP_SIZE);
          var adjusted = adjustTil(bridge, movement, caret, moved, NUM_RETRIES).getOr(moved);
          return checkScroll(movement, adjusted, bridge).fold(function() {
            return bridge.situsFromPoint(adjusted.left, movement.point(adjusted));
          }, function(delta) {
            bridge.scrollBy(0, delta);
            return bridge.situsFromPoint(adjusted.left, movement.point(adjusted) - delta);
          });
        };
        var Retries = {
          tryUp: curry(retry, upMovement),
          tryDown: curry(retry, downMovement),
          ieTryUp,
          ieTryDown,
          getJumpSize: constant(JUMP_SIZE)
        };
        var MAX_RETRIES = 20;
        var findSpot = function(bridge, isRoot, direction) {
          return bridge.getSelection().bind(function(sel) {
            return tryBr(isRoot, sel.finish, sel.foffset, direction).fold(function() {
              return Optional.some(point(sel.finish, sel.foffset));
            }, function(brNeighbour) {
              var range2 = bridge.fromSitus(brNeighbour);
              var analysis = BeforeAfter.verify(bridge, sel.finish, sel.foffset, range2.finish, range2.foffset, direction.failure, isRoot);
              return process2(analysis);
            });
          });
        };
        var scan = function(bridge, isRoot, element, offset2, direction, numRetries) {
          if (numRetries === 0) {
            return Optional.none();
          }
          return tryCursor(bridge, isRoot, element, offset2, direction).bind(function(situs) {
            var range2 = bridge.fromSitus(situs);
            var analysis = BeforeAfter.verify(bridge, element, offset2, range2.finish, range2.foffset, direction.failure, isRoot);
            return BeforeAfter.cata(analysis, function() {
              return Optional.none();
            }, function() {
              return Optional.some(situs);
            }, function(cell2) {
              if (eq$1(element, cell2) && offset2 === 0) {
                return tryAgain(bridge, element, offset2, moveUp, direction);
              } else {
                return scan(bridge, isRoot, cell2, 0, direction, numRetries - 1);
              }
            }, function(cell2) {
              if (eq$1(element, cell2) && offset2 === getEnd(cell2)) {
                return tryAgain(bridge, element, offset2, moveDown, direction);
              } else {
                return scan(bridge, isRoot, cell2, getEnd(cell2), direction, numRetries - 1);
              }
            });
          });
        };
        var tryAgain = function(bridge, element, offset2, move, direction) {
          return getBoxAt(bridge, element, offset2).bind(function(box) {
            return tryAt(bridge, direction, move(box, Retries.getJumpSize()));
          });
        };
        var tryAt = function(bridge, direction, box) {
          var browser = detect$3().browser;
          if (browser.isChrome() || browser.isSafari() || browser.isFirefox() || browser.isEdge()) {
            return direction.otherRetry(bridge, box);
          } else if (browser.isIE()) {
            return direction.ieRetry(bridge, box);
          } else {
            return Optional.none();
          }
        };
        var tryCursor = function(bridge, isRoot, element, offset2, direction) {
          return getBoxAt(bridge, element, offset2).bind(function(box) {
            return tryAt(bridge, direction, box);
          });
        };
        var handle = function(bridge, isRoot, direction) {
          return findSpot(bridge, isRoot, direction).bind(function(spot) {
            return scan(bridge, isRoot, spot.element, spot.offset, direction, MAX_RETRIES).map(bridge.fromSitus);
          });
        };
        var inSameTable = function(elem, table2) {
          return ancestor(elem, function(e2) {
            return parent(e2).exists(function(p2) {
              return eq$1(p2, table2);
            });
          });
        };
        var simulate = function(bridge, isRoot, direction, initial, anchor) {
          return closest$1(initial, "td,th", isRoot).bind(function(start4) {
            return closest$1(start4, "table", isRoot).bind(function(table2) {
              if (!inSameTable(anchor, table2)) {
                return Optional.none();
              }
              return handle(bridge, isRoot, direction).bind(function(range2) {
                return closest$1(range2.finish, "td,th", isRoot).map(function(finish) {
                  return {
                    start: start4,
                    finish,
                    range: range2
                  };
                });
              });
            });
          });
        };
        var navigate = function(bridge, isRoot, direction, initial, anchor, precheck) {
          if (detect$3().browser.isIE()) {
            return Optional.none();
          } else {
            return precheck(initial, isRoot).orThunk(function() {
              return simulate(bridge, isRoot, direction, initial, anchor).map(function(info) {
                var range2 = info.range;
                return Response2.create(Optional.some(makeSitus(range2.start, range2.soffset, range2.finish, range2.foffset)), true);
              });
            });
          }
        };
        var firstUpCheck = function(initial, isRoot) {
          return closest$1(initial, "tr", isRoot).bind(function(startRow) {
            return closest$1(startRow, "table", isRoot).bind(function(table2) {
              var rows2 = descendants(table2, "tr");
              if (eq$1(startRow, rows2[0])) {
                return seekLeft(table2, function(element) {
                  return last$1(element).isSome();
                }, isRoot).map(function(last2) {
                  var lastOffset = getEnd(last2);
                  return Response2.create(Optional.some(makeSitus(last2, lastOffset, last2, lastOffset)), true);
                });
              } else {
                return Optional.none();
              }
            });
          });
        };
        var lastDownCheck = function(initial, isRoot) {
          return closest$1(initial, "tr", isRoot).bind(function(startRow) {
            return closest$1(startRow, "table", isRoot).bind(function(table2) {
              var rows2 = descendants(table2, "tr");
              if (eq$1(startRow, rows2[rows2.length - 1])) {
                return seekRight(table2, function(element) {
                  return first(element).isSome();
                }, isRoot).map(function(first2) {
                  return Response2.create(Optional.some(makeSitus(first2, 0, first2, 0)), true);
                });
              } else {
                return Optional.none();
              }
            });
          });
        };
        var select = function(bridge, container, isRoot, direction, initial, anchor, selectRange) {
          return simulate(bridge, isRoot, direction, initial, anchor).bind(function(info) {
            return detect(container, isRoot, info.start, info.finish, selectRange);
          });
        };
        var findCell = function(target, isRoot) {
          return closest$1(target, "td,th", isRoot);
        };
        var MouseSelection = function(bridge, container, isRoot, annotations) {
          var cursor = value();
          var clearstate = cursor.clear;
          var applySelection = function(event) {
            cursor.on(function(start4) {
              annotations.clearBeforeUpdate(container);
              findCell(event.target, isRoot).each(function(finish) {
                identify(start4, finish, isRoot).each(function(cellSel) {
                  var boxes = cellSel.boxes.getOr([]);
                  if (boxes.length === 1) {
                    var singleCell = boxes[0];
                    var isNonEditableCell = getRaw(singleCell) === "false";
                    var isCellClosestContentEditable = is(closest(event.target), singleCell, eq$1);
                    if (isNonEditableCell && isCellClosestContentEditable) {
                      annotations.selectRange(container, boxes, singleCell, singleCell);
                      bridge.selectContents(singleCell);
                    }
                  } else if (boxes.length > 1) {
                    annotations.selectRange(container, boxes, cellSel.start, cellSel.finish);
                    bridge.selectContents(finish);
                  }
                });
              });
            });
          };
          var mousedown = function(event) {
            annotations.clear(container);
            findCell(event.target, isRoot).each(cursor.set);
          };
          var mouseover = function(event) {
            applySelection(event);
          };
          var mouseup = function(event) {
            applySelection(event);
            clearstate();
          };
          return {
            clearstate,
            mousedown,
            mouseover,
            mouseup
          };
        };
        var down = {
          traverse: nextSibling,
          gather: after,
          relative: Situ.before,
          otherRetry: Retries.tryDown,
          ieRetry: Retries.ieTryDown,
          failure: BeforeAfter.failedDown
        };
        var up = {
          traverse: prevSibling,
          gather: before,
          relative: Situ.before,
          otherRetry: Retries.tryUp,
          ieRetry: Retries.ieTryUp,
          failure: BeforeAfter.failedUp
        };
        var isKey = function(key2) {
          return function(keycode) {
            return keycode === key2;
          };
        };
        var isUp = isKey(38);
        var isDown = isKey(40);
        var isNavigation = function(keycode) {
          return keycode >= 37 && keycode <= 40;
        };
        var ltr = {
          isBackward: isKey(37),
          isForward: isKey(39)
        };
        var rtl = {
          isBackward: isKey(39),
          isForward: isKey(37)
        };
        var get = function(_DOC) {
          var doc = _DOC !== void 0 ? _DOC.dom : document;
          var x2 = doc.body.scrollLeft || doc.documentElement.scrollLeft;
          var y2 = doc.body.scrollTop || doc.documentElement.scrollTop;
          return SugarPosition(x2, y2);
        };
        var by = function(x2, y2, _DOC) {
          var doc = _DOC !== void 0 ? _DOC.dom : document;
          var win = doc.defaultView;
          if (win) {
            win.scrollBy(x2, y2);
          }
        };
        var WindowBridge = function(win) {
          var elementFromPoint = function(x2, y2) {
            return SugarElement.fromPoint(SugarElement.fromDom(win.document), x2, y2);
          };
          var getRect = function(element) {
            return element.dom.getBoundingClientRect();
          };
          var getRangedRect = function(start4, soffset, finish, foffset) {
            var sel = SimSelection.exact(start4, soffset, finish, foffset);
            return getFirstRect(win, sel);
          };
          var getSelection = function() {
            return get$1(win).map(function(exactAdt) {
              return convertToRange(win, exactAdt);
            });
          };
          var fromSitus = function(situs) {
            var relative2 = SimSelection.relative(situs.start, situs.finish);
            return convertToRange(win, relative2);
          };
          var situsFromPoint = function(x2, y2) {
            return getAtPoint(win, x2, y2).map(function(exact2) {
              return Situs.create(exact2.start, exact2.soffset, exact2.finish, exact2.foffset);
            });
          };
          var clearSelection = function() {
            clear(win);
          };
          var collapseSelection = function(toStart) {
            if (toStart === void 0) {
              toStart = false;
            }
            get$1(win).each(function(sel) {
              return sel.fold(function(rng) {
                return rng.collapse(toStart);
              }, function(startSitu, finishSitu) {
                var situ = toStart ? startSitu : finishSitu;
                setRelative(win, situ, situ);
              }, function(start4, soffset, finish, foffset) {
                var node = toStart ? start4 : finish;
                var offset2 = toStart ? soffset : foffset;
                setExact(win, node, offset2, node, offset2);
              });
            });
          };
          var selectNode2 = function(element) {
            setToElement(win, element, false);
          };
          var selectContents = function(element) {
            setToElement(win, element);
          };
          var setSelection = function(sel) {
            setExact(win, sel.start, sel.soffset, sel.finish, sel.foffset);
          };
          var setRelativeSelection = function(start4, finish) {
            setRelative(win, start4, finish);
          };
          var getInnerHeight = function() {
            return win.innerHeight;
          };
          var getScrollY = function() {
            var pos = get(SugarElement.fromDom(win.document));
            return pos.top;
          };
          var scrollBy = function(x2, y2) {
            by(x2, y2, SugarElement.fromDom(win.document));
          };
          return {
            elementFromPoint,
            getRect,
            getRangedRect,
            getSelection,
            fromSitus,
            situsFromPoint,
            clearSelection,
            collapseSelection,
            setSelection,
            setRelativeSelection,
            selectNode: selectNode2,
            selectContents,
            getInnerHeight,
            getScrollY,
            scrollBy
          };
        };
        var rc = function(rows2, cols) {
          return {
            rows: rows2,
            cols
          };
        };
        var mouse = function(win, container, isRoot, annotations) {
          var bridge = WindowBridge(win);
          var handlers = MouseSelection(bridge, container, isRoot, annotations);
          return {
            clearstate: handlers.clearstate,
            mousedown: handlers.mousedown,
            mouseover: handlers.mouseover,
            mouseup: handlers.mouseup
          };
        };
        var keyboard = function(win, container, isRoot, annotations) {
          var bridge = WindowBridge(win);
          var clearToNavigate = function() {
            annotations.clear(container);
            return Optional.none();
          };
          var keydown = function(event, start4, soffset, finish, foffset, direction) {
            var realEvent = event.raw;
            var keycode = realEvent.which;
            var shiftKey = realEvent.shiftKey === true;
            var handler = retrieve$1(container, annotations.selectedSelector).fold(function() {
              if (isNavigation(keycode) && !shiftKey) {
                annotations.clearBeforeUpdate(container);
              }
              if (isDown(keycode) && shiftKey) {
                return curry(select, bridge, container, isRoot, down, finish, start4, annotations.selectRange);
              } else if (isUp(keycode) && shiftKey) {
                return curry(select, bridge, container, isRoot, up, finish, start4, annotations.selectRange);
              } else if (isDown(keycode)) {
                return curry(navigate, bridge, isRoot, down, finish, start4, lastDownCheck);
              } else if (isUp(keycode)) {
                return curry(navigate, bridge, isRoot, up, finish, start4, firstUpCheck);
              } else {
                return Optional.none;
              }
            }, function(selected) {
              var update$1 = function(attempts) {
                return function() {
                  var navigation = findMap(attempts, function(delta) {
                    return update(delta.rows, delta.cols, container, selected, annotations);
                  });
                  return navigation.fold(function() {
                    return getEdges(container, annotations.firstSelectedSelector, annotations.lastSelectedSelector).map(function(edges) {
                      var relative2 = isDown(keycode) || direction.isForward(keycode) ? Situ.after : Situ.before;
                      bridge.setRelativeSelection(Situ.on(edges.first, 0), relative2(edges.table));
                      annotations.clear(container);
                      return Response2.create(Optional.none(), true);
                    });
                  }, function(_2) {
                    return Optional.some(Response2.create(Optional.none(), true));
                  });
                };
              };
              if (isDown(keycode) && shiftKey) {
                return update$1([rc(1, 0)]);
              } else if (isUp(keycode) && shiftKey) {
                return update$1([rc(-1, 0)]);
              } else if (direction.isBackward(keycode) && shiftKey) {
                return update$1([
                  rc(0, -1),
                  rc(-1, 0)
                ]);
              } else if (direction.isForward(keycode) && shiftKey) {
                return update$1([
                  rc(0, 1),
                  rc(1, 0)
                ]);
              } else if (isNavigation(keycode) && !shiftKey) {
                return clearToNavigate;
              } else {
                return Optional.none;
              }
            });
            return handler();
          };
          var keyup = function(event, start4, soffset, finish, foffset) {
            return retrieve$1(container, annotations.selectedSelector).fold(function() {
              var realEvent = event.raw;
              var keycode = realEvent.which;
              var shiftKey = realEvent.shiftKey === true;
              if (!shiftKey) {
                return Optional.none();
              }
              if (isNavigation(keycode)) {
                return sync(container, isRoot, start4, soffset, finish, foffset, annotations.selectRange);
              } else {
                return Optional.none();
              }
            }, Optional.none);
          };
          return {
            keydown,
            keyup
          };
        };
        var external = function(win, container, isRoot, annotations) {
          var bridge = WindowBridge(win);
          return function(start4, finish) {
            annotations.clearBeforeUpdate(container);
            identify(start4, finish, isRoot).each(function(cellSel) {
              var boxes = cellSel.boxes.getOr([]);
              annotations.selectRange(container, boxes, cellSel.start, cellSel.finish);
              bridge.selectContents(finish);
              bridge.collapseSelection();
            });
          };
        };
        var remove = function(element, classes) {
          each$2(classes, function(x2) {
            remove$2(element, x2);
          });
        };
        var addClass = function(clazz) {
          return function(element) {
            add3(element, clazz);
          };
        };
        var removeClasses = function(classes) {
          return function(element) {
            remove(element, classes);
          };
        };
        var byClass = function(ephemera2) {
          var addSelectionClass = addClass(ephemera2.selected);
          var removeSelectionClasses = removeClasses([
            ephemera2.selected,
            ephemera2.lastSelected,
            ephemera2.firstSelected
          ]);
          var clear2 = function(container) {
            var sels = descendants(container, ephemera2.selectedSelector);
            each$2(sels, removeSelectionClasses);
          };
          var selectRange = function(container, cells2, start4, finish) {
            clear2(container);
            each$2(cells2, addSelectionClass);
            add3(start4, ephemera2.firstSelected);
            add3(finish, ephemera2.lastSelected);
          };
          return {
            clearBeforeUpdate: clear2,
            clear: clear2,
            selectRange,
            selectedSelector: ephemera2.selectedSelector,
            firstSelectedSelector: ephemera2.firstSelectedSelector,
            lastSelectedSelector: ephemera2.lastSelectedSelector
          };
        };
        var byAttr = function(ephemera2, onSelection, onClear) {
          var removeSelectionAttributes = function(element) {
            remove$7(element, ephemera2.selected);
            remove$7(element, ephemera2.firstSelected);
            remove$7(element, ephemera2.lastSelected);
          };
          var addSelectionAttribute = function(element) {
            set$2(element, ephemera2.selected, "1");
          };
          var clear2 = function(container) {
            clearBeforeUpdate(container);
            onClear();
          };
          var clearBeforeUpdate = function(container) {
            var sels = descendants(container, ephemera2.selectedSelector + "," + ephemera2.firstSelectedSelector + "," + ephemera2.lastSelectedSelector);
            each$2(sels, removeSelectionAttributes);
          };
          var selectRange = function(container, cells2, start4, finish) {
            clear2(container);
            each$2(cells2, addSelectionAttribute);
            set$2(start4, ephemera2.firstSelected, "1");
            set$2(finish, ephemera2.lastSelected, "1");
            onSelection(cells2, start4, finish);
          };
          return {
            clearBeforeUpdate,
            clear: clear2,
            selectRange,
            selectedSelector: ephemera2.selectedSelector,
            firstSelectedSelector: ephemera2.firstSelectedSelector,
            lastSelectedSelector: ephemera2.lastSelectedSelector
          };
        };
        var SelectionAnnotation = {
          byClass,
          byAttr
        };
        var getUpOrLeftCells = function(grid2, selectedCells) {
          var upGrid = grid2.slice(0, selectedCells[selectedCells.length - 1].row + 1);
          var upDetails = toDetailList(upGrid);
          return bind$2(upDetails, function(detail2) {
            var slicedCells = detail2.cells.slice(0, selectedCells[selectedCells.length - 1].column + 1);
            return map$12(slicedCells, function(cell2) {
              return cell2.element;
            });
          });
        };
        var getDownOrRightCells = function(grid2, selectedCells) {
          var downGrid = grid2.slice(selectedCells[0].row + selectedCells[0].rowspan - 1, grid2.length);
          var downDetails = toDetailList(downGrid);
          return bind$2(downDetails, function(detail2) {
            var slicedCells = detail2.cells.slice(selectedCells[0].column + selectedCells[0].colspan - 1, detail2.cells.length);
            return map$12(slicedCells, function(cell2) {
              return cell2.element;
            });
          });
        };
        var getOtherCells = function(table2, target, generators) {
          var warehouse = Warehouse.fromTable(table2);
          var details = onCells(warehouse, target);
          return details.map(function(selectedCells) {
            var grid2 = toGrid(warehouse, generators, false);
            var upOrLeftCells = getUpOrLeftCells(grid2, selectedCells);
            var downOrRightCells = getDownOrRightCells(grid2, selectedCells);
            return {
              upOrLeftCells,
              downOrRightCells
            };
          });
        };
        var global2 = tinymce.util.Tools.resolve("tinymce.Env");
        var hasInternalTarget = function(e2) {
          return has(SugarElement.fromDom(e2.target), "ephox-snooker-resizer-bar") === false;
        };
        function CellSelection(editor, lazyResize, selectionTargets) {
          var onSelection = function(cells2, start4, finish) {
            selectionTargets.targets().each(function(targets) {
              var tableOpt = table(start4);
              tableOpt.each(function(table2) {
                var cloneFormats2 = getCloneElements(editor);
                var generators = cellOperations(noop3, SugarElement.fromDom(editor.getDoc()), cloneFormats2);
                var otherCells = getOtherCells(table2, targets, generators);
                fireTableSelectionChange(editor, cells2, start4, finish, otherCells);
              });
            });
          };
          var onClear = function() {
            return fireTableSelectionClear(editor);
          };
          var annotations = SelectionAnnotation.byAttr(ephemera, onSelection, onClear);
          editor.on("init", function(_e2) {
            var win = editor.getWin();
            var body2 = getBody(editor);
            var isRoot = getIsRoot(editor);
            var syncSelection = function() {
              var sel = editor.selection;
              var start4 = SugarElement.fromDom(sel.getStart());
              var end2 = SugarElement.fromDom(sel.getEnd());
              var shared = sharedOne(table, [
                start4,
                end2
              ]);
              shared.fold(function() {
                return annotations.clear(body2);
              }, noop3);
            };
            var mouseHandlers = mouse(win, body2, isRoot, annotations);
            var keyHandlers = keyboard(win, body2, isRoot, annotations);
            var external$1 = external(win, body2, isRoot, annotations);
            var hasShiftKey = function(event) {
              return event.raw.shiftKey === true;
            };
            editor.on("TableSelectorChange", function(e2) {
              return external$1(e2.start, e2.finish);
            });
            var handleResponse = function(event, response) {
              if (!hasShiftKey(event)) {
                return;
              }
              if (response.kill) {
                event.kill();
              }
              response.selection.each(function(ns) {
                var relative2 = SimSelection.relative(ns.start, ns.finish);
                var rng = asLtrRange(win, relative2);
                editor.selection.setRng(rng);
              });
            };
            var keyup = function(event) {
              var wrappedEvent = fromRawEvent(event);
              if (wrappedEvent.raw.shiftKey && isNavigation(wrappedEvent.raw.which)) {
                var rng = editor.selection.getRng();
                var start4 = SugarElement.fromDom(rng.startContainer);
                var end2 = SugarElement.fromDom(rng.endContainer);
                keyHandlers.keyup(wrappedEvent, start4, rng.startOffset, end2, rng.endOffset).each(function(response) {
                  handleResponse(wrappedEvent, response);
                });
              }
            };
            var keydown = function(event) {
              var wrappedEvent = fromRawEvent(event);
              lazyResize().each(function(resize2) {
                return resize2.hideBars();
              });
              var rng = editor.selection.getRng();
              var start4 = SugarElement.fromDom(rng.startContainer);
              var end2 = SugarElement.fromDom(rng.endContainer);
              var direction = onDirection(ltr, rtl)(SugarElement.fromDom(editor.selection.getStart()));
              keyHandlers.keydown(wrappedEvent, start4, rng.startOffset, end2, rng.endOffset, direction).each(function(response) {
                handleResponse(wrappedEvent, response);
              });
              lazyResize().each(function(resize2) {
                return resize2.showBars();
              });
            };
            var isLeftMouse = function(raw) {
              return raw.button === 0;
            };
            var isLeftButtonPressed = function(raw) {
              if (raw.buttons === void 0) {
                return true;
              }
              if (global2.browser.isEdge() && raw.buttons === 0) {
                return true;
              }
              return (raw.buttons & 1) !== 0;
            };
            var dragStart = function(_e3) {
              mouseHandlers.clearstate();
            };
            var mouseDown = function(e2) {
              if (isLeftMouse(e2) && hasInternalTarget(e2)) {
                mouseHandlers.mousedown(fromRawEvent(e2));
              }
            };
            var mouseOver = function(e2) {
              if (isLeftButtonPressed(e2) && hasInternalTarget(e2)) {
                mouseHandlers.mouseover(fromRawEvent(e2));
              }
            };
            var mouseUp = function(e2) {
              if (isLeftMouse(e2) && hasInternalTarget(e2)) {
                mouseHandlers.mouseup(fromRawEvent(e2));
              }
            };
            var getDoubleTap = function() {
              var lastTarget = Cell(SugarElement.fromDom(body2));
              var lastTimeStamp = Cell(0);
              var touchEnd = function(t2) {
                var target = SugarElement.fromDom(t2.target);
                if (name(target) === "td" || name(target) === "th") {
                  var lT = lastTarget.get();
                  var lTS = lastTimeStamp.get();
                  if (eq$1(lT, target) && t2.timeStamp - lTS < 300) {
                    t2.preventDefault();
                    external$1(target, target);
                  }
                }
                lastTarget.set(target);
                lastTimeStamp.set(t2.timeStamp);
              };
              return { touchEnd };
            };
            var doubleTap = getDoubleTap();
            editor.on("dragstart", dragStart);
            editor.on("mousedown", mouseDown);
            editor.on("mouseover", mouseOver);
            editor.on("mouseup", mouseUp);
            editor.on("touchend", doubleTap.touchEnd);
            editor.on("keyup", keyup);
            editor.on("keydown", keydown);
            editor.on("NodeChange", syncSelection);
          });
          return { clear: annotations.clear };
        }
        var child = function(scope, selector) {
          return child$1(scope, selector).isSome();
        };
        var getSelectionTargets = function(editor, selections) {
          var targets = Cell(Optional.none());
          var changeHandlers = Cell([]);
          var selectionDetails = Optional.none();
          var isCaption = isTag("caption");
          var isDisabledForSelection = function(key2) {
            return selectionDetails.forall(function(details) {
              return !details[key2];
            });
          };
          var getStart2 = function() {
            return getSelectionCellOrCaption(getSelectionStart(editor), getIsRoot(editor));
          };
          var getEnd2 = function() {
            return getSelectionCellOrCaption(getSelectionEnd(editor), getIsRoot(editor));
          };
          var findTargets = function() {
            return getStart2().bind(function(startCellOrCaption) {
              return flatten(lift2(table(startCellOrCaption), getEnd2().bind(table), function(startTable, endTable) {
                if (eq$1(startTable, endTable)) {
                  if (isCaption(startCellOrCaption)) {
                    return Optional.some(noMenu(startCellOrCaption));
                  } else {
                    return Optional.some(forMenu(selections, startTable, startCellOrCaption));
                  }
                }
                return Optional.none();
              }));
            });
          };
          var getExtractedDetails = function(targets2) {
            var tableOpt = table(targets2.element);
            return tableOpt.map(function(table2) {
              var warehouse = Warehouse.fromTable(table2);
              var selectedCells = onCells(warehouse, targets2).getOr([]);
              var locked = foldl(selectedCells, function(acc, cell2) {
                if (cell2.isLocked) {
                  acc.onAny = true;
                  if (cell2.column === 0) {
                    acc.onFirst = true;
                  } else if (cell2.column + cell2.colspan >= warehouse.grid.columns) {
                    acc.onLast = true;
                  }
                }
                return acc;
              }, {
                onAny: false,
                onFirst: false,
                onLast: false
              });
              return {
                mergeable: onUnlockedMergable(warehouse, targets2).isSome(),
                unmergeable: onUnlockedUnmergable(warehouse, targets2).isSome(),
                locked
              };
            });
          };
          var resetTargets = function() {
            targets.set(cached(findTargets)());
            selectionDetails = targets.get().bind(getExtractedDetails);
            each$2(changeHandlers.get(), function(handler) {
              return handler();
            });
          };
          var setupHandler = function(handler) {
            handler();
            changeHandlers.set(changeHandlers.get().concat([handler]));
            return function() {
              changeHandlers.set(filter$2(changeHandlers.get(), function(h3) {
                return h3 !== handler;
              }));
            };
          };
          var onSetup = function(api2, isDisabled2) {
            return setupHandler(function() {
              return targets.get().fold(function() {
                api2.setDisabled(true);
              }, function(targets2) {
                api2.setDisabled(isDisabled2(targets2));
              });
            });
          };
          var onSetupWithToggle = function(api2, isDisabled2, isActive) {
            return setupHandler(function() {
              return targets.get().fold(function() {
                api2.setDisabled(true);
                api2.setActive(false);
              }, function(targets2) {
                api2.setDisabled(isDisabled2(targets2));
                api2.setActive(isActive(targets2));
              });
            });
          };
          var isDisabledFromLocked = function(lockedDisable) {
            return selectionDetails.exists(function(details) {
              return details.locked[lockedDisable];
            });
          };
          var onSetupTable = function(api2) {
            return onSetup(api2, function(_2) {
              return false;
            });
          };
          var onSetupCellOrRow = function(api2) {
            return onSetup(api2, function(targets2) {
              return isCaption(targets2.element);
            });
          };
          var onSetupColumn = function(lockedDisable) {
            return function(api2) {
              return onSetup(api2, function(targets2) {
                return isCaption(targets2.element) || isDisabledFromLocked(lockedDisable);
              });
            };
          };
          var onSetupPasteable = function(getClipboardData) {
            return function(api2) {
              return onSetup(api2, function(targets2) {
                return isCaption(targets2.element) || getClipboardData().isNone();
              });
            };
          };
          var onSetupPasteableColumn = function(getClipboardData, lockedDisable) {
            return function(api2) {
              return onSetup(api2, function(targets2) {
                return isCaption(targets2.element) || getClipboardData().isNone() || isDisabledFromLocked(lockedDisable);
              });
            };
          };
          var onSetupMergeable = function(api2) {
            return onSetup(api2, function(_targets) {
              return isDisabledForSelection("mergeable");
            });
          };
          var onSetupUnmergeable = function(api2) {
            return onSetup(api2, function(_targets) {
              return isDisabledForSelection("unmergeable");
            });
          };
          var onSetupTableWithCaption = function(api2) {
            return onSetupWithToggle(api2, never, function(targets2) {
              var tableOpt = table(targets2.element, getIsRoot(editor));
              return tableOpt.exists(function(table2) {
                return child(table2, "caption");
              });
            });
          };
          var onSetupTableHeaders = function(command, headerType) {
            return function(api2) {
              return onSetupWithToggle(api2, function(targets2) {
                return isCaption(targets2.element);
              }, function() {
                return editor.queryCommandValue(command) === headerType;
              });
            };
          };
          var onSetupTableRowHeaders = onSetupTableHeaders("mceTableRowType", "header");
          var onSetupTableColumnHeaders = onSetupTableHeaders("mceTableColType", "th");
          editor.on("NodeChange ExecCommand TableSelectorChange", resetTargets);
          return {
            onSetupTable,
            onSetupCellOrRow,
            onSetupColumn,
            onSetupPasteable,
            onSetupPasteableColumn,
            onSetupMergeable,
            onSetupUnmergeable,
            resetTargets,
            onSetupTableWithCaption,
            onSetupTableRowHeaders,
            onSetupTableColumnHeaders,
            targets: targets.get
          };
        };
        var addButtons = function(editor, selections, selectionTargets, clipboard) {
          editor.ui.registry.addMenuButton("table", {
            tooltip: "Table",
            icon: "table",
            fetch: function(callback2) {
              return callback2("inserttable | cell row column | advtablesort | tableprops deletetable");
            }
          });
          var cmd = function(command) {
            return function() {
              return editor.execCommand(command);
            };
          };
          editor.ui.registry.addButton("tableprops", {
            tooltip: "Table properties",
            onAction: cmd("mceTableProps"),
            icon: "table",
            onSetup: selectionTargets.onSetupTable
          });
          editor.ui.registry.addButton("tabledelete", {
            tooltip: "Delete table",
            onAction: cmd("mceTableDelete"),
            icon: "table-delete-table",
            onSetup: selectionTargets.onSetupTable
          });
          editor.ui.registry.addButton("tablecellprops", {
            tooltip: "Cell properties",
            onAction: cmd("mceTableCellProps"),
            icon: "table-cell-properties",
            onSetup: selectionTargets.onSetupCellOrRow
          });
          editor.ui.registry.addButton("tablemergecells", {
            tooltip: "Merge cells",
            onAction: cmd("mceTableMergeCells"),
            icon: "table-merge-cells",
            onSetup: selectionTargets.onSetupMergeable
          });
          editor.ui.registry.addButton("tablesplitcells", {
            tooltip: "Split cell",
            onAction: cmd("mceTableSplitCells"),
            icon: "table-split-cells",
            onSetup: selectionTargets.onSetupUnmergeable
          });
          editor.ui.registry.addButton("tableinsertrowbefore", {
            tooltip: "Insert row before",
            onAction: cmd("mceTableInsertRowBefore"),
            icon: "table-insert-row-above",
            onSetup: selectionTargets.onSetupCellOrRow
          });
          editor.ui.registry.addButton("tableinsertrowafter", {
            tooltip: "Insert row after",
            onAction: cmd("mceTableInsertRowAfter"),
            icon: "table-insert-row-after",
            onSetup: selectionTargets.onSetupCellOrRow
          });
          editor.ui.registry.addButton("tabledeleterow", {
            tooltip: "Delete row",
            onAction: cmd("mceTableDeleteRow"),
            icon: "table-delete-row",
            onSetup: selectionTargets.onSetupCellOrRow
          });
          editor.ui.registry.addButton("tablerowprops", {
            tooltip: "Row properties",
            onAction: cmd("mceTableRowProps"),
            icon: "table-row-properties",
            onSetup: selectionTargets.onSetupCellOrRow
          });
          editor.ui.registry.addButton("tableinsertcolbefore", {
            tooltip: "Insert column before",
            onAction: cmd("mceTableInsertColBefore"),
            icon: "table-insert-column-before",
            onSetup: selectionTargets.onSetupColumn("onFirst")
          });
          editor.ui.registry.addButton("tableinsertcolafter", {
            tooltip: "Insert column after",
            onAction: cmd("mceTableInsertColAfter"),
            icon: "table-insert-column-after",
            onSetup: selectionTargets.onSetupColumn("onLast")
          });
          editor.ui.registry.addButton("tabledeletecol", {
            tooltip: "Delete column",
            onAction: cmd("mceTableDeleteCol"),
            icon: "table-delete-column",
            onSetup: selectionTargets.onSetupColumn("onAny")
          });
          editor.ui.registry.addButton("tablecutrow", {
            tooltip: "Cut row",
            icon: "cut-row",
            onAction: cmd("mceTableCutRow"),
            onSetup: selectionTargets.onSetupCellOrRow
          });
          editor.ui.registry.addButton("tablecopyrow", {
            tooltip: "Copy row",
            icon: "duplicate-row",
            onAction: cmd("mceTableCopyRow"),
            onSetup: selectionTargets.onSetupCellOrRow
          });
          editor.ui.registry.addButton("tablepasterowbefore", {
            tooltip: "Paste row before",
            icon: "paste-row-before",
            onAction: cmd("mceTablePasteRowBefore"),
            onSetup: selectionTargets.onSetupPasteable(clipboard.getRows)
          });
          editor.ui.registry.addButton("tablepasterowafter", {
            tooltip: "Paste row after",
            icon: "paste-row-after",
            onAction: cmd("mceTablePasteRowAfter"),
            onSetup: selectionTargets.onSetupPasteable(clipboard.getRows)
          });
          editor.ui.registry.addButton("tablecutcol", {
            tooltip: "Cut column",
            icon: "cut-column",
            onAction: cmd("mceTableCutCol"),
            onSetup: selectionTargets.onSetupColumn("onAny")
          });
          editor.ui.registry.addButton("tablecopycol", {
            tooltip: "Copy column",
            icon: "duplicate-column",
            onAction: cmd("mceTableCopyCol"),
            onSetup: selectionTargets.onSetupColumn("onAny")
          });
          editor.ui.registry.addButton("tablepastecolbefore", {
            tooltip: "Paste column before",
            icon: "paste-column-before",
            onAction: cmd("mceTablePasteColBefore"),
            onSetup: selectionTargets.onSetupPasteableColumn(clipboard.getColumns, "onFirst")
          });
          editor.ui.registry.addButton("tablepastecolafter", {
            tooltip: "Paste column after",
            icon: "paste-column-after",
            onAction: cmd("mceTablePasteColAfter"),
            onSetup: selectionTargets.onSetupPasteableColumn(clipboard.getColumns, "onLast")
          });
          editor.ui.registry.addButton("tableinsertdialog", {
            tooltip: "Insert table",
            onAction: cmd("mceInsertTable"),
            icon: "table"
          });
          var tableClassList = filterNoneItem(getTableClassList(editor));
          if (tableClassList.length !== 0) {
            editor.ui.registry.addMenuButton("tableclass", {
              icon: "table-classes",
              tooltip: "Table styles",
              fetch: generateMenuItemsCallback(editor, selections, tableClassList, "tableclass", function(value2) {
                return editor.execCommand("mceTableToggleClass", false, value2);
              }),
              onSetup: selectionTargets.onSetupTable
            });
          }
          var tableCellClassList = filterNoneItem(getCellClassList(editor));
          if (tableCellClassList.length !== 0) {
            editor.ui.registry.addMenuButton("tablecellclass", {
              icon: "table-cell-classes",
              tooltip: "Cell styles",
              fetch: generateMenuItemsCallback(editor, selections, tableCellClassList, "tablecellclass", function(value2) {
                return editor.execCommand("mceTableCellToggleClass", false, value2);
              }),
              onSetup: selectionTargets.onSetupCellOrRow
            });
          }
          editor.ui.registry.addMenuButton("tablecellvalign", {
            icon: "vertical-align",
            tooltip: "Vertical align",
            fetch: generateMenuItemsCallback(editor, selections, verticalAlignValues, "tablecellverticalalign", applyTableCellStyle(editor, "vertical-align")),
            onSetup: selectionTargets.onSetupCellOrRow
          });
          editor.ui.registry.addMenuButton("tablecellborderwidth", {
            icon: "border-width",
            tooltip: "Border width",
            fetch: generateMenuItemsCallback(editor, selections, getTableBorderWidths(editor), "tablecellborderwidth", applyTableCellStyle(editor, "border-width")),
            onSetup: selectionTargets.onSetupCellOrRow
          });
          editor.ui.registry.addMenuButton("tablecellborderstyle", {
            icon: "border-style",
            tooltip: "Border style",
            fetch: generateMenuItemsCallback(editor, selections, getTableBorderStyles(editor), "tablecellborderstyle", applyTableCellStyle(editor, "border-style")),
            onSetup: selectionTargets.onSetupCellOrRow
          });
          editor.ui.registry.addToggleButton("tablecaption", {
            tooltip: "Table caption",
            onAction: cmd("mceTableToggleCaption"),
            icon: "table-caption",
            onSetup: selectionTargets.onSetupTableWithCaption
          });
          editor.ui.registry.addMenuButton("tablecellbackgroundcolor", {
            icon: "cell-background-color",
            tooltip: "Background color",
            fetch: function(callback2) {
              return callback2(buildColorMenu(editor, getTableBackgroundColorMap(editor), "background-color"));
            },
            onSetup: selectionTargets.onSetupCellOrRow
          });
          editor.ui.registry.addMenuButton("tablecellbordercolor", {
            icon: "cell-border-color",
            tooltip: "Border color",
            fetch: function(callback2) {
              return callback2(buildColorMenu(editor, getTableBorderColorMap(editor), "border-color"));
            },
            onSetup: selectionTargets.onSetupCellOrRow
          });
          editor.ui.registry.addToggleButton("tablerowheader", {
            tooltip: "Row header",
            icon: "table-top-header",
            onAction: changeRowHeader(editor),
            onSetup: selectionTargets.onSetupTableRowHeaders
          });
          editor.ui.registry.addToggleButton("tablecolheader", {
            tooltip: "Column header",
            icon: "table-left-header",
            onAction: changeColumnHeader(editor),
            onSetup: selectionTargets.onSetupTableColumnHeaders
          });
        };
        var addToolbars = function(editor) {
          var isTable = function(table2) {
            return editor.dom.is(table2, "table") && editor.getBody().contains(table2);
          };
          var toolbar = getToolbar(editor);
          if (toolbar.length > 0) {
            editor.ui.registry.addContextToolbar("table", {
              predicate: isTable,
              items: toolbar,
              scope: "node",
              position: "node"
            });
          }
        };
        var addMenuItems = function(editor, selections, selectionTargets, clipboard) {
          var cmd = function(command) {
            return function() {
              return editor.execCommand(command);
            };
          };
          var insertTableAction = function(data) {
            editor.execCommand("mceInsertTable", false, {
              rows: data.numRows,
              columns: data.numColumns
            });
          };
          var tableProperties = {
            text: "Table properties",
            onSetup: selectionTargets.onSetupTable,
            onAction: cmd("mceTableProps")
          };
          var deleteTable = {
            text: "Delete table",
            icon: "table-delete-table",
            onSetup: selectionTargets.onSetupTable,
            onAction: cmd("mceTableDelete")
          };
          editor.ui.registry.addMenuItem("tableinsertrowbefore", {
            text: "Insert row before",
            icon: "table-insert-row-above",
            onAction: cmd("mceTableInsertRowBefore"),
            onSetup: selectionTargets.onSetupCellOrRow
          });
          editor.ui.registry.addMenuItem("tableinsertrowafter", {
            text: "Insert row after",
            icon: "table-insert-row-after",
            onAction: cmd("mceTableInsertRowAfter"),
            onSetup: selectionTargets.onSetupCellOrRow
          });
          editor.ui.registry.addMenuItem("tabledeleterow", {
            text: "Delete row",
            icon: "table-delete-row",
            onAction: cmd("mceTableDeleteRow"),
            onSetup: selectionTargets.onSetupCellOrRow
          });
          editor.ui.registry.addMenuItem("tablerowprops", {
            text: "Row properties",
            icon: "table-row-properties",
            onAction: cmd("mceTableRowProps"),
            onSetup: selectionTargets.onSetupCellOrRow
          });
          editor.ui.registry.addMenuItem("tablecutrow", {
            text: "Cut row",
            icon: "cut-row",
            onAction: cmd("mceTableCutRow"),
            onSetup: selectionTargets.onSetupCellOrRow
          });
          editor.ui.registry.addMenuItem("tablecopyrow", {
            text: "Copy row",
            icon: "duplicate-row",
            onAction: cmd("mceTableCopyRow"),
            onSetup: selectionTargets.onSetupCellOrRow
          });
          editor.ui.registry.addMenuItem("tablepasterowbefore", {
            text: "Paste row before",
            icon: "paste-row-before",
            onAction: cmd("mceTablePasteRowBefore"),
            onSetup: selectionTargets.onSetupPasteable(clipboard.getRows)
          });
          editor.ui.registry.addMenuItem("tablepasterowafter", {
            text: "Paste row after",
            icon: "paste-row-after",
            onAction: cmd("mceTablePasteRowAfter"),
            onSetup: selectionTargets.onSetupPasteable(clipboard.getRows)
          });
          var row2 = {
            type: "nestedmenuitem",
            text: "Row",
            getSubmenuItems: constant("tableinsertrowbefore tableinsertrowafter tabledeleterow tablerowprops | tablecutrow tablecopyrow tablepasterowbefore tablepasterowafter")
          };
          editor.ui.registry.addMenuItem("tableinsertcolumnbefore", {
            text: "Insert column before",
            icon: "table-insert-column-before",
            onAction: cmd("mceTableInsertColBefore"),
            onSetup: selectionTargets.onSetupColumn("onFirst")
          });
          editor.ui.registry.addMenuItem("tableinsertcolumnafter", {
            text: "Insert column after",
            icon: "table-insert-column-after",
            onAction: cmd("mceTableInsertColAfter"),
            onSetup: selectionTargets.onSetupColumn("onLast")
          });
          editor.ui.registry.addMenuItem("tabledeletecolumn", {
            text: "Delete column",
            icon: "table-delete-column",
            onAction: cmd("mceTableDeleteCol"),
            onSetup: selectionTargets.onSetupColumn("onAny")
          });
          editor.ui.registry.addMenuItem("tablecutcolumn", {
            text: "Cut column",
            icon: "cut-column",
            onAction: cmd("mceTableCutCol"),
            onSetup: selectionTargets.onSetupColumn("onAny")
          });
          editor.ui.registry.addMenuItem("tablecopycolumn", {
            text: "Copy column",
            icon: "duplicate-column",
            onAction: cmd("mceTableCopyCol"),
            onSetup: selectionTargets.onSetupColumn("onAny")
          });
          editor.ui.registry.addMenuItem("tablepastecolumnbefore", {
            text: "Paste column before",
            icon: "paste-column-before",
            onAction: cmd("mceTablePasteColBefore"),
            onSetup: selectionTargets.onSetupPasteableColumn(clipboard.getColumns, "onFirst")
          });
          editor.ui.registry.addMenuItem("tablepastecolumnafter", {
            text: "Paste column after",
            icon: "paste-column-after",
            onAction: cmd("mceTablePasteColAfter"),
            onSetup: selectionTargets.onSetupPasteableColumn(clipboard.getColumns, "onLast")
          });
          var column = {
            type: "nestedmenuitem",
            text: "Column",
            getSubmenuItems: constant("tableinsertcolumnbefore tableinsertcolumnafter tabledeletecolumn | tablecutcolumn tablecopycolumn tablepastecolumnbefore tablepastecolumnafter")
          };
          editor.ui.registry.addMenuItem("tablecellprops", {
            text: "Cell properties",
            icon: "table-cell-properties",
            onAction: cmd("mceTableCellProps"),
            onSetup: selectionTargets.onSetupCellOrRow
          });
          editor.ui.registry.addMenuItem("tablemergecells", {
            text: "Merge cells",
            icon: "table-merge-cells",
            onAction: cmd("mceTableMergeCells"),
            onSetup: selectionTargets.onSetupMergeable
          });
          editor.ui.registry.addMenuItem("tablesplitcells", {
            text: "Split cell",
            icon: "table-split-cells",
            onAction: cmd("mceTableSplitCells"),
            onSetup: selectionTargets.onSetupUnmergeable
          });
          var cell2 = {
            type: "nestedmenuitem",
            text: "Cell",
            getSubmenuItems: constant("tablecellprops tablemergecells tablesplitcells")
          };
          if (hasTableGrid(editor) === false) {
            editor.ui.registry.addMenuItem("inserttable", {
              text: "Table",
              icon: "table",
              onAction: cmd("mceInsertTable")
            });
          } else {
            editor.ui.registry.addNestedMenuItem("inserttable", {
              text: "Table",
              icon: "table",
              getSubmenuItems: function() {
                return [{
                  type: "fancymenuitem",
                  fancytype: "inserttable",
                  onAction: insertTableAction
                }];
              }
            });
          }
          editor.ui.registry.addMenuItem("inserttabledialog", {
            text: "Insert table",
            icon: "table",
            onAction: cmd("mceInsertTable")
          });
          editor.ui.registry.addMenuItem("tableprops", tableProperties);
          editor.ui.registry.addMenuItem("deletetable", deleteTable);
          editor.ui.registry.addNestedMenuItem("row", row2);
          editor.ui.registry.addNestedMenuItem("column", column);
          editor.ui.registry.addNestedMenuItem("cell", cell2);
          editor.ui.registry.addContextMenu("table", {
            update: function() {
              selectionTargets.resetTargets();
              return selectionTargets.targets().fold(constant(""), function(targets) {
                if (name(targets.element) === "caption") {
                  return "tableprops deletetable";
                } else {
                  return "cell row column | advtablesort | tableprops deletetable";
                }
              });
            }
          });
          var tableClassList = filterNoneItem(getTableClassList(editor));
          if (tableClassList.length !== 0) {
            editor.ui.registry.addNestedMenuItem("tableclass", {
              icon: "table-classes",
              text: "Table styles",
              getSubmenuItems: function() {
                return buildMenuItems(editor, selections, tableClassList, "tableclass", function(value2) {
                  return editor.execCommand("mceTableToggleClass", false, value2);
                });
              },
              onSetup: selectionTargets.onSetupTable
            });
          }
          var tableCellClassList = filterNoneItem(getCellClassList(editor));
          if (tableCellClassList.length !== 0) {
            editor.ui.registry.addNestedMenuItem("tablecellclass", {
              icon: "table-cell-classes",
              text: "Cell styles",
              getSubmenuItems: function() {
                return buildMenuItems(editor, selections, tableCellClassList, "tablecellclass", function(value2) {
                  return editor.execCommand("mceTableCellToggleClass", false, value2);
                });
              },
              onSetup: selectionTargets.onSetupCellOrRow
            });
          }
          editor.ui.registry.addNestedMenuItem("tablecellvalign", {
            icon: "vertical-align",
            text: "Vertical align",
            getSubmenuItems: function() {
              return buildMenuItems(editor, selections, verticalAlignValues, "tablecellverticalalign", applyTableCellStyle(editor, "vertical-align"));
            },
            onSetup: selectionTargets.onSetupCellOrRow
          });
          editor.ui.registry.addNestedMenuItem("tablecellborderwidth", {
            icon: "border-width",
            text: "Border width",
            getSubmenuItems: function() {
              return buildMenuItems(editor, selections, getTableBorderWidths(editor), "tablecellborderwidth", applyTableCellStyle(editor, "border-width"));
            },
            onSetup: selectionTargets.onSetupCellOrRow
          });
          editor.ui.registry.addNestedMenuItem("tablecellborderstyle", {
            icon: "border-style",
            text: "Border style",
            getSubmenuItems: function() {
              return buildMenuItems(editor, selections, getTableBorderStyles(editor), "tablecellborderstyle", applyTableCellStyle(editor, "border-style"));
            },
            onSetup: selectionTargets.onSetupCellOrRow
          });
          editor.ui.registry.addToggleMenuItem("tablecaption", {
            icon: "table-caption",
            text: "Table caption",
            onAction: cmd("mceTableToggleCaption"),
            onSetup: selectionTargets.onSetupTableWithCaption
          });
          editor.ui.registry.addNestedMenuItem("tablecellbackgroundcolor", {
            icon: "cell-background-color",
            text: "Background color",
            getSubmenuItems: function() {
              return buildColorMenu(editor, getTableBackgroundColorMap(editor), "background-color");
            },
            onSetup: selectionTargets.onSetupCellOrRow
          });
          editor.ui.registry.addNestedMenuItem("tablecellbordercolor", {
            icon: "cell-border-color",
            text: "Border color",
            getSubmenuItems: function() {
              return buildColorMenu(editor, getTableBorderColorMap(editor), "border-color");
            },
            onSetup: selectionTargets.onSetupCellOrRow
          });
          editor.ui.registry.addToggleMenuItem("tablerowheader", {
            text: "Row header",
            icon: "table-top-header",
            onAction: changeRowHeader(editor),
            onSetup: selectionTargets.onSetupTableRowHeaders
          });
          editor.ui.registry.addToggleMenuItem("tablecolheader", {
            text: "Column header",
            icon: "table-left-header",
            onAction: changeColumnHeader(editor),
            onSetup: selectionTargets.onSetupTableColumnHeaders
          });
        };
        var Plugin = function(editor) {
          var selections = Selections(function() {
            return getBody(editor);
          }, function() {
            return getSelectionCell(getSelectionStart(editor), getIsRoot(editor));
          }, ephemera.selectedSelector);
          var selectionTargets = getSelectionTargets(editor, selections);
          var resizeHandler = getResizeHandler(editor);
          var cellSelection = CellSelection(editor, resizeHandler.lazyResize, selectionTargets);
          var actions = TableActions(editor, cellSelection, resizeHandler.lazyWire);
          var clipboard = Clipboard();
          registerCommands(editor, actions, cellSelection, selections, clipboard);
          registerQueryCommands(editor, actions, selections);
          registerEvents(editor, selections, actions);
          addMenuItems(editor, selections, selectionTargets, clipboard);
          addButtons(editor, selections, selectionTargets, clipboard);
          addToolbars(editor);
          editor.on("PreInit", function() {
            editor.serializer.addTempAttr(ephemera.firstSelected);
            editor.serializer.addTempAttr(ephemera.lastSelected);
            registerFormats(editor);
          });
          if (hasTabNavigation(editor)) {
            editor.on("keydown", function(e2) {
              handle$1(e2, editor, cellSelection);
            });
          }
          editor.on("remove", function() {
            resizeHandler.destroy();
          });
          return getApi(editor, clipboard, resizeHandler, selectionTargets);
        };
        function Plugin$1() {
          global$3.add("table", Plugin);
        }
        Plugin$1();
      })();
    }
  });

  // ../../node_modules/tinymce/plugins/charmap/plugin.js
  var require_plugin17 = __commonJS({
    "../../node_modules/tinymce/plugins/charmap/plugin.js"() {
      (function() {
        "use strict";
        var global$2 = tinymce.util.Tools.resolve("tinymce.PluginManager");
        var fireInsertCustomChar = function(editor, chr) {
          return editor.fire("insertCustomChar", { chr });
        };
        var insertChar = function(editor, chr) {
          var evtChr = fireInsertCustomChar(editor, chr).chr;
          editor.execCommand("mceInsertContent", false, evtChr);
        };
        var typeOf = function(x2) {
          var t2 = typeof x2;
          if (x2 === null) {
            return "null";
          } else if (t2 === "object" && (Array.prototype.isPrototypeOf(x2) || x2.constructor && x2.constructor.name === "Array")) {
            return "array";
          } else if (t2 === "object" && (String.prototype.isPrototypeOf(x2) || x2.constructor && x2.constructor.name === "String")) {
            return "string";
          } else {
            return t2;
          }
        };
        var isType = function(type) {
          return function(value) {
            return typeOf(value) === type;
          };
        };
        var eq2 = function(t2) {
          return function(a2) {
            return t2 === a2;
          };
        };
        var isArray$1 = isType("array");
        var isNull = eq2(null);
        var noop3 = function() {
        };
        var constant = function(value) {
          return function() {
            return value;
          };
        };
        var identity = function(x2) {
          return x2;
        };
        var never = constant(false);
        var always = constant(true);
        var none = function() {
          return NONE;
        };
        var NONE = function() {
          var call = function(thunk) {
            return thunk();
          };
          var id2 = identity;
          var me2 = {
            fold: function(n2, _s) {
              return n2();
            },
            isSome: never,
            isNone: always,
            getOr: id2,
            getOrThunk: call,
            getOrDie: function(msg) {
              throw new Error(msg || "error: getOrDie called on none.");
            },
            getOrNull: constant(null),
            getOrUndefined: constant(void 0),
            or: id2,
            orThunk: call,
            map: none,
            each: noop3,
            bind: none,
            exists: never,
            forall: always,
            filter: function() {
              return none();
            },
            toArray: function() {
              return [];
            },
            toString: constant("none()")
          };
          return me2;
        }();
        var some = function(a2) {
          var constant_a = constant(a2);
          var self2 = function() {
            return me2;
          };
          var bind2 = function(f2) {
            return f2(a2);
          };
          var me2 = {
            fold: function(n2, s2) {
              return s2(a2);
            },
            isSome: always,
            isNone: never,
            getOr: constant_a,
            getOrThunk: constant_a,
            getOrDie: constant_a,
            getOrNull: constant_a,
            getOrUndefined: constant_a,
            or: self2,
            orThunk: self2,
            map: function(f2) {
              return some(f2(a2));
            },
            each: function(f2) {
              f2(a2);
            },
            bind: bind2,
            exists: bind2,
            forall: bind2,
            filter: function(f2) {
              return f2(a2) ? me2 : NONE;
            },
            toArray: function() {
              return [a2];
            },
            toString: function() {
              return "some(" + a2 + ")";
            }
          };
          return me2;
        };
        var from = function(value) {
          return value === null || value === void 0 ? NONE : some(value);
        };
        var Optional = {
          some,
          none,
          from
        };
        var nativePush = Array.prototype.push;
        var map3 = function(xs, f2) {
          var len = xs.length;
          var r2 = new Array(len);
          for (var i2 = 0; i2 < len; i2++) {
            var x2 = xs[i2];
            r2[i2] = f2(x2, i2);
          }
          return r2;
        };
        var each2 = function(xs, f2) {
          for (var i2 = 0, len = xs.length; i2 < len; i2++) {
            var x2 = xs[i2];
            f2(x2, i2);
          }
        };
        var findUntil = function(xs, pred, until) {
          for (var i2 = 0, len = xs.length; i2 < len; i2++) {
            var x2 = xs[i2];
            if (pred(x2, i2)) {
              return Optional.some(x2);
            } else if (until(x2, i2)) {
              break;
            }
          }
          return Optional.none();
        };
        var find = function(xs, pred) {
          return findUntil(xs, pred, never);
        };
        var flatten = function(xs) {
          var r2 = [];
          for (var i2 = 0, len = xs.length; i2 < len; ++i2) {
            if (!isArray$1(xs[i2])) {
              throw new Error("Arr.flatten item " + i2 + " was not an array, input: " + xs);
            }
            nativePush.apply(r2, xs[i2]);
          }
          return r2;
        };
        var bind = function(xs, f2) {
          return flatten(map3(xs, f2));
        };
        var global$1 = tinymce.util.Tools.resolve("tinymce.util.Tools");
        var getCharMap$1 = function(editor) {
          return editor.getParam("charmap");
        };
        var getCharMapAppend = function(editor) {
          return editor.getParam("charmap_append");
        };
        var isArray2 = global$1.isArray;
        var UserDefined = "User Defined";
        var getDefaultCharMap = function() {
          return [
            {
              name: "Currency",
              characters: [
                [
                  36,
                  "dollar sign"
                ],
                [
                  162,
                  "cent sign"
                ],
                [
                  8364,
                  "euro sign"
                ],
                [
                  163,
                  "pound sign"
                ],
                [
                  165,
                  "yen sign"
                ],
                [
                  164,
                  "currency sign"
                ],
                [
                  8352,
                  "euro-currency sign"
                ],
                [
                  8353,
                  "colon sign"
                ],
                [
                  8354,
                  "cruzeiro sign"
                ],
                [
                  8355,
                  "french franc sign"
                ],
                [
                  8356,
                  "lira sign"
                ],
                [
                  8357,
                  "mill sign"
                ],
                [
                  8358,
                  "naira sign"
                ],
                [
                  8359,
                  "peseta sign"
                ],
                [
                  8360,
                  "rupee sign"
                ],
                [
                  8361,
                  "won sign"
                ],
                [
                  8362,
                  "new sheqel sign"
                ],
                [
                  8363,
                  "dong sign"
                ],
                [
                  8365,
                  "kip sign"
                ],
                [
                  8366,
                  "tugrik sign"
                ],
                [
                  8367,
                  "drachma sign"
                ],
                [
                  8368,
                  "german penny symbol"
                ],
                [
                  8369,
                  "peso sign"
                ],
                [
                  8370,
                  "guarani sign"
                ],
                [
                  8371,
                  "austral sign"
                ],
                [
                  8372,
                  "hryvnia sign"
                ],
                [
                  8373,
                  "cedi sign"
                ],
                [
                  8374,
                  "livre tournois sign"
                ],
                [
                  8375,
                  "spesmilo sign"
                ],
                [
                  8376,
                  "tenge sign"
                ],
                [
                  8377,
                  "indian rupee sign"
                ],
                [
                  8378,
                  "turkish lira sign"
                ],
                [
                  8379,
                  "nordic mark sign"
                ],
                [
                  8380,
                  "manat sign"
                ],
                [
                  8381,
                  "ruble sign"
                ],
                [
                  20870,
                  "yen character"
                ],
                [
                  20803,
                  "yuan character"
                ],
                [
                  22291,
                  "yuan character, in hong kong and taiwan"
                ],
                [
                  22278,
                  "yen/yuan character variant one"
                ]
              ]
            },
            {
              name: "Text",
              characters: [
                [
                  169,
                  "copyright sign"
                ],
                [
                  174,
                  "registered sign"
                ],
                [
                  8482,
                  "trade mark sign"
                ],
                [
                  8240,
                  "per mille sign"
                ],
                [
                  181,
                  "micro sign"
                ],
                [
                  183,
                  "middle dot"
                ],
                [
                  8226,
                  "bullet"
                ],
                [
                  8230,
                  "three dot leader"
                ],
                [
                  8242,
                  "minutes / feet"
                ],
                [
                  8243,
                  "seconds / inches"
                ],
                [
                  167,
                  "section sign"
                ],
                [
                  182,
                  "paragraph sign"
                ],
                [
                  223,
                  "sharp s / ess-zed"
                ]
              ]
            },
            {
              name: "Quotations",
              characters: [
                [
                  8249,
                  "single left-pointing angle quotation mark"
                ],
                [
                  8250,
                  "single right-pointing angle quotation mark"
                ],
                [
                  171,
                  "left pointing guillemet"
                ],
                [
                  187,
                  "right pointing guillemet"
                ],
                [
                  8216,
                  "left single quotation mark"
                ],
                [
                  8217,
                  "right single quotation mark"
                ],
                [
                  8220,
                  "left double quotation mark"
                ],
                [
                  8221,
                  "right double quotation mark"
                ],
                [
                  8218,
                  "single low-9 quotation mark"
                ],
                [
                  8222,
                  "double low-9 quotation mark"
                ],
                [
                  60,
                  "less-than sign"
                ],
                [
                  62,
                  "greater-than sign"
                ],
                [
                  8804,
                  "less-than or equal to"
                ],
                [
                  8805,
                  "greater-than or equal to"
                ],
                [
                  8211,
                  "en dash"
                ],
                [
                  8212,
                  "em dash"
                ],
                [
                  175,
                  "macron"
                ],
                [
                  8254,
                  "overline"
                ],
                [
                  164,
                  "currency sign"
                ],
                [
                  166,
                  "broken bar"
                ],
                [
                  168,
                  "diaeresis"
                ],
                [
                  161,
                  "inverted exclamation mark"
                ],
                [
                  191,
                  "turned question mark"
                ],
                [
                  710,
                  "circumflex accent"
                ],
                [
                  732,
                  "small tilde"
                ],
                [
                  176,
                  "degree sign"
                ],
                [
                  8722,
                  "minus sign"
                ],
                [
                  177,
                  "plus-minus sign"
                ],
                [
                  247,
                  "division sign"
                ],
                [
                  8260,
                  "fraction slash"
                ],
                [
                  215,
                  "multiplication sign"
                ],
                [
                  185,
                  "superscript one"
                ],
                [
                  178,
                  "superscript two"
                ],
                [
                  179,
                  "superscript three"
                ],
                [
                  188,
                  "fraction one quarter"
                ],
                [
                  189,
                  "fraction one half"
                ],
                [
                  190,
                  "fraction three quarters"
                ]
              ]
            },
            {
              name: "Mathematical",
              characters: [
                [
                  402,
                  "function / florin"
                ],
                [
                  8747,
                  "integral"
                ],
                [
                  8721,
                  "n-ary sumation"
                ],
                [
                  8734,
                  "infinity"
                ],
                [
                  8730,
                  "square root"
                ],
                [
                  8764,
                  "similar to"
                ],
                [
                  8773,
                  "approximately equal to"
                ],
                [
                  8776,
                  "almost equal to"
                ],
                [
                  8800,
                  "not equal to"
                ],
                [
                  8801,
                  "identical to"
                ],
                [
                  8712,
                  "element of"
                ],
                [
                  8713,
                  "not an element of"
                ],
                [
                  8715,
                  "contains as member"
                ],
                [
                  8719,
                  "n-ary product"
                ],
                [
                  8743,
                  "logical and"
                ],
                [
                  8744,
                  "logical or"
                ],
                [
                  172,
                  "not sign"
                ],
                [
                  8745,
                  "intersection"
                ],
                [
                  8746,
                  "union"
                ],
                [
                  8706,
                  "partial differential"
                ],
                [
                  8704,
                  "for all"
                ],
                [
                  8707,
                  "there exists"
                ],
                [
                  8709,
                  "diameter"
                ],
                [
                  8711,
                  "backward difference"
                ],
                [
                  8727,
                  "asterisk operator"
                ],
                [
                  8733,
                  "proportional to"
                ],
                [
                  8736,
                  "angle"
                ]
              ]
            },
            {
              name: "Extended Latin",
              characters: [
                [
                  192,
                  "A - grave"
                ],
                [
                  193,
                  "A - acute"
                ],
                [
                  194,
                  "A - circumflex"
                ],
                [
                  195,
                  "A - tilde"
                ],
                [
                  196,
                  "A - diaeresis"
                ],
                [
                  197,
                  "A - ring above"
                ],
                [
                  256,
                  "A - macron"
                ],
                [
                  198,
                  "ligature AE"
                ],
                [
                  199,
                  "C - cedilla"
                ],
                [
                  200,
                  "E - grave"
                ],
                [
                  201,
                  "E - acute"
                ],
                [
                  202,
                  "E - circumflex"
                ],
                [
                  203,
                  "E - diaeresis"
                ],
                [
                  274,
                  "E - macron"
                ],
                [
                  204,
                  "I - grave"
                ],
                [
                  205,
                  "I - acute"
                ],
                [
                  206,
                  "I - circumflex"
                ],
                [
                  207,
                  "I - diaeresis"
                ],
                [
                  298,
                  "I - macron"
                ],
                [
                  208,
                  "ETH"
                ],
                [
                  209,
                  "N - tilde"
                ],
                [
                  210,
                  "O - grave"
                ],
                [
                  211,
                  "O - acute"
                ],
                [
                  212,
                  "O - circumflex"
                ],
                [
                  213,
                  "O - tilde"
                ],
                [
                  214,
                  "O - diaeresis"
                ],
                [
                  216,
                  "O - slash"
                ],
                [
                  332,
                  "O - macron"
                ],
                [
                  338,
                  "ligature OE"
                ],
                [
                  352,
                  "S - caron"
                ],
                [
                  217,
                  "U - grave"
                ],
                [
                  218,
                  "U - acute"
                ],
                [
                  219,
                  "U - circumflex"
                ],
                [
                  220,
                  "U - diaeresis"
                ],
                [
                  362,
                  "U - macron"
                ],
                [
                  221,
                  "Y - acute"
                ],
                [
                  376,
                  "Y - diaeresis"
                ],
                [
                  562,
                  "Y - macron"
                ],
                [
                  222,
                  "THORN"
                ],
                [
                  224,
                  "a - grave"
                ],
                [
                  225,
                  "a - acute"
                ],
                [
                  226,
                  "a - circumflex"
                ],
                [
                  227,
                  "a - tilde"
                ],
                [
                  228,
                  "a - diaeresis"
                ],
                [
                  229,
                  "a - ring above"
                ],
                [
                  257,
                  "a - macron"
                ],
                [
                  230,
                  "ligature ae"
                ],
                [
                  231,
                  "c - cedilla"
                ],
                [
                  232,
                  "e - grave"
                ],
                [
                  233,
                  "e - acute"
                ],
                [
                  234,
                  "e - circumflex"
                ],
                [
                  235,
                  "e - diaeresis"
                ],
                [
                  275,
                  "e - macron"
                ],
                [
                  236,
                  "i - grave"
                ],
                [
                  237,
                  "i - acute"
                ],
                [
                  238,
                  "i - circumflex"
                ],
                [
                  239,
                  "i - diaeresis"
                ],
                [
                  299,
                  "i - macron"
                ],
                [
                  240,
                  "eth"
                ],
                [
                  241,
                  "n - tilde"
                ],
                [
                  242,
                  "o - grave"
                ],
                [
                  243,
                  "o - acute"
                ],
                [
                  244,
                  "o - circumflex"
                ],
                [
                  245,
                  "o - tilde"
                ],
                [
                  246,
                  "o - diaeresis"
                ],
                [
                  248,
                  "o slash"
                ],
                [
                  333,
                  "o macron"
                ],
                [
                  339,
                  "ligature oe"
                ],
                [
                  353,
                  "s - caron"
                ],
                [
                  249,
                  "u - grave"
                ],
                [
                  250,
                  "u - acute"
                ],
                [
                  251,
                  "u - circumflex"
                ],
                [
                  252,
                  "u - diaeresis"
                ],
                [
                  363,
                  "u - macron"
                ],
                [
                  253,
                  "y - acute"
                ],
                [
                  254,
                  "thorn"
                ],
                [
                  255,
                  "y - diaeresis"
                ],
                [
                  563,
                  "y - macron"
                ],
                [
                  913,
                  "Alpha"
                ],
                [
                  914,
                  "Beta"
                ],
                [
                  915,
                  "Gamma"
                ],
                [
                  916,
                  "Delta"
                ],
                [
                  917,
                  "Epsilon"
                ],
                [
                  918,
                  "Zeta"
                ],
                [
                  919,
                  "Eta"
                ],
                [
                  920,
                  "Theta"
                ],
                [
                  921,
                  "Iota"
                ],
                [
                  922,
                  "Kappa"
                ],
                [
                  923,
                  "Lambda"
                ],
                [
                  924,
                  "Mu"
                ],
                [
                  925,
                  "Nu"
                ],
                [
                  926,
                  "Xi"
                ],
                [
                  927,
                  "Omicron"
                ],
                [
                  928,
                  "Pi"
                ],
                [
                  929,
                  "Rho"
                ],
                [
                  931,
                  "Sigma"
                ],
                [
                  932,
                  "Tau"
                ],
                [
                  933,
                  "Upsilon"
                ],
                [
                  934,
                  "Phi"
                ],
                [
                  935,
                  "Chi"
                ],
                [
                  936,
                  "Psi"
                ],
                [
                  937,
                  "Omega"
                ],
                [
                  945,
                  "alpha"
                ],
                [
                  946,
                  "beta"
                ],
                [
                  947,
                  "gamma"
                ],
                [
                  948,
                  "delta"
                ],
                [
                  949,
                  "epsilon"
                ],
                [
                  950,
                  "zeta"
                ],
                [
                  951,
                  "eta"
                ],
                [
                  952,
                  "theta"
                ],
                [
                  953,
                  "iota"
                ],
                [
                  954,
                  "kappa"
                ],
                [
                  955,
                  "lambda"
                ],
                [
                  956,
                  "mu"
                ],
                [
                  957,
                  "nu"
                ],
                [
                  958,
                  "xi"
                ],
                [
                  959,
                  "omicron"
                ],
                [
                  960,
                  "pi"
                ],
                [
                  961,
                  "rho"
                ],
                [
                  962,
                  "final sigma"
                ],
                [
                  963,
                  "sigma"
                ],
                [
                  964,
                  "tau"
                ],
                [
                  965,
                  "upsilon"
                ],
                [
                  966,
                  "phi"
                ],
                [
                  967,
                  "chi"
                ],
                [
                  968,
                  "psi"
                ],
                [
                  969,
                  "omega"
                ]
              ]
            },
            {
              name: "Symbols",
              characters: [
                [
                  8501,
                  "alef symbol"
                ],
                [
                  982,
                  "pi symbol"
                ],
                [
                  8476,
                  "real part symbol"
                ],
                [
                  978,
                  "upsilon - hook symbol"
                ],
                [
                  8472,
                  "Weierstrass p"
                ],
                [
                  8465,
                  "imaginary part"
                ]
              ]
            },
            {
              name: "Arrows",
              characters: [
                [
                  8592,
                  "leftwards arrow"
                ],
                [
                  8593,
                  "upwards arrow"
                ],
                [
                  8594,
                  "rightwards arrow"
                ],
                [
                  8595,
                  "downwards arrow"
                ],
                [
                  8596,
                  "left right arrow"
                ],
                [
                  8629,
                  "carriage return"
                ],
                [
                  8656,
                  "leftwards double arrow"
                ],
                [
                  8657,
                  "upwards double arrow"
                ],
                [
                  8658,
                  "rightwards double arrow"
                ],
                [
                  8659,
                  "downwards double arrow"
                ],
                [
                  8660,
                  "left right double arrow"
                ],
                [
                  8756,
                  "therefore"
                ],
                [
                  8834,
                  "subset of"
                ],
                [
                  8835,
                  "superset of"
                ],
                [
                  8836,
                  "not a subset of"
                ],
                [
                  8838,
                  "subset of or equal to"
                ],
                [
                  8839,
                  "superset of or equal to"
                ],
                [
                  8853,
                  "circled plus"
                ],
                [
                  8855,
                  "circled times"
                ],
                [
                  8869,
                  "perpendicular"
                ],
                [
                  8901,
                  "dot operator"
                ],
                [
                  8968,
                  "left ceiling"
                ],
                [
                  8969,
                  "right ceiling"
                ],
                [
                  8970,
                  "left floor"
                ],
                [
                  8971,
                  "right floor"
                ],
                [
                  9001,
                  "left-pointing angle bracket"
                ],
                [
                  9002,
                  "right-pointing angle bracket"
                ],
                [
                  9674,
                  "lozenge"
                ],
                [
                  9824,
                  "black spade suit"
                ],
                [
                  9827,
                  "black club suit"
                ],
                [
                  9829,
                  "black heart suit"
                ],
                [
                  9830,
                  "black diamond suit"
                ],
                [
                  8194,
                  "en space"
                ],
                [
                  8195,
                  "em space"
                ],
                [
                  8201,
                  "thin space"
                ],
                [
                  8204,
                  "zero width non-joiner"
                ],
                [
                  8205,
                  "zero width joiner"
                ],
                [
                  8206,
                  "left-to-right mark"
                ],
                [
                  8207,
                  "right-to-left mark"
                ]
              ]
            }
          ];
        };
        var charmapFilter = function(charmap) {
          return global$1.grep(charmap, function(item) {
            return isArray2(item) && item.length === 2;
          });
        };
        var getCharsFromSetting = function(settingValue) {
          if (isArray2(settingValue)) {
            return charmapFilter(settingValue);
          }
          if (typeof settingValue === "function") {
            return settingValue();
          }
          return [];
        };
        var extendCharMap = function(editor, charmap) {
          var userCharMap = getCharMap$1(editor);
          if (userCharMap) {
            charmap = [{
              name: UserDefined,
              characters: getCharsFromSetting(userCharMap)
            }];
          }
          var userCharMapAppend = getCharMapAppend(editor);
          if (userCharMapAppend) {
            var userDefinedGroup = global$1.grep(charmap, function(cg) {
              return cg.name === UserDefined;
            });
            if (userDefinedGroup.length) {
              userDefinedGroup[0].characters = [].concat(userDefinedGroup[0].characters).concat(getCharsFromSetting(userCharMapAppend));
              return charmap;
            }
            return charmap.concat({
              name: UserDefined,
              characters: getCharsFromSetting(userCharMapAppend)
            });
          }
          return charmap;
        };
        var getCharMap = function(editor) {
          var groups = extendCharMap(editor, getDefaultCharMap());
          return groups.length > 1 ? [{
            name: "All",
            characters: bind(groups, function(g2) {
              return g2.characters;
            })
          }].concat(groups) : groups;
        };
        var get = function(editor) {
          var getCharMap$12 = function() {
            return getCharMap(editor);
          };
          var insertChar$1 = function(chr) {
            insertChar(editor, chr);
          };
          return {
            getCharMap: getCharMap$12,
            insertChar: insertChar$1
          };
        };
        var Cell = function(initial) {
          var value = initial;
          var get2 = function() {
            return value;
          };
          var set2 = function(v2) {
            value = v2;
          };
          return {
            get: get2,
            set: set2
          };
        };
        var last = function(fn3, rate) {
          var timer = null;
          var cancel = function() {
            if (!isNull(timer)) {
              clearTimeout(timer);
              timer = null;
            }
          };
          var throttle = function() {
            var args = [];
            for (var _i2 = 0; _i2 < arguments.length; _i2++) {
              args[_i2] = arguments[_i2];
            }
            cancel();
            timer = setTimeout(function() {
              timer = null;
              fn3.apply(null, args);
            }, rate);
          };
          return {
            cancel,
            throttle
          };
        };
        var nativeFromCodePoint = String.fromCodePoint;
        var contains2 = function(str, substr) {
          return str.indexOf(substr) !== -1;
        };
        var fromCodePoint = function() {
          var codePoints = [];
          for (var _i2 = 0; _i2 < arguments.length; _i2++) {
            codePoints[_i2] = arguments[_i2];
          }
          if (nativeFromCodePoint) {
            return nativeFromCodePoint.apply(void 0, codePoints);
          } else {
            var codeUnits = [];
            var codeLen = 0;
            var result = "";
            for (var index = 0, len = codePoints.length; index !== len; ++index) {
              var codePoint = +codePoints[index];
              if (!(codePoint < 1114111 && codePoint >>> 0 === codePoint)) {
                throw RangeError("Invalid code point: " + codePoint);
              }
              if (codePoint <= 65535) {
                codeLen = codeUnits.push(codePoint);
              } else {
                codePoint -= 65536;
                codeLen = codeUnits.push((codePoint >> 10) + 55296, codePoint % 1024 + 56320);
              }
              if (codeLen >= 16383) {
                result += String.fromCharCode.apply(null, codeUnits);
                codeUnits.length = 0;
              }
            }
            return result + String.fromCharCode.apply(null, codeUnits);
          }
        };
        var charMatches = function(charCode, name, lowerCasePattern) {
          if (contains2(fromCodePoint(charCode).toLowerCase(), lowerCasePattern)) {
            return true;
          } else {
            return contains2(name.toLowerCase(), lowerCasePattern) || contains2(name.toLowerCase().replace(/\s+/g, ""), lowerCasePattern);
          }
        };
        var scan = function(group, pattern) {
          var matches = [];
          var lowerCasePattern = pattern.toLowerCase();
          each2(group.characters, function(g2) {
            if (charMatches(g2[0], g2[1], lowerCasePattern)) {
              matches.push(g2);
            }
          });
          return map3(matches, function(m2) {
            return {
              text: m2[1],
              value: fromCodePoint(m2[0]),
              icon: fromCodePoint(m2[0])
            };
          });
        };
        var patternName = "pattern";
        var open = function(editor, charMap) {
          var makeGroupItems = function() {
            return [
              {
                label: "Search",
                type: "input",
                name: patternName
              },
              {
                type: "collection",
                name: "results"
              }
            ];
          };
          var makeTabs = function() {
            return map3(charMap, function(charGroup) {
              return {
                title: charGroup.name,
                name: charGroup.name,
                items: makeGroupItems()
              };
            });
          };
          var makePanel = function() {
            return {
              type: "panel",
              items: makeGroupItems()
            };
          };
          var makeTabPanel = function() {
            return {
              type: "tabpanel",
              tabs: makeTabs()
            };
          };
          var currentTab = charMap.length === 1 ? Cell(UserDefined) : Cell("All");
          var scanAndSet = function(dialogApi2, pattern) {
            find(charMap, function(group) {
              return group.name === currentTab.get();
            }).each(function(f2) {
              var items = scan(f2, pattern);
              dialogApi2.setData({ results: items });
            });
          };
          var SEARCH_DELAY = 40;
          var updateFilter = last(function(dialogApi2) {
            var pattern = dialogApi2.getData().pattern;
            scanAndSet(dialogApi2, pattern);
          }, SEARCH_DELAY);
          var body = charMap.length === 1 ? makePanel() : makeTabPanel();
          var initialData = {
            pattern: "",
            results: scan(charMap[0], "")
          };
          var bridgeSpec = {
            title: "Special Character",
            size: "normal",
            body,
            buttons: [{
              type: "cancel",
              name: "close",
              text: "Close",
              primary: true
            }],
            initialData,
            onAction: function(api, details) {
              if (details.name === "results") {
                insertChar(editor, details.value);
                api.close();
              }
            },
            onTabChange: function(dialogApi2, details) {
              currentTab.set(details.newTabName);
              updateFilter.throttle(dialogApi2);
            },
            onChange: function(dialogApi2, changeData) {
              if (changeData.name === patternName) {
                updateFilter.throttle(dialogApi2);
              }
            }
          };
          var dialogApi = editor.windowManager.open(bridgeSpec);
          dialogApi.focus(patternName);
        };
        var register$1 = function(editor, charMap) {
          editor.addCommand("mceShowCharmap", function() {
            open(editor, charMap);
          });
        };
        var global2 = tinymce.util.Tools.resolve("tinymce.util.Promise");
        var init = function(editor, all) {
          editor.ui.registry.addAutocompleter("charmap", {
            ch: ":",
            columns: "auto",
            minChars: 2,
            fetch: function(pattern, _maxResults) {
              return new global2(function(resolve2, _reject) {
                resolve2(scan(all, pattern));
              });
            },
            onAction: function(autocompleteApi, rng, value) {
              editor.selection.setRng(rng);
              editor.insertContent(value);
              autocompleteApi.hide();
            }
          });
        };
        var register = function(editor) {
          editor.ui.registry.addButton("charmap", {
            icon: "insert-character",
            tooltip: "Special character",
            onAction: function() {
              return editor.execCommand("mceShowCharmap");
            }
          });
          editor.ui.registry.addMenuItem("charmap", {
            icon: "insert-character",
            text: "Special character...",
            onAction: function() {
              return editor.execCommand("mceShowCharmap");
            }
          });
        };
        function Plugin() {
          global$2.add("charmap", function(editor) {
            var charMap = getCharMap(editor);
            register$1(editor, charMap);
            register(editor);
            init(editor, charMap[0]);
            return get(editor);
          });
        }
        Plugin();
      })();
    }
  });

  // ../../node_modules/tinymce/plugins/hr/plugin.js
  var require_plugin18 = __commonJS({
    "../../node_modules/tinymce/plugins/hr/plugin.js"() {
      (function() {
        "use strict";
        var global2 = tinymce.util.Tools.resolve("tinymce.PluginManager");
        var register$1 = function(editor) {
          editor.addCommand("InsertHorizontalRule", function() {
            editor.execCommand("mceInsertContent", false, "<hr />");
          });
        };
        var register = function(editor) {
          var onAction = function() {
            return editor.execCommand("InsertHorizontalRule");
          };
          editor.ui.registry.addButton("hr", {
            icon: "horizontal-rule",
            tooltip: "Horizontal line",
            onAction
          });
          editor.ui.registry.addMenuItem("hr", {
            icon: "horizontal-rule",
            text: "Horizontal line",
            onAction
          });
        };
        function Plugin() {
          global2.add("hr", function(editor) {
            register$1(editor);
            register(editor);
          });
        }
        Plugin();
      })();
    }
  });

  // ../../node_modules/tinymce/plugins/pagebreak/plugin.js
  var require_plugin19 = __commonJS({
    "../../node_modules/tinymce/plugins/pagebreak/plugin.js"() {
      (function() {
        "use strict";
        var global$1 = tinymce.util.Tools.resolve("tinymce.PluginManager");
        var global2 = tinymce.util.Tools.resolve("tinymce.Env");
        var getSeparatorHtml = function(editor) {
          return editor.getParam("pagebreak_separator", "<!-- pagebreak -->");
        };
        var shouldSplitBlock = function(editor) {
          return editor.getParam("pagebreak_split_block", false);
        };
        var pageBreakClass = "mce-pagebreak";
        var getPlaceholderHtml = function(shouldSplitBlock2) {
          var html = '<img src="' + global2.transparentSrc + '" class="' + pageBreakClass + '" data-mce-resize="false" data-mce-placeholder />';
          return shouldSplitBlock2 ? "<p>" + html + "</p>" : html;
        };
        var setup$1 = function(editor) {
          var separatorHtml = getSeparatorHtml(editor);
          var shouldSplitBlock$1 = function() {
            return shouldSplitBlock(editor);
          };
          var pageBreakSeparatorRegExp = new RegExp(separatorHtml.replace(/[\?\.\*\[\]\(\)\{\}\+\^\$\:]/g, function(a2) {
            return "\\" + a2;
          }), "gi");
          editor.on("BeforeSetContent", function(e2) {
            e2.content = e2.content.replace(pageBreakSeparatorRegExp, getPlaceholderHtml(shouldSplitBlock$1()));
          });
          editor.on("PreInit", function() {
            editor.serializer.addNodeFilter("img", function(nodes) {
              var i2 = nodes.length, node, className;
              while (i2--) {
                node = nodes[i2];
                className = node.attr("class");
                if (className && className.indexOf(pageBreakClass) !== -1) {
                  var parentNode = node.parent;
                  if (editor.schema.getBlockElements()[parentNode.name] && shouldSplitBlock$1()) {
                    parentNode.type = 3;
                    parentNode.value = separatorHtml;
                    parentNode.raw = true;
                    node.remove();
                    continue;
                  }
                  node.type = 3;
                  node.value = separatorHtml;
                  node.raw = true;
                }
              }
            });
          });
        };
        var register$1 = function(editor) {
          editor.addCommand("mcePageBreak", function() {
            editor.insertContent(getPlaceholderHtml(shouldSplitBlock(editor)));
          });
        };
        var setup = function(editor) {
          editor.on("ResolveName", function(e2) {
            if (e2.target.nodeName === "IMG" && editor.dom.hasClass(e2.target, pageBreakClass)) {
              e2.name = "pagebreak";
            }
          });
        };
        var register = function(editor) {
          var onAction = function() {
            return editor.execCommand("mcePageBreak");
          };
          editor.ui.registry.addButton("pagebreak", {
            icon: "page-break",
            tooltip: "Page break",
            onAction
          });
          editor.ui.registry.addMenuItem("pagebreak", {
            text: "Page break",
            icon: "page-break",
            onAction
          });
        };
        function Plugin() {
          global$1.add("pagebreak", function(editor) {
            register$1(editor);
            register(editor);
            setup$1(editor);
            setup(editor);
          });
        }
        Plugin();
      })();
    }
  });

  // ../../node_modules/tinymce/plugins/nonbreaking/plugin.js
  var require_plugin20 = __commonJS({
    "../../node_modules/tinymce/plugins/nonbreaking/plugin.js"() {
      (function() {
        "use strict";
        var global$1 = tinymce.util.Tools.resolve("tinymce.PluginManager");
        var getKeyboardSpaces = function(editor) {
          var spaces = editor.getParam("nonbreaking_force_tab", 0);
          if (typeof spaces === "boolean") {
            return spaces === true ? 3 : 0;
          } else {
            return spaces;
          }
        };
        var wrapNbsps = function(editor) {
          return editor.getParam("nonbreaking_wrap", true, "boolean");
        };
        var stringRepeat = function(string, repeats) {
          var str = "";
          for (var index = 0; index < repeats; index++) {
            str += string;
          }
          return str;
        };
        var isVisualCharsEnabled = function(editor) {
          return editor.plugins.visualchars ? editor.plugins.visualchars.isEnabled() : false;
        };
        var insertNbsp = function(editor, times) {
          var classes = function() {
            return isVisualCharsEnabled(editor) ? "mce-nbsp-wrap mce-nbsp" : "mce-nbsp-wrap";
          };
          var nbspSpan = function() {
            return '<span class="' + classes() + '" contenteditable="false">' + stringRepeat("&nbsp;", times) + "</span>";
          };
          var shouldWrap = wrapNbsps(editor);
          var html = shouldWrap || editor.plugins.visualchars ? nbspSpan() : stringRepeat("&nbsp;", times);
          editor.undoManager.transact(function() {
            return editor.insertContent(html);
          });
        };
        var register$1 = function(editor) {
          editor.addCommand("mceNonBreaking", function() {
            insertNbsp(editor, 1);
          });
        };
        var global2 = tinymce.util.Tools.resolve("tinymce.util.VK");
        var setup = function(editor) {
          var spaces = getKeyboardSpaces(editor);
          if (spaces > 0) {
            editor.on("keydown", function(e2) {
              if (e2.keyCode === global2.TAB && !e2.isDefaultPrevented()) {
                if (e2.shiftKey) {
                  return;
                }
                e2.preventDefault();
                e2.stopImmediatePropagation();
                insertNbsp(editor, spaces);
              }
            });
          }
        };
        var register = function(editor) {
          var onAction = function() {
            return editor.execCommand("mceNonBreaking");
          };
          editor.ui.registry.addButton("nonbreaking", {
            icon: "non-breaking",
            tooltip: "Nonbreaking space",
            onAction
          });
          editor.ui.registry.addMenuItem("nonbreaking", {
            icon: "non-breaking",
            text: "Nonbreaking space",
            onAction
          });
        };
        function Plugin() {
          global$1.add("nonbreaking", function(editor) {
            register$1(editor);
            register(editor);
            setup(editor);
          });
        }
        Plugin();
      })();
    }
  });

  // ../../node_modules/tinymce/plugins/anchor/plugin.js
  var require_plugin21 = __commonJS({
    "../../node_modules/tinymce/plugins/anchor/plugin.js"() {
      (function() {
        "use strict";
        var global$2 = tinymce.util.Tools.resolve("tinymce.PluginManager");
        var global$1 = tinymce.util.Tools.resolve("tinymce.dom.RangeUtils");
        var global2 = tinymce.util.Tools.resolve("tinymce.util.Tools");
        var allowHtmlInNamedAnchor = function(editor) {
          return editor.getParam("allow_html_in_named_anchor", false, "boolean");
        };
        var namedAnchorSelector = "a:not([href])";
        var isEmptyString = function(str) {
          return !str;
        };
        var getIdFromAnchor = function(elm) {
          var id2 = elm.getAttribute("id") || elm.getAttribute("name");
          return id2 || "";
        };
        var isAnchor = function(elm) {
          return elm && elm.nodeName.toLowerCase() === "a";
        };
        var isNamedAnchor = function(elm) {
          return isAnchor(elm) && !elm.getAttribute("href") && getIdFromAnchor(elm) !== "";
        };
        var isEmptyNamedAnchor = function(elm) {
          return isNamedAnchor(elm) && !elm.firstChild;
        };
        var removeEmptyNamedAnchorsInSelection = function(editor) {
          var dom = editor.dom;
          global$1(dom).walk(editor.selection.getRng(), function(nodes) {
            global2.each(nodes, function(node) {
              if (isEmptyNamedAnchor(node)) {
                dom.remove(node, false);
              }
            });
          });
        };
        var isValidId = function(id2) {
          return /^[A-Za-z][A-Za-z0-9\-:._]*$/.test(id2);
        };
        var getNamedAnchor = function(editor) {
          return editor.dom.getParent(editor.selection.getStart(), namedAnchorSelector);
        };
        var getId = function(editor) {
          var anchor = getNamedAnchor(editor);
          if (anchor) {
            return getIdFromAnchor(anchor);
          } else {
            return "";
          }
        };
        var createAnchor = function(editor, id2) {
          editor.undoManager.transact(function() {
            if (!allowHtmlInNamedAnchor(editor)) {
              editor.selection.collapse(true);
            }
            if (editor.selection.isCollapsed()) {
              editor.insertContent(editor.dom.createHTML("a", { id: id2 }));
            } else {
              removeEmptyNamedAnchorsInSelection(editor);
              editor.formatter.remove("namedAnchor", null, null, true);
              editor.formatter.apply("namedAnchor", { value: id2 });
              editor.addVisual();
            }
          });
        };
        var updateAnchor = function(editor, id2, anchorElement) {
          anchorElement.removeAttribute("name");
          anchorElement.id = id2;
          editor.addVisual();
          editor.undoManager.add();
        };
        var insert = function(editor, id2) {
          var anchor = getNamedAnchor(editor);
          if (anchor) {
            updateAnchor(editor, id2, anchor);
          } else {
            createAnchor(editor, id2);
          }
          editor.focus();
        };
        var insertAnchor = function(editor, newId) {
          if (!isValidId(newId)) {
            editor.windowManager.alert("Id should start with a letter, followed only by letters, numbers, dashes, dots, colons or underscores.");
            return false;
          } else {
            insert(editor, newId);
            return true;
          }
        };
        var open = function(editor) {
          var currentId = getId(editor);
          editor.windowManager.open({
            title: "Anchor",
            size: "normal",
            body: {
              type: "panel",
              items: [{
                name: "id",
                type: "input",
                label: "ID",
                placeholder: "example"
              }]
            },
            buttons: [
              {
                type: "cancel",
                name: "cancel",
                text: "Cancel"
              },
              {
                type: "submit",
                name: "save",
                text: "Save",
                primary: true
              }
            ],
            initialData: { id: currentId },
            onSubmit: function(api) {
              if (insertAnchor(editor, api.getData().id)) {
                api.close();
              }
            }
          });
        };
        var register$1 = function(editor) {
          editor.addCommand("mceAnchor", function() {
            open(editor);
          });
        };
        var isNamedAnchorNode = function(node) {
          return node && isEmptyString(node.attr("href")) && !isEmptyString(node.attr("id") || node.attr("name"));
        };
        var isEmptyNamedAnchorNode = function(node) {
          return isNamedAnchorNode(node) && !node.firstChild;
        };
        var setContentEditable = function(state) {
          return function(nodes) {
            for (var i2 = 0; i2 < nodes.length; i2++) {
              var node = nodes[i2];
              if (isEmptyNamedAnchorNode(node)) {
                node.attr("contenteditable", state);
              }
            }
          };
        };
        var setup = function(editor) {
          editor.on("PreInit", function() {
            editor.parser.addNodeFilter("a", setContentEditable("false"));
            editor.serializer.addNodeFilter("a", setContentEditable(null));
          });
        };
        var registerFormats = function(editor) {
          editor.formatter.register("namedAnchor", {
            inline: "a",
            selector: namedAnchorSelector,
            remove: "all",
            split: true,
            deep: true,
            attributes: { id: "%value" },
            onmatch: function(node, _fmt, _itemName) {
              return isNamedAnchor(node);
            }
          });
        };
        var register = function(editor) {
          editor.ui.registry.addToggleButton("anchor", {
            icon: "bookmark",
            tooltip: "Anchor",
            onAction: function() {
              return editor.execCommand("mceAnchor");
            },
            onSetup: function(buttonApi) {
              return editor.selection.selectorChangedWithUnbind("a:not([href])", buttonApi.setActive).unbind;
            }
          });
          editor.ui.registry.addMenuItem("anchor", {
            icon: "bookmark",
            text: "Anchor...",
            onAction: function() {
              return editor.execCommand("mceAnchor");
            }
          });
        };
        function Plugin() {
          global$2.add("anchor", function(editor) {
            setup(editor);
            register$1(editor);
            register(editor);
            editor.on("PreInit", function() {
              registerFormats(editor);
            });
          });
        }
        Plugin();
      })();
    }
  });

  // ../../node_modules/tinymce/plugins/advlist/plugin.js
  var require_plugin22 = __commonJS({
    "../../node_modules/tinymce/plugins/advlist/plugin.js"() {
      (function() {
        "use strict";
        var global$1 = tinymce.util.Tools.resolve("tinymce.PluginManager");
        var applyListFormat = function(editor, listName, styleValue) {
          var cmd = listName === "UL" ? "InsertUnorderedList" : "InsertOrderedList";
          editor.execCommand(cmd, false, styleValue === false ? null : { "list-style-type": styleValue });
        };
        var register$1 = function(editor) {
          editor.addCommand("ApplyUnorderedListStyle", function(ui2, value) {
            applyListFormat(editor, "UL", value["list-style-type"]);
          });
          editor.addCommand("ApplyOrderedListStyle", function(ui2, value) {
            applyListFormat(editor, "OL", value["list-style-type"]);
          });
        };
        var global2 = tinymce.util.Tools.resolve("tinymce.util.Tools");
        var getNumberStyles = function(editor) {
          var styles = editor.getParam("advlist_number_styles", "default,lower-alpha,lower-greek,lower-roman,upper-alpha,upper-roman");
          return styles ? styles.split(/[ ,]/) : [];
        };
        var getBulletStyles = function(editor) {
          var styles = editor.getParam("advlist_bullet_styles", "default,circle,square");
          return styles ? styles.split(/[ ,]/) : [];
        };
        var noop3 = function() {
        };
        var constant = function(value) {
          return function() {
            return value;
          };
        };
        var identity = function(x2) {
          return x2;
        };
        var never = constant(false);
        var always = constant(true);
        var none = function() {
          return NONE;
        };
        var NONE = function() {
          var call = function(thunk) {
            return thunk();
          };
          var id2 = identity;
          var me2 = {
            fold: function(n2, _s) {
              return n2();
            },
            isSome: never,
            isNone: always,
            getOr: id2,
            getOrThunk: call,
            getOrDie: function(msg) {
              throw new Error(msg || "error: getOrDie called on none.");
            },
            getOrNull: constant(null),
            getOrUndefined: constant(void 0),
            or: id2,
            orThunk: call,
            map: none,
            each: noop3,
            bind: none,
            exists: never,
            forall: always,
            filter: function() {
              return none();
            },
            toArray: function() {
              return [];
            },
            toString: constant("none()")
          };
          return me2;
        }();
        var some = function(a2) {
          var constant_a = constant(a2);
          var self2 = function() {
            return me2;
          };
          var bind = function(f2) {
            return f2(a2);
          };
          var me2 = {
            fold: function(n2, s2) {
              return s2(a2);
            },
            isSome: always,
            isNone: never,
            getOr: constant_a,
            getOrThunk: constant_a,
            getOrDie: constant_a,
            getOrNull: constant_a,
            getOrUndefined: constant_a,
            or: self2,
            orThunk: self2,
            map: function(f2) {
              return some(f2(a2));
            },
            each: function(f2) {
              f2(a2);
            },
            bind,
            exists: bind,
            forall: bind,
            filter: function(f2) {
              return f2(a2) ? me2 : NONE;
            },
            toArray: function() {
              return [a2];
            },
            toString: function() {
              return "some(" + a2 + ")";
            }
          };
          return me2;
        };
        var from = function(value) {
          return value === null || value === void 0 ? NONE : some(value);
        };
        var Optional = {
          some,
          none,
          from
        };
        var isChildOfBody = function(editor, elm) {
          return editor.$.contains(editor.getBody(), elm);
        };
        var isTableCellNode = function(node) {
          return node && /^(TH|TD)$/.test(node.nodeName);
        };
        var isListNode = function(editor) {
          return function(node) {
            return node && /^(OL|UL|DL)$/.test(node.nodeName) && isChildOfBody(editor, node);
          };
        };
        var getSelectedStyleType = function(editor) {
          var listElm = editor.dom.getParent(editor.selection.getNode(), "ol,ul");
          var style = editor.dom.getStyle(listElm, "listStyleType");
          return Optional.from(style);
        };
        var findIndex2 = function(list, predicate) {
          for (var index = 0; index < list.length; index++) {
            var element = list[index];
            if (predicate(element)) {
              return index;
            }
          }
          return -1;
        };
        var styleValueToText = function(styleValue) {
          return styleValue.replace(/\-/g, " ").replace(/\b\w/g, function(chr) {
            return chr.toUpperCase();
          });
        };
        var isWithinList = function(editor, e2, nodeName) {
          var tableCellIndex = findIndex2(e2.parents, isTableCellNode);
          var parents = tableCellIndex !== -1 ? e2.parents.slice(0, tableCellIndex) : e2.parents;
          var lists = global2.grep(parents, isListNode(editor));
          return lists.length > 0 && lists[0].nodeName === nodeName;
        };
        var makeSetupHandler = function(editor, nodeName) {
          return function(api) {
            var nodeChangeHandler = function(e2) {
              api.setActive(isWithinList(editor, e2, nodeName));
            };
            editor.on("NodeChange", nodeChangeHandler);
            return function() {
              return editor.off("NodeChange", nodeChangeHandler);
            };
          };
        };
        var addSplitButton = function(editor, id2, tooltip, cmd, nodeName, styles) {
          editor.ui.registry.addSplitButton(id2, {
            tooltip,
            icon: nodeName === "OL" ? "ordered-list" : "unordered-list",
            presets: "listpreview",
            columns: 3,
            fetch: function(callback2) {
              var items = global2.map(styles, function(styleValue) {
                var iconStyle = nodeName === "OL" ? "num" : "bull";
                var iconName = styleValue === "disc" || styleValue === "decimal" ? "default" : styleValue;
                var itemValue = styleValue === "default" ? "" : styleValue;
                var displayText = styleValueToText(styleValue);
                return {
                  type: "choiceitem",
                  value: itemValue,
                  icon: "list-" + iconStyle + "-" + iconName,
                  text: displayText
                };
              });
              callback2(items);
            },
            onAction: function() {
              return editor.execCommand(cmd);
            },
            onItemAction: function(_splitButtonApi, value) {
              applyListFormat(editor, nodeName, value);
            },
            select: function(value) {
              var listStyleType = getSelectedStyleType(editor);
              return listStyleType.map(function(listStyle) {
                return value === listStyle;
              }).getOr(false);
            },
            onSetup: makeSetupHandler(editor, nodeName)
          });
        };
        var addButton = function(editor, id2, tooltip, cmd, nodeName, _styles) {
          editor.ui.registry.addToggleButton(id2, {
            active: false,
            tooltip,
            icon: nodeName === "OL" ? "ordered-list" : "unordered-list",
            onSetup: makeSetupHandler(editor, nodeName),
            onAction: function() {
              return editor.execCommand(cmd);
            }
          });
        };
        var addControl = function(editor, id2, tooltip, cmd, nodeName, styles) {
          if (styles.length > 1) {
            addSplitButton(editor, id2, tooltip, cmd, nodeName, styles);
          } else {
            addButton(editor, id2, tooltip, cmd, nodeName);
          }
        };
        var register = function(editor) {
          addControl(editor, "numlist", "Numbered list", "InsertOrderedList", "OL", getNumberStyles(editor));
          addControl(editor, "bullist", "Bullet list", "InsertUnorderedList", "UL", getBulletStyles(editor));
        };
        function Plugin() {
          global$1.add("advlist", function(editor) {
            if (editor.hasPlugin("lists")) {
              register(editor);
              register$1(editor);
            } else {
              console.error("Please use the Lists plugin together with the Advanced List plugin.");
            }
          });
        }
        Plugin();
      })();
    }
  });

  // ../../node_modules/tinymce/plugins/lists/plugin.js
  var require_plugin23 = __commonJS({
    "../../node_modules/tinymce/plugins/lists/plugin.js"() {
      (function() {
        "use strict";
        var global$7 = tinymce.util.Tools.resolve("tinymce.PluginManager");
        var typeOf = function(x2) {
          var t2 = typeof x2;
          if (x2 === null) {
            return "null";
          } else if (t2 === "object" && (Array.prototype.isPrototypeOf(x2) || x2.constructor && x2.constructor.name === "Array")) {
            return "array";
          } else if (t2 === "object" && (String.prototype.isPrototypeOf(x2) || x2.constructor && x2.constructor.name === "String")) {
            return "string";
          } else {
            return t2;
          }
        };
        var isType$1 = function(type2) {
          return function(value) {
            return typeOf(value) === type2;
          };
        };
        var isSimpleType = function(type2) {
          return function(value) {
            return typeof value === type2;
          };
        };
        var isString = isType$1("string");
        var isObject2 = isType$1("object");
        var isArray2 = isType$1("array");
        var isBoolean = isSimpleType("boolean");
        var isFunction2 = isSimpleType("function");
        var isNumber2 = isSimpleType("number");
        var noop3 = function() {
        };
        var constant = function(value) {
          return function() {
            return value;
          };
        };
        var identity = function(x2) {
          return x2;
        };
        var tripleEquals = function(a2, b2) {
          return a2 === b2;
        };
        var not = function(f2) {
          return function(t2) {
            return !f2(t2);
          };
        };
        var never = constant(false);
        var always = constant(true);
        var none = function() {
          return NONE;
        };
        var NONE = function() {
          var call = function(thunk) {
            return thunk();
          };
          var id2 = identity;
          var me2 = {
            fold: function(n2, _s) {
              return n2();
            },
            isSome: never,
            isNone: always,
            getOr: id2,
            getOrThunk: call,
            getOrDie: function(msg) {
              throw new Error(msg || "error: getOrDie called on none.");
            },
            getOrNull: constant(null),
            getOrUndefined: constant(void 0),
            or: id2,
            orThunk: call,
            map: none,
            each: noop3,
            bind: none,
            exists: never,
            forall: always,
            filter: function() {
              return none();
            },
            toArray: function() {
              return [];
            },
            toString: constant("none()")
          };
          return me2;
        }();
        var some = function(a2) {
          var constant_a = constant(a2);
          var self2 = function() {
            return me2;
          };
          var bind2 = function(f2) {
            return f2(a2);
          };
          var me2 = {
            fold: function(n2, s2) {
              return s2(a2);
            },
            isSome: always,
            isNone: never,
            getOr: constant_a,
            getOrThunk: constant_a,
            getOrDie: constant_a,
            getOrNull: constant_a,
            getOrUndefined: constant_a,
            or: self2,
            orThunk: self2,
            map: function(f2) {
              return some(f2(a2));
            },
            each: function(f2) {
              f2(a2);
            },
            bind: bind2,
            exists: bind2,
            forall: bind2,
            filter: function(f2) {
              return f2(a2) ? me2 : NONE;
            },
            toArray: function() {
              return [a2];
            },
            toString: function() {
              return "some(" + a2 + ")";
            }
          };
          return me2;
        };
        var from = function(value) {
          return value === null || value === void 0 ? NONE : some(value);
        };
        var Optional = {
          some,
          none,
          from
        };
        var nativeSlice = Array.prototype.slice;
        var nativePush = Array.prototype.push;
        var map3 = function(xs, f2) {
          var len = xs.length;
          var r2 = new Array(len);
          for (var i2 = 0; i2 < len; i2++) {
            var x2 = xs[i2];
            r2[i2] = f2(x2, i2);
          }
          return r2;
        };
        var each$1 = function(xs, f2) {
          for (var i2 = 0, len = xs.length; i2 < len; i2++) {
            var x2 = xs[i2];
            f2(x2, i2);
          }
        };
        var filter$1 = function(xs, pred) {
          var r2 = [];
          for (var i2 = 0, len = xs.length; i2 < len; i2++) {
            var x2 = xs[i2];
            if (pred(x2, i2)) {
              r2.push(x2);
            }
          }
          return r2;
        };
        var groupBy = function(xs, f2) {
          if (xs.length === 0) {
            return [];
          } else {
            var wasType = f2(xs[0]);
            var r2 = [];
            var group = [];
            for (var i2 = 0, len = xs.length; i2 < len; i2++) {
              var x2 = xs[i2];
              var type2 = f2(x2);
              if (type2 !== wasType) {
                r2.push(group);
                group = [];
              }
              wasType = type2;
              group.push(x2);
            }
            if (group.length !== 0) {
              r2.push(group);
            }
            return r2;
          }
        };
        var foldl = function(xs, f2, acc) {
          each$1(xs, function(x2, i2) {
            acc = f2(acc, x2, i2);
          });
          return acc;
        };
        var findUntil = function(xs, pred, until) {
          for (var i2 = 0, len = xs.length; i2 < len; i2++) {
            var x2 = xs[i2];
            if (pred(x2, i2)) {
              return Optional.some(x2);
            } else if (until(x2, i2)) {
              break;
            }
          }
          return Optional.none();
        };
        var find$1 = function(xs, pred) {
          return findUntil(xs, pred, never);
        };
        var flatten = function(xs) {
          var r2 = [];
          for (var i2 = 0, len = xs.length; i2 < len; ++i2) {
            if (!isArray2(xs[i2])) {
              throw new Error("Arr.flatten item " + i2 + " was not an array, input: " + xs);
            }
            nativePush.apply(r2, xs[i2]);
          }
          return r2;
        };
        var bind = function(xs, f2) {
          return flatten(map3(xs, f2));
        };
        var reverse = function(xs) {
          var r2 = nativeSlice.call(xs, 0);
          r2.reverse();
          return r2;
        };
        var get$1 = function(xs, i2) {
          return i2 >= 0 && i2 < xs.length ? Optional.some(xs[i2]) : Optional.none();
        };
        var head = function(xs) {
          return get$1(xs, 0);
        };
        var last = function(xs) {
          return get$1(xs, xs.length - 1);
        };
        var findMap = function(arr, f2) {
          for (var i2 = 0; i2 < arr.length; i2++) {
            var r2 = f2(arr[i2], i2);
            if (r2.isSome()) {
              return r2;
            }
          }
          return Optional.none();
        };
        var __assign = function() {
          __assign = Object.assign || function __assign2(t2) {
            for (var s2, i2 = 1, n2 = arguments.length; i2 < n2; i2++) {
              s2 = arguments[i2];
              for (var p2 in s2)
                if (Object.prototype.hasOwnProperty.call(s2, p2))
                  t2[p2] = s2[p2];
            }
            return t2;
          };
          return __assign.apply(this, arguments);
        };
        function __spreadArray(to, from2, pack) {
          if (pack || arguments.length === 2)
            for (var i2 = 0, l2 = from2.length, ar; i2 < l2; i2++) {
              if (ar || !(i2 in from2)) {
                if (!ar)
                  ar = Array.prototype.slice.call(from2, 0, i2);
                ar[i2] = from2[i2];
              }
            }
          return to.concat(ar || Array.prototype.slice.call(from2));
        }
        var cached = function(f2) {
          var called = false;
          var r2;
          return function() {
            var args = [];
            for (var _i2 = 0; _i2 < arguments.length; _i2++) {
              args[_i2] = arguments[_i2];
            }
            if (!called) {
              called = true;
              r2 = f2.apply(null, args);
            }
            return r2;
          };
        };
        var DeviceType = function(os, browser, userAgent, mediaMatch2) {
          var isiPad = os.isiOS() && /ipad/i.test(userAgent) === true;
          var isiPhone = os.isiOS() && !isiPad;
          var isMobile = os.isiOS() || os.isAndroid();
          var isTouch = isMobile || mediaMatch2("(pointer:coarse)");
          var isTablet = isiPad || !isiPhone && isMobile && mediaMatch2("(min-device-width:768px)");
          var isPhone = isiPhone || isMobile && !isTablet;
          var iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false;
          var isDesktop = !isPhone && !isTablet && !iOSwebview;
          return {
            isiPad: constant(isiPad),
            isiPhone: constant(isiPhone),
            isTablet: constant(isTablet),
            isPhone: constant(isPhone),
            isTouch: constant(isTouch),
            isAndroid: os.isAndroid,
            isiOS: os.isiOS,
            isWebView: constant(iOSwebview),
            isDesktop: constant(isDesktop)
          };
        };
        var firstMatch = function(regexes, s2) {
          for (var i2 = 0; i2 < regexes.length; i2++) {
            var x2 = regexes[i2];
            if (x2.test(s2)) {
              return x2;
            }
          }
          return void 0;
        };
        var find = function(regexes, agent) {
          var r2 = firstMatch(regexes, agent);
          if (!r2) {
            return {
              major: 0,
              minor: 0
            };
          }
          var group = function(i2) {
            return Number(agent.replace(r2, "$" + i2));
          };
          return nu$2(group(1), group(2));
        };
        var detect$3 = function(versionRegexes, agent) {
          var cleanedAgent = String(agent).toLowerCase();
          if (versionRegexes.length === 0) {
            return unknown$2();
          }
          return find(versionRegexes, cleanedAgent);
        };
        var unknown$2 = function() {
          return nu$2(0, 0);
        };
        var nu$2 = function(major, minor) {
          return {
            major,
            minor
          };
        };
        var Version = {
          nu: nu$2,
          detect: detect$3,
          unknown: unknown$2
        };
        var detectBrowser$1 = function(browsers2, userAgentData) {
          return findMap(userAgentData.brands, function(uaBrand) {
            var lcBrand = uaBrand.brand.toLowerCase();
            return find$1(browsers2, function(browser) {
              var _a;
              return lcBrand === ((_a = browser.brand) === null || _a === void 0 ? void 0 : _a.toLowerCase());
            }).map(function(info) {
              return {
                current: info.name,
                version: Version.nu(parseInt(uaBrand.version, 10), 0)
              };
            });
          });
        };
        var detect$2 = function(candidates, userAgent) {
          var agent = String(userAgent).toLowerCase();
          return find$1(candidates, function(candidate) {
            return candidate.search(agent);
          });
        };
        var detectBrowser = function(browsers2, userAgent) {
          return detect$2(browsers2, userAgent).map(function(browser) {
            var version2 = Version.detect(browser.versionRegexes, userAgent);
            return {
              current: browser.name,
              version: version2
            };
          });
        };
        var detectOs = function(oses2, userAgent) {
          return detect$2(oses2, userAgent).map(function(os) {
            var version2 = Version.detect(os.versionRegexes, userAgent);
            return {
              current: os.name,
              version: version2
            };
          });
        };
        var contains$1 = function(str, substr) {
          return str.indexOf(substr) !== -1;
        };
        var blank = function(r2) {
          return function(s2) {
            return s2.replace(r2, "");
          };
        };
        var trim = blank(/^\s+|\s+$/g);
        var isNotEmpty = function(s2) {
          return s2.length > 0;
        };
        var isEmpty$1 = function(s2) {
          return !isNotEmpty(s2);
        };
        var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/;
        var checkContains = function(target) {
          return function(uastring) {
            return contains$1(uastring, target);
          };
        };
        var browsers = [
          {
            name: "Edge",
            versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],
            search: function(uastring) {
              return contains$1(uastring, "edge/") && contains$1(uastring, "chrome") && contains$1(uastring, "safari") && contains$1(uastring, "applewebkit");
            }
          },
          {
            name: "Chrome",
            brand: "Chromium",
            versionRegexes: [
              /.*?chrome\/([0-9]+)\.([0-9]+).*/,
              normalVersionRegex
            ],
            search: function(uastring) {
              return contains$1(uastring, "chrome") && !contains$1(uastring, "chromeframe");
            }
          },
          {
            name: "IE",
            versionRegexes: [
              /.*?msie\ ?([0-9]+)\.([0-9]+).*/,
              /.*?rv:([0-9]+)\.([0-9]+).*/
            ],
            search: function(uastring) {
              return contains$1(uastring, "msie") || contains$1(uastring, "trident");
            }
          },
          {
            name: "Opera",
            versionRegexes: [
              normalVersionRegex,
              /.*?opera\/([0-9]+)\.([0-9]+).*/
            ],
            search: checkContains("opera")
          },
          {
            name: "Firefox",
            versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],
            search: checkContains("firefox")
          },
          {
            name: "Safari",
            versionRegexes: [
              normalVersionRegex,
              /.*?cpu os ([0-9]+)_([0-9]+).*/
            ],
            search: function(uastring) {
              return (contains$1(uastring, "safari") || contains$1(uastring, "mobile/")) && contains$1(uastring, "applewebkit");
            }
          }
        ];
        var oses = [
          {
            name: "Windows",
            search: checkContains("win"),
            versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]
          },
          {
            name: "iOS",
            search: function(uastring) {
              return contains$1(uastring, "iphone") || contains$1(uastring, "ipad");
            },
            versionRegexes: [
              /.*?version\/\ ?([0-9]+)\.([0-9]+).*/,
              /.*cpu os ([0-9]+)_([0-9]+).*/,
              /.*cpu iphone os ([0-9]+)_([0-9]+).*/
            ]
          },
          {
            name: "Android",
            search: checkContains("android"),
            versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/]
          },
          {
            name: "OSX",
            search: checkContains("mac os x"),
            versionRegexes: [/.*?mac\ os\ x\ ?([0-9]+)_([0-9]+).*/]
          },
          {
            name: "Linux",
            search: checkContains("linux"),
            versionRegexes: []
          },
          {
            name: "Solaris",
            search: checkContains("sunos"),
            versionRegexes: []
          },
          {
            name: "FreeBSD",
            search: checkContains("freebsd"),
            versionRegexes: []
          },
          {
            name: "ChromeOS",
            search: checkContains("cros"),
            versionRegexes: [/.*?chrome\/([0-9]+)\.([0-9]+).*/]
          }
        ];
        var PlatformInfo = {
          browsers: constant(browsers),
          oses: constant(oses)
        };
        var edge = "Edge";
        var chrome = "Chrome";
        var ie2 = "IE";
        var opera = "Opera";
        var firefox = "Firefox";
        var safari = "Safari";
        var unknown$1 = function() {
          return nu$1({
            current: void 0,
            version: Version.unknown()
          });
        };
        var nu$1 = function(info) {
          var current = info.current;
          var version2 = info.version;
          var isBrowser = function(name2) {
            return function() {
              return current === name2;
            };
          };
          return {
            current,
            version: version2,
            isEdge: isBrowser(edge),
            isChrome: isBrowser(chrome),
            isIE: isBrowser(ie2),
            isOpera: isBrowser(opera),
            isFirefox: isBrowser(firefox),
            isSafari: isBrowser(safari)
          };
        };
        var Browser = {
          unknown: unknown$1,
          nu: nu$1,
          edge: constant(edge),
          chrome: constant(chrome),
          ie: constant(ie2),
          opera: constant(opera),
          firefox: constant(firefox),
          safari: constant(safari)
        };
        var windows = "Windows";
        var ios = "iOS";
        var android = "Android";
        var linux = "Linux";
        var osx = "OSX";
        var solaris = "Solaris";
        var freebsd = "FreeBSD";
        var chromeos = "ChromeOS";
        var unknown = function() {
          return nu({
            current: void 0,
            version: Version.unknown()
          });
        };
        var nu = function(info) {
          var current = info.current;
          var version2 = info.version;
          var isOS = function(name2) {
            return function() {
              return current === name2;
            };
          };
          return {
            current,
            version: version2,
            isWindows: isOS(windows),
            isiOS: isOS(ios),
            isAndroid: isOS(android),
            isOSX: isOS(osx),
            isLinux: isOS(linux),
            isSolaris: isOS(solaris),
            isFreeBSD: isOS(freebsd),
            isChromeOS: isOS(chromeos)
          };
        };
        var OperatingSystem = {
          unknown,
          nu,
          windows: constant(windows),
          ios: constant(ios),
          android: constant(android),
          linux: constant(linux),
          osx: constant(osx),
          solaris: constant(solaris),
          freebsd: constant(freebsd),
          chromeos: constant(chromeos)
        };
        var detect$1 = function(userAgent, userAgentDataOpt, mediaMatch2) {
          var browsers2 = PlatformInfo.browsers();
          var oses2 = PlatformInfo.oses();
          var browser = userAgentDataOpt.bind(function(userAgentData) {
            return detectBrowser$1(browsers2, userAgentData);
          }).orThunk(function() {
            return detectBrowser(browsers2, userAgent);
          }).fold(Browser.unknown, Browser.nu);
          var os = detectOs(oses2, userAgent).fold(OperatingSystem.unknown, OperatingSystem.nu);
          var deviceType = DeviceType(os, browser, userAgent, mediaMatch2);
          return {
            browser,
            os,
            deviceType
          };
        };
        var PlatformDetection = { detect: detect$1 };
        var mediaMatch = function(query) {
          return window.matchMedia(query).matches;
        };
        var platform = cached(function() {
          return PlatformDetection.detect(navigator.userAgent, Optional.from(navigator.userAgentData), mediaMatch);
        });
        var detect = function() {
          return platform();
        };
        var compareDocumentPosition = function(a2, b2, match2) {
          return (a2.compareDocumentPosition(b2) & match2) !== 0;
        };
        var documentPositionContainedBy = function(a2, b2) {
          return compareDocumentPosition(a2, b2, Node.DOCUMENT_POSITION_CONTAINED_BY);
        };
        var ELEMENT = 1;
        var fromHtml = function(html, scope) {
          var doc = scope || document;
          var div = doc.createElement("div");
          div.innerHTML = html;
          if (!div.hasChildNodes() || div.childNodes.length > 1) {
            console.error("HTML does not have a single root node", html);
            throw new Error("HTML must have a single root node");
          }
          return fromDom(div.childNodes[0]);
        };
        var fromTag = function(tag, scope) {
          var doc = scope || document;
          var node = doc.createElement(tag);
          return fromDom(node);
        };
        var fromText = function(text, scope) {
          var doc = scope || document;
          var node = doc.createTextNode(text);
          return fromDom(node);
        };
        var fromDom = function(node) {
          if (node === null || node === void 0) {
            throw new Error("Node cannot be null or undefined");
          }
          return { dom: node };
        };
        var fromPoint = function(docElm, x2, y2) {
          return Optional.from(docElm.dom.elementFromPoint(x2, y2)).map(fromDom);
        };
        var SugarElement = {
          fromHtml,
          fromTag,
          fromText,
          fromDom,
          fromPoint
        };
        var is$2 = function(element, selector) {
          var dom = element.dom;
          if (dom.nodeType !== ELEMENT) {
            return false;
          } else {
            var elem = dom;
            if (elem.matches !== void 0) {
              return elem.matches(selector);
            } else if (elem.msMatchesSelector !== void 0) {
              return elem.msMatchesSelector(selector);
            } else if (elem.webkitMatchesSelector !== void 0) {
              return elem.webkitMatchesSelector(selector);
            } else if (elem.mozMatchesSelector !== void 0) {
              return elem.mozMatchesSelector(selector);
            } else {
              throw new Error("Browser lacks native selectors");
            }
          }
        };
        var eq2 = function(e1, e2) {
          return e1.dom === e2.dom;
        };
        var regularContains = function(e1, e2) {
          var d1 = e1.dom;
          var d2 = e2.dom;
          return d1 === d2 ? false : d1.contains(d2);
        };
        var ieContains = function(e1, e2) {
          return documentPositionContainedBy(e1.dom, e2.dom);
        };
        var contains2 = function(e1, e2) {
          return detect().browser.isIE() ? ieContains(e1, e2) : regularContains(e1, e2);
        };
        var is$1 = is$2;
        var global$6 = tinymce.util.Tools.resolve("tinymce.dom.RangeUtils");
        var global$5 = tinymce.util.Tools.resolve("tinymce.dom.TreeWalker");
        var global$4 = tinymce.util.Tools.resolve("tinymce.util.VK");
        var keys = Object.keys;
        var each2 = function(obj, f2) {
          var props = keys(obj);
          for (var k2 = 0, len = props.length; k2 < len; k2++) {
            var i2 = props[k2];
            var x2 = obj[i2];
            f2(x2, i2);
          }
        };
        var objAcc = function(r2) {
          return function(x2, i2) {
            r2[i2] = x2;
          };
        };
        var internalFilter = function(obj, pred, onTrue, onFalse) {
          var r2 = {};
          each2(obj, function(x2, i2) {
            (pred(x2, i2) ? onTrue : onFalse)(x2, i2);
          });
          return r2;
        };
        var filter = function(obj, pred) {
          var t2 = {};
          internalFilter(obj, pred, objAcc(t2), noop3);
          return t2;
        };
        typeof window !== "undefined" ? window : Function("return this;")();
        var name = function(element) {
          var r2 = element.dom.nodeName;
          return r2.toLowerCase();
        };
        var type = function(element) {
          return element.dom.nodeType;
        };
        var isType = function(t2) {
          return function(element) {
            return type(element) === t2;
          };
        };
        var isElement3 = isType(ELEMENT);
        var isTag = function(tag) {
          return function(e2) {
            return isElement3(e2) && name(e2) === tag;
          };
        };
        var rawSet = function(dom, key, value) {
          if (isString(value) || isBoolean(value) || isNumber2(value)) {
            dom.setAttribute(key, value + "");
          } else {
            console.error("Invalid call to Attribute.set. Key ", key, ":: Value ", value, ":: Element ", dom);
            throw new Error("Attribute value was not simple");
          }
        };
        var setAll = function(element, attrs) {
          var dom = element.dom;
          each2(attrs, function(v2, k2) {
            rawSet(dom, k2, v2);
          });
        };
        var clone$12 = function(element) {
          return foldl(element.dom.attributes, function(acc, attr) {
            acc[attr.name] = attr.value;
            return acc;
          }, {});
        };
        var parent = function(element) {
          return Optional.from(element.dom.parentNode).map(SugarElement.fromDom);
        };
        var children = function(element) {
          return map3(element.dom.childNodes, SugarElement.fromDom);
        };
        var child = function(element, index) {
          var cs = element.dom.childNodes;
          return Optional.from(cs[index]).map(SugarElement.fromDom);
        };
        var firstChild = function(element) {
          return child(element, 0);
        };
        var lastChild = function(element) {
          return child(element, element.dom.childNodes.length - 1);
        };
        var before$1 = function(marker, element) {
          var parent$1 = parent(marker);
          parent$1.each(function(v2) {
            v2.dom.insertBefore(element.dom, marker.dom);
          });
        };
        var append$1 = function(parent2, element) {
          parent2.dom.appendChild(element.dom);
        };
        var before = function(marker, elements2) {
          each$1(elements2, function(x2) {
            before$1(marker, x2);
          });
        };
        var append = function(parent2, elements2) {
          each$1(elements2, function(x2) {
            append$1(parent2, x2);
          });
        };
        var remove = function(element) {
          var dom = element.dom;
          if (dom.parentNode !== null) {
            dom.parentNode.removeChild(dom);
          }
        };
        var clone2 = function(original, isDeep) {
          return SugarElement.fromDom(original.dom.cloneNode(isDeep));
        };
        var deep = function(original) {
          return clone2(original, true);
        };
        var shallowAs = function(original, tag) {
          var nu2 = SugarElement.fromTag(tag);
          var attributes = clone$12(original);
          setAll(nu2, attributes);
          return nu2;
        };
        var mutate = function(original, tag) {
          var nu2 = shallowAs(original, tag);
          before$1(original, nu2);
          var children$1 = children(original);
          append(nu2, children$1);
          remove(original);
          return nu2;
        };
        var global$3 = tinymce.util.Tools.resolve("tinymce.dom.DOMUtils");
        var global$2 = tinymce.util.Tools.resolve("tinymce.util.Tools");
        var matchNodeName = function(name2) {
          return function(node) {
            return node && node.nodeName.toLowerCase() === name2;
          };
        };
        var matchNodeNames = function(regex) {
          return function(node) {
            return node && regex.test(node.nodeName);
          };
        };
        var isTextNode = function(node) {
          return node && node.nodeType === 3;
        };
        var isListNode = matchNodeNames(/^(OL|UL|DL)$/);
        var isOlUlNode = matchNodeNames(/^(OL|UL)$/);
        var isOlNode = matchNodeName("ol");
        var isListItemNode = matchNodeNames(/^(LI|DT|DD)$/);
        var isDlItemNode = matchNodeNames(/^(DT|DD)$/);
        var isTableCellNode = matchNodeNames(/^(TH|TD)$/);
        var isBr = matchNodeName("br");
        var isFirstChild = function(node) {
          return node.parentNode.firstChild === node;
        };
        var isTextBlock = function(editor, node) {
          return node && !!editor.schema.getTextBlockElements()[node.nodeName];
        };
        var isBlock = function(node, blockElements) {
          return node && node.nodeName in blockElements;
        };
        var isBogusBr = function(dom, node) {
          if (!isBr(node)) {
            return false;
          }
          return dom.isBlock(node.nextSibling) && !isBr(node.previousSibling);
        };
        var isEmpty = function(dom, elm, keepBookmarks) {
          var empty = dom.isEmpty(elm);
          if (keepBookmarks && dom.select("span[data-mce-type=bookmark]", elm).length > 0) {
            return false;
          }
          return empty;
        };
        var isChildOfBody = function(dom, elm) {
          return dom.isChildOf(elm, dom.getRoot());
        };
        var shouldIndentOnTab = function(editor) {
          return editor.getParam("lists_indent_on_tab", true);
        };
        var getForcedRootBlock = function(editor) {
          var block = editor.getParam("forced_root_block", "p");
          if (block === false) {
            return "";
          } else if (block === true) {
            return "p";
          } else {
            return block;
          }
        };
        var getForcedRootBlockAttrs = function(editor) {
          return editor.getParam("forced_root_block_attrs", {});
        };
        var createTextBlock = function(editor, contentNode) {
          var dom = editor.dom;
          var blockElements = editor.schema.getBlockElements();
          var fragment = dom.createFragment();
          var blockName = getForcedRootBlock(editor);
          var node, textBlock, hasContentNode;
          if (blockName) {
            textBlock = dom.create(blockName);
            if (textBlock.tagName === blockName.toUpperCase()) {
              dom.setAttribs(textBlock, getForcedRootBlockAttrs(editor));
            }
            if (!isBlock(contentNode.firstChild, blockElements)) {
              fragment.appendChild(textBlock);
            }
          }
          if (contentNode) {
            while (node = contentNode.firstChild) {
              var nodeName = node.nodeName;
              if (!hasContentNode && (nodeName !== "SPAN" || node.getAttribute("data-mce-type") !== "bookmark")) {
                hasContentNode = true;
              }
              if (isBlock(node, blockElements)) {
                fragment.appendChild(node);
                textBlock = null;
              } else {
                if (blockName) {
                  if (!textBlock) {
                    textBlock = dom.create(blockName);
                    fragment.appendChild(textBlock);
                  }
                  textBlock.appendChild(node);
                } else {
                  fragment.appendChild(node);
                }
              }
            }
          }
          if (!blockName) {
            fragment.appendChild(dom.create("br"));
          } else {
            if (!hasContentNode) {
              textBlock.appendChild(dom.create("br", { "data-mce-bogus": "1" }));
            }
          }
          return fragment;
        };
        var DOM$2 = global$3.DOM;
        var splitList = function(editor, list, li2) {
          var removeAndKeepBookmarks = function(targetNode) {
            global$2.each(bookmarks, function(node2) {
              targetNode.parentNode.insertBefore(node2, li2.parentNode);
            });
            DOM$2.remove(targetNode);
          };
          var bookmarks = DOM$2.select('span[data-mce-type="bookmark"]', list);
          var newBlock = createTextBlock(editor, li2);
          var tmpRng = DOM$2.createRng();
          tmpRng.setStartAfter(li2);
          tmpRng.setEndAfter(list);
          var fragment = tmpRng.extractContents();
          for (var node = fragment.firstChild; node; node = node.firstChild) {
            if (node.nodeName === "LI" && editor.dom.isEmpty(node)) {
              DOM$2.remove(node);
              break;
            }
          }
          if (!editor.dom.isEmpty(fragment)) {
            DOM$2.insertAfter(fragment, list);
          }
          DOM$2.insertAfter(newBlock, list);
          if (isEmpty(editor.dom, li2.parentNode)) {
            removeAndKeepBookmarks(li2.parentNode);
          }
          DOM$2.remove(li2);
          if (isEmpty(editor.dom, list)) {
            DOM$2.remove(list);
          }
        };
        var isDescriptionDetail = isTag("dd");
        var isDescriptionTerm = isTag("dt");
        var outdentDlItem = function(editor, item) {
          if (isDescriptionDetail(item)) {
            mutate(item, "dt");
          } else if (isDescriptionTerm(item)) {
            parent(item).each(function(dl) {
              return splitList(editor, dl.dom, item.dom);
            });
          }
        };
        var indentDlItem = function(item) {
          if (isDescriptionTerm(item)) {
            mutate(item, "dd");
          }
        };
        var dlIndentation = function(editor, indentation, dlItems) {
          if (indentation === "Indent") {
            each$1(dlItems, indentDlItem);
          } else {
            each$1(dlItems, function(item) {
              return outdentDlItem(editor, item);
            });
          }
        };
        var getNormalizedPoint = function(container, offset2) {
          if (isTextNode(container)) {
            return {
              container,
              offset: offset2
            };
          }
          var node = global$6.getNode(container, offset2);
          if (isTextNode(node)) {
            return {
              container: node,
              offset: offset2 >= container.childNodes.length ? node.data.length : 0
            };
          } else if (node.previousSibling && isTextNode(node.previousSibling)) {
            return {
              container: node.previousSibling,
              offset: node.previousSibling.data.length
            };
          } else if (node.nextSibling && isTextNode(node.nextSibling)) {
            return {
              container: node.nextSibling,
              offset: 0
            };
          }
          return {
            container,
            offset: offset2
          };
        };
        var normalizeRange = function(rng) {
          var outRng = rng.cloneRange();
          var rangeStart = getNormalizedPoint(rng.startContainer, rng.startOffset);
          outRng.setStart(rangeStart.container, rangeStart.offset);
          var rangeEnd = getNormalizedPoint(rng.endContainer, rng.endOffset);
          outRng.setEnd(rangeEnd.container, rangeEnd.offset);
          return outRng;
        };
        var global$1 = tinymce.util.Tools.resolve("tinymce.dom.DomQuery");
        var getParentList = function(editor, node) {
          var selectionStart = node || editor.selection.getStart(true);
          return editor.dom.getParent(selectionStart, "OL,UL,DL", getClosestListRootElm(editor, selectionStart));
        };
        var isParentListSelected = function(parentList, selectedBlocks) {
          return parentList && selectedBlocks.length === 1 && selectedBlocks[0] === parentList;
        };
        var findSubLists = function(parentList) {
          return filter$1(parentList.querySelectorAll("ol,ul,dl"), isListNode);
        };
        var getSelectedSubLists = function(editor) {
          var parentList = getParentList(editor);
          var selectedBlocks = editor.selection.getSelectedBlocks();
          if (isParentListSelected(parentList, selectedBlocks)) {
            return findSubLists(parentList);
          } else {
            return filter$1(selectedBlocks, function(elm) {
              return isListNode(elm) && parentList !== elm;
            });
          }
        };
        var findParentListItemsNodes = function(editor, elms) {
          var listItemsElms = global$2.map(elms, function(elm) {
            var parentLi = editor.dom.getParent(elm, "li,dd,dt", getClosestListRootElm(editor, elm));
            return parentLi ? parentLi : elm;
          });
          return global$1.unique(listItemsElms);
        };
        var getSelectedListItems = function(editor) {
          var selectedBlocks = editor.selection.getSelectedBlocks();
          return filter$1(findParentListItemsNodes(editor, selectedBlocks), isListItemNode);
        };
        var getSelectedDlItems = function(editor) {
          return filter$1(getSelectedListItems(editor), isDlItemNode);
        };
        var getClosestListRootElm = function(editor, elm) {
          var parentTableCell = editor.dom.getParents(elm, "TD,TH");
          return parentTableCell.length > 0 ? parentTableCell[0] : editor.getBody();
        };
        var findLastParentListNode = function(editor, elm) {
          var parentLists = editor.dom.getParents(elm, "ol,ul", getClosestListRootElm(editor, elm));
          return last(parentLists);
        };
        var getSelectedLists = function(editor) {
          var firstList = findLastParentListNode(editor, editor.selection.getStart());
          var subsequentLists = filter$1(editor.selection.getSelectedBlocks(), isOlUlNode);
          return firstList.toArray().concat(subsequentLists);
        };
        var getSelectedListRoots = function(editor) {
          var selectedLists = getSelectedLists(editor);
          return getUniqueListRoots(editor, selectedLists);
        };
        var getUniqueListRoots = function(editor, lists) {
          var listRoots = map3(lists, function(list) {
            return findLastParentListNode(editor, list).getOr(list);
          });
          return global$1.unique(listRoots);
        };
        var is = function(lhs, rhs, comparator) {
          if (comparator === void 0) {
            comparator = tripleEquals;
          }
          return lhs.exists(function(left2) {
            return comparator(left2, rhs);
          });
        };
        var lift2 = function(oa, ob, f2) {
          return oa.isSome() && ob.isSome() ? Optional.some(f2(oa.getOrDie(), ob.getOrDie())) : Optional.none();
        };
        var fromElements = function(elements2, scope) {
          var doc = scope || document;
          var fragment = doc.createDocumentFragment();
          each$1(elements2, function(element) {
            fragment.appendChild(element.dom);
          });
          return SugarElement.fromDom(fragment);
        };
        var fireListEvent = function(editor, action, element) {
          return editor.fire("ListMutation", {
            action,
            element
          });
        };
        var isSupported = function(dom) {
          return dom.style !== void 0 && isFunction2(dom.style.getPropertyValue);
        };
        var internalSet = function(dom, property, value) {
          if (!isString(value)) {
            console.error("Invalid call to CSS.set. Property ", property, ":: Value ", value, ":: Element ", dom);
            throw new Error("CSS value must be a string: " + value);
          }
          if (isSupported(dom)) {
            dom.style.setProperty(property, value);
          }
        };
        var set2 = function(element, property, value) {
          var dom = element.dom;
          internalSet(dom, property, value);
        };
        var joinSegment = function(parent2, child2) {
          append$1(parent2.item, child2.list);
        };
        var joinSegments = function(segments) {
          for (var i2 = 1; i2 < segments.length; i2++) {
            joinSegment(segments[i2 - 1], segments[i2]);
          }
        };
        var appendSegments = function(head$1, tail) {
          lift2(last(head$1), head(tail), joinSegment);
        };
        var createSegment = function(scope, listType) {
          var segment = {
            list: SugarElement.fromTag(listType, scope),
            item: SugarElement.fromTag("li", scope)
          };
          append$1(segment.list, segment.item);
          return segment;
        };
        var createSegments = function(scope, entry, size) {
          var segments = [];
          for (var i2 = 0; i2 < size; i2++) {
            segments.push(createSegment(scope, entry.listType));
          }
          return segments;
        };
        var populateSegments = function(segments, entry) {
          for (var i2 = 0; i2 < segments.length - 1; i2++) {
            set2(segments[i2].item, "list-style-type", "none");
          }
          last(segments).each(function(segment) {
            setAll(segment.list, entry.listAttributes);
            setAll(segment.item, entry.itemAttributes);
            append(segment.item, entry.content);
          });
        };
        var normalizeSegment2 = function(segment, entry) {
          if (name(segment.list) !== entry.listType) {
            segment.list = mutate(segment.list, entry.listType);
          }
          setAll(segment.list, entry.listAttributes);
        };
        var createItem = function(scope, attr, content) {
          var item = SugarElement.fromTag("li", scope);
          setAll(item, attr);
          append(item, content);
          return item;
        };
        var appendItem = function(segment, item) {
          append$1(segment.list, item);
          segment.item = item;
        };
        var writeShallow = function(scope, cast, entry) {
          var newCast = cast.slice(0, entry.depth);
          last(newCast).each(function(segment) {
            var item = createItem(scope, entry.itemAttributes, entry.content);
            appendItem(segment, item);
            normalizeSegment2(segment, entry);
          });
          return newCast;
        };
        var writeDeep = function(scope, cast, entry) {
          var segments = createSegments(scope, entry, entry.depth - cast.length);
          joinSegments(segments);
          populateSegments(segments, entry);
          appendSegments(cast, segments);
          return cast.concat(segments);
        };
        var composeList = function(scope, entries) {
          var cast = foldl(entries, function(cast2, entry) {
            return entry.depth > cast2.length ? writeDeep(scope, cast2, entry) : writeShallow(scope, cast2, entry);
          }, []);
          return head(cast).map(function(segment) {
            return segment.list;
          });
        };
        var isList = function(el) {
          return is$1(el, "OL,UL");
        };
        var hasFirstChildList = function(el) {
          return firstChild(el).exists(isList);
        };
        var hasLastChildList = function(el) {
          return lastChild(el).exists(isList);
        };
        var isIndented = function(entry) {
          return entry.depth > 0;
        };
        var isSelected = function(entry) {
          return entry.isSelected;
        };
        var cloneItemContent = function(li2) {
          var children$1 = children(li2);
          var content = hasLastChildList(li2) ? children$1.slice(0, -1) : children$1;
          return map3(content, deep);
        };
        var createEntry = function(li2, depth, isSelected2) {
          return parent(li2).filter(isElement3).map(function(list) {
            return {
              depth,
              dirty: false,
              isSelected: isSelected2,
              content: cloneItemContent(li2),
              itemAttributes: clone$12(li2),
              listAttributes: clone$12(list),
              listType: name(list)
            };
          });
        };
        var indentEntry = function(indentation, entry) {
          switch (indentation) {
            case "Indent":
              entry.depth++;
              break;
            case "Outdent":
              entry.depth--;
              break;
            case "Flatten":
              entry.depth = 0;
          }
          entry.dirty = true;
        };
        var cloneListProperties = function(target, source) {
          target.listType = source.listType;
          target.listAttributes = __assign({}, source.listAttributes);
        };
        var cleanListProperties = function(entry) {
          entry.listAttributes = filter(entry.listAttributes, function(_value, key) {
            return key !== "start";
          });
        };
        var closestSiblingEntry = function(entries, start4) {
          var depth = entries[start4].depth;
          var matches = function(entry) {
            return entry.depth === depth && !entry.dirty;
          };
          var until = function(entry) {
            return entry.depth < depth;
          };
          return findUntil(reverse(entries.slice(0, start4)), matches, until).orThunk(function() {
            return findUntil(entries.slice(start4 + 1), matches, until);
          });
        };
        var normalizeEntries = function(entries) {
          each$1(entries, function(entry, i2) {
            closestSiblingEntry(entries, i2).fold(function() {
              if (entry.dirty) {
                cleanListProperties(entry);
              }
            }, function(matchingEntry) {
              return cloneListProperties(entry, matchingEntry);
            });
          });
          return entries;
        };
        var Cell = function(initial) {
          var value = initial;
          var get2 = function() {
            return value;
          };
          var set3 = function(v2) {
            value = v2;
          };
          return {
            get: get2,
            set: set3
          };
        };
        var parseItem = function(depth, itemSelection, selectionState, item) {
          return firstChild(item).filter(isList).fold(function() {
            itemSelection.each(function(selection) {
              if (eq2(selection.start, item)) {
                selectionState.set(true);
              }
            });
            var currentItemEntry = createEntry(item, depth, selectionState.get());
            itemSelection.each(function(selection) {
              if (eq2(selection.end, item)) {
                selectionState.set(false);
              }
            });
            var childListEntries = lastChild(item).filter(isList).map(function(list) {
              return parseList(depth, itemSelection, selectionState, list);
            }).getOr([]);
            return currentItemEntry.toArray().concat(childListEntries);
          }, function(list) {
            return parseList(depth, itemSelection, selectionState, list);
          });
        };
        var parseList = function(depth, itemSelection, selectionState, list) {
          return bind(children(list), function(element) {
            var parser = isList(element) ? parseList : parseItem;
            var newDepth = depth + 1;
            return parser(newDepth, itemSelection, selectionState, element);
          });
        };
        var parseLists = function(lists, itemSelection) {
          var selectionState = Cell(false);
          var initialDepth = 0;
          return map3(lists, function(list) {
            return {
              sourceList: list,
              entries: parseList(initialDepth, itemSelection, selectionState, list)
            };
          });
        };
        var outdentedComposer = function(editor, entries) {
          var normalizedEntries = normalizeEntries(entries);
          return map3(normalizedEntries, function(entry) {
            var content = fromElements(entry.content);
            return SugarElement.fromDom(createTextBlock(editor, content.dom));
          });
        };
        var indentedComposer = function(editor, entries) {
          var normalizedEntries = normalizeEntries(entries);
          return composeList(editor.contentDocument, normalizedEntries).toArray();
        };
        var composeEntries = function(editor, entries) {
          return bind(groupBy(entries, isIndented), function(entries2) {
            var groupIsIndented = head(entries2).exists(isIndented);
            return groupIsIndented ? indentedComposer(editor, entries2) : outdentedComposer(editor, entries2);
          });
        };
        var indentSelectedEntries = function(entries, indentation) {
          each$1(filter$1(entries, isSelected), function(entry) {
            return indentEntry(indentation, entry);
          });
        };
        var getItemSelection = function(editor) {
          var selectedListItems = map3(getSelectedListItems(editor), SugarElement.fromDom);
          return lift2(find$1(selectedListItems, not(hasFirstChildList)), find$1(reverse(selectedListItems), not(hasFirstChildList)), function(start4, end2) {
            return {
              start: start4,
              end: end2
            };
          });
        };
        var listIndentation = function(editor, lists, indentation) {
          var entrySets = parseLists(lists, getItemSelection(editor));
          each$1(entrySets, function(entrySet) {
            indentSelectedEntries(entrySet.entries, indentation);
            var composedLists = composeEntries(editor, entrySet.entries);
            each$1(composedLists, function(composedList) {
              fireListEvent(editor, indentation === "Indent" ? "IndentList" : "OutdentList", composedList.dom);
            });
            before(entrySet.sourceList, composedLists);
            remove(entrySet.sourceList);
          });
        };
        var selectionIndentation = function(editor, indentation) {
          var lists = map3(getSelectedListRoots(editor), SugarElement.fromDom);
          var dlItems = map3(getSelectedDlItems(editor), SugarElement.fromDom);
          var isHandled = false;
          if (lists.length || dlItems.length) {
            var bookmark = editor.selection.getBookmark();
            listIndentation(editor, lists, indentation);
            dlIndentation(editor, indentation, dlItems);
            editor.selection.moveToBookmark(bookmark);
            editor.selection.setRng(normalizeRange(editor.selection.getRng()));
            editor.nodeChanged();
            isHandled = true;
          }
          return isHandled;
        };
        var indentListSelection = function(editor) {
          return selectionIndentation(editor, "Indent");
        };
        var outdentListSelection = function(editor) {
          return selectionIndentation(editor, "Outdent");
        };
        var flattenListSelection = function(editor) {
          return selectionIndentation(editor, "Flatten");
        };
        var global2 = tinymce.util.Tools.resolve("tinymce.dom.BookmarkManager");
        var DOM$1 = global$3.DOM;
        var createBookmark = function(rng) {
          var bookmark = {};
          var setupEndPoint = function(start4) {
            var container = rng[start4 ? "startContainer" : "endContainer"];
            var offset2 = rng[start4 ? "startOffset" : "endOffset"];
            if (container.nodeType === 1) {
              var offsetNode = DOM$1.create("span", { "data-mce-type": "bookmark" });
              if (container.hasChildNodes()) {
                offset2 = Math.min(offset2, container.childNodes.length - 1);
                if (start4) {
                  container.insertBefore(offsetNode, container.childNodes[offset2]);
                } else {
                  DOM$1.insertAfter(offsetNode, container.childNodes[offset2]);
                }
              } else {
                container.appendChild(offsetNode);
              }
              container = offsetNode;
              offset2 = 0;
            }
            bookmark[start4 ? "startContainer" : "endContainer"] = container;
            bookmark[start4 ? "startOffset" : "endOffset"] = offset2;
          };
          setupEndPoint(true);
          if (!rng.collapsed) {
            setupEndPoint();
          }
          return bookmark;
        };
        var resolveBookmark = function(bookmark) {
          var restoreEndPoint = function(start4) {
            var node;
            var nodeIndex = function(container2) {
              var node2 = container2.parentNode.firstChild, idx = 0;
              while (node2) {
                if (node2 === container2) {
                  return idx;
                }
                if (node2.nodeType !== 1 || node2.getAttribute("data-mce-type") !== "bookmark") {
                  idx++;
                }
                node2 = node2.nextSibling;
              }
              return -1;
            };
            var container = node = bookmark[start4 ? "startContainer" : "endContainer"];
            var offset2 = bookmark[start4 ? "startOffset" : "endOffset"];
            if (!container) {
              return;
            }
            if (container.nodeType === 1) {
              offset2 = nodeIndex(container);
              container = container.parentNode;
              DOM$1.remove(node);
              if (!container.hasChildNodes() && DOM$1.isBlock(container)) {
                container.appendChild(DOM$1.create("br"));
              }
            }
            bookmark[start4 ? "startContainer" : "endContainer"] = container;
            bookmark[start4 ? "startOffset" : "endOffset"] = offset2;
          };
          restoreEndPoint(true);
          restoreEndPoint();
          var rng = DOM$1.createRng();
          rng.setStart(bookmark.startContainer, bookmark.startOffset);
          if (bookmark.endContainer) {
            rng.setEnd(bookmark.endContainer, bookmark.endOffset);
          }
          return normalizeRange(rng);
        };
        var listToggleActionFromListName = function(listName) {
          switch (listName) {
            case "UL":
              return "ToggleUlList";
            case "OL":
              return "ToggleOlList";
            case "DL":
              return "ToggleDLList";
          }
        };
        var isCustomList = function(list) {
          return /\btox\-/.test(list.className);
        };
        var listState = function(editor, listName, activate) {
          var nodeChangeHandler = function(e2) {
            var inList = findUntil(e2.parents, isListNode, isTableCellNode).filter(function(list) {
              return list.nodeName === listName && !isCustomList(list);
            }).isSome();
            activate(inList);
          };
          var parents = editor.dom.getParents(editor.selection.getNode());
          nodeChangeHandler({ parents });
          editor.on("NodeChange", nodeChangeHandler);
          return function() {
            return editor.off("NodeChange", nodeChangeHandler);
          };
        };
        var updateListStyle = function(dom, el, detail) {
          var type2 = detail["list-style-type"] ? detail["list-style-type"] : null;
          dom.setStyle(el, "list-style-type", type2);
        };
        var setAttribs = function(elm, attrs) {
          global$2.each(attrs, function(value, key) {
            elm.setAttribute(key, value);
          });
        };
        var updateListAttrs = function(dom, el, detail) {
          setAttribs(el, detail["list-attributes"]);
          global$2.each(dom.select("li", el), function(li2) {
            setAttribs(li2, detail["list-item-attributes"]);
          });
        };
        var updateListWithDetails = function(dom, el, detail) {
          updateListStyle(dom, el, detail);
          updateListAttrs(dom, el, detail);
        };
        var removeStyles = function(dom, element, styles) {
          global$2.each(styles, function(style) {
            var _a;
            return dom.setStyle(element, (_a = {}, _a[style] = "", _a));
          });
        };
        var getEndPointNode = function(editor, rng, start4, root) {
          var container = rng[start4 ? "startContainer" : "endContainer"];
          var offset2 = rng[start4 ? "startOffset" : "endOffset"];
          if (container.nodeType === 1) {
            container = container.childNodes[Math.min(offset2, container.childNodes.length - 1)] || container;
          }
          if (!start4 && isBr(container.nextSibling)) {
            container = container.nextSibling;
          }
          while (container.parentNode !== root) {
            if (isTextBlock(editor, container)) {
              return container;
            }
            if (/^(TD|TH)$/.test(container.parentNode.nodeName)) {
              return container;
            }
            container = container.parentNode;
          }
          return container;
        };
        var getSelectedTextBlocks = function(editor, rng, root) {
          var textBlocks = [];
          var dom = editor.dom;
          var startNode = getEndPointNode(editor, rng, true, root);
          var endNode = getEndPointNode(editor, rng, false, root);
          var block;
          var siblings = [];
          for (var node = startNode; node; node = node.nextSibling) {
            siblings.push(node);
            if (node === endNode) {
              break;
            }
          }
          global$2.each(siblings, function(node2) {
            if (isTextBlock(editor, node2)) {
              textBlocks.push(node2);
              block = null;
              return;
            }
            if (dom.isBlock(node2) || isBr(node2)) {
              if (isBr(node2)) {
                dom.remove(node2);
              }
              block = null;
              return;
            }
            var nextSibling = node2.nextSibling;
            if (global2.isBookmarkNode(node2)) {
              if (isListNode(nextSibling) || isTextBlock(editor, nextSibling) || !nextSibling && node2.parentNode === root) {
                block = null;
                return;
              }
            }
            if (!block) {
              block = dom.create("p");
              node2.parentNode.insertBefore(block, node2);
              textBlocks.push(block);
            }
            block.appendChild(node2);
          });
          return textBlocks;
        };
        var hasCompatibleStyle = function(dom, sib, detail) {
          var sibStyle = dom.getStyle(sib, "list-style-type");
          var detailStyle = detail ? detail["list-style-type"] : "";
          detailStyle = detailStyle === null ? "" : detailStyle;
          return sibStyle === detailStyle;
        };
        var applyList = function(editor, listName, detail) {
          var rng = editor.selection.getRng();
          var listItemName = "LI";
          var root = getClosestListRootElm(editor, editor.selection.getStart(true));
          var dom = editor.dom;
          if (dom.getContentEditable(editor.selection.getNode()) === "false") {
            return;
          }
          listName = listName.toUpperCase();
          if (listName === "DL") {
            listItemName = "DT";
          }
          var bookmark = createBookmark(rng);
          var selectedTextBlocks = getSelectedTextBlocks(editor, rng, root);
          global$2.each(selectedTextBlocks, function(block) {
            var listBlock;
            var sibling = block.previousSibling;
            var parent2 = block.parentNode;
            if (!isListItemNode(parent2)) {
              if (sibling && isListNode(sibling) && sibling.nodeName === listName && hasCompatibleStyle(dom, sibling, detail)) {
                listBlock = sibling;
                block = dom.rename(block, listItemName);
                sibling.appendChild(block);
              } else {
                listBlock = dom.create(listName);
                block.parentNode.insertBefore(listBlock, block);
                listBlock.appendChild(block);
                block = dom.rename(block, listItemName);
              }
              removeStyles(dom, block, [
                "margin",
                "margin-right",
                "margin-bottom",
                "margin-left",
                "margin-top",
                "padding",
                "padding-right",
                "padding-bottom",
                "padding-left",
                "padding-top"
              ]);
              updateListWithDetails(dom, listBlock, detail);
              mergeWithAdjacentLists(editor.dom, listBlock);
            }
          });
          editor.selection.setRng(resolveBookmark(bookmark));
        };
        var isValidLists = function(list1, list2) {
          return list1 && list2 && isListNode(list1) && list1.nodeName === list2.nodeName;
        };
        var hasSameListStyle = function(dom, list1, list2) {
          var targetStyle = dom.getStyle(list1, "list-style-type", true);
          var style = dom.getStyle(list2, "list-style-type", true);
          return targetStyle === style;
        };
        var hasSameClasses = function(elm1, elm2) {
          return elm1.className === elm2.className;
        };
        var shouldMerge = function(dom, list1, list2) {
          return isValidLists(list1, list2) && hasSameListStyle(dom, list1, list2) && hasSameClasses(list1, list2);
        };
        var mergeWithAdjacentLists = function(dom, listBlock) {
          var sibling, node;
          sibling = listBlock.nextSibling;
          if (shouldMerge(dom, listBlock, sibling)) {
            while (node = sibling.firstChild) {
              listBlock.appendChild(node);
            }
            dom.remove(sibling);
          }
          sibling = listBlock.previousSibling;
          if (shouldMerge(dom, listBlock, sibling)) {
            while (node = sibling.lastChild) {
              listBlock.insertBefore(node, listBlock.firstChild);
            }
            dom.remove(sibling);
          }
        };
        var updateList$1 = function(editor, list, listName, detail) {
          if (list.nodeName !== listName) {
            var newList = editor.dom.rename(list, listName);
            updateListWithDetails(editor.dom, newList, detail);
            fireListEvent(editor, listToggleActionFromListName(listName), newList);
          } else {
            updateListWithDetails(editor.dom, list, detail);
            fireListEvent(editor, listToggleActionFromListName(listName), list);
          }
        };
        var toggleMultipleLists = function(editor, parentList, lists, listName, detail) {
          var parentIsList = isListNode(parentList);
          if (parentIsList && parentList.nodeName === listName && !hasListStyleDetail(detail)) {
            flattenListSelection(editor);
          } else {
            applyList(editor, listName, detail);
            var bookmark = createBookmark(editor.selection.getRng());
            var allLists = parentIsList ? __spreadArray([parentList], lists, true) : lists;
            global$2.each(allLists, function(elm) {
              updateList$1(editor, elm, listName, detail);
            });
            editor.selection.setRng(resolveBookmark(bookmark));
          }
        };
        var hasListStyleDetail = function(detail) {
          return "list-style-type" in detail;
        };
        var toggleSingleList = function(editor, parentList, listName, detail) {
          if (parentList === editor.getBody()) {
            return;
          }
          if (parentList) {
            if (parentList.nodeName === listName && !hasListStyleDetail(detail) && !isCustomList(parentList)) {
              flattenListSelection(editor);
            } else {
              var bookmark = createBookmark(editor.selection.getRng());
              updateListWithDetails(editor.dom, parentList, detail);
              var newList = editor.dom.rename(parentList, listName);
              mergeWithAdjacentLists(editor.dom, newList);
              editor.selection.setRng(resolveBookmark(bookmark));
              applyList(editor, listName, detail);
              fireListEvent(editor, listToggleActionFromListName(listName), newList);
            }
          } else {
            applyList(editor, listName, detail);
            fireListEvent(editor, listToggleActionFromListName(listName), parentList);
          }
        };
        var toggleList = function(editor, listName, _detail) {
          var parentList = getParentList(editor);
          var selectedSubLists = getSelectedSubLists(editor);
          var detail = isObject2(_detail) ? _detail : {};
          if (selectedSubLists.length > 0) {
            toggleMultipleLists(editor, parentList, selectedSubLists, listName, detail);
          } else {
            toggleSingleList(editor, parentList, listName, detail);
          }
        };
        var DOM = global$3.DOM;
        var normalizeList = function(dom, list) {
          var parentNode = list.parentNode;
          if (parentNode.nodeName === "LI" && parentNode.firstChild === list) {
            var sibling = parentNode.previousSibling;
            if (sibling && sibling.nodeName === "LI") {
              sibling.appendChild(list);
              if (isEmpty(dom, parentNode)) {
                DOM.remove(parentNode);
              }
            } else {
              DOM.setStyle(parentNode, "listStyleType", "none");
            }
          }
          if (isListNode(parentNode)) {
            var sibling = parentNode.previousSibling;
            if (sibling && sibling.nodeName === "LI") {
              sibling.appendChild(list);
            }
          }
        };
        var normalizeLists = function(dom, element) {
          var lists = global$2.grep(dom.select("ol,ul", element));
          global$2.each(lists, function(list) {
            normalizeList(dom, list);
          });
        };
        var findNextCaretContainer = function(editor, rng, isForward, root) {
          var node = rng.startContainer;
          var offset2 = rng.startOffset;
          if (isTextNode(node) && (isForward ? offset2 < node.data.length : offset2 > 0)) {
            return node;
          }
          var nonEmptyBlocks = editor.schema.getNonEmptyElements();
          if (node.nodeType === 1) {
            node = global$6.getNode(node, offset2);
          }
          var walker = new global$5(node, root);
          if (isForward) {
            if (isBogusBr(editor.dom, node)) {
              walker.next();
            }
          }
          while (node = walker[isForward ? "next" : "prev2"]()) {
            if (node.nodeName === "LI" && !node.hasChildNodes()) {
              return node;
            }
            if (nonEmptyBlocks[node.nodeName]) {
              return node;
            }
            if (isTextNode(node) && node.data.length > 0) {
              return node;
            }
          }
        };
        var hasOnlyOneBlockChild = function(dom, elm) {
          var childNodes = elm.childNodes;
          return childNodes.length === 1 && !isListNode(childNodes[0]) && dom.isBlock(childNodes[0]);
        };
        var unwrapSingleBlockChild = function(dom, elm) {
          if (hasOnlyOneBlockChild(dom, elm)) {
            dom.remove(elm.firstChild, true);
          }
        };
        var moveChildren = function(dom, fromElm, toElm) {
          var node;
          var targetElm = hasOnlyOneBlockChild(dom, toElm) ? toElm.firstChild : toElm;
          unwrapSingleBlockChild(dom, fromElm);
          if (!isEmpty(dom, fromElm, true)) {
            while (node = fromElm.firstChild) {
              targetElm.appendChild(node);
            }
          }
        };
        var mergeLiElements = function(dom, fromElm, toElm) {
          var listNode;
          var ul = fromElm.parentNode;
          if (!isChildOfBody(dom, fromElm) || !isChildOfBody(dom, toElm)) {
            return;
          }
          if (isListNode(toElm.lastChild)) {
            listNode = toElm.lastChild;
          }
          if (ul === toElm.lastChild) {
            if (isBr(ul.previousSibling)) {
              dom.remove(ul.previousSibling);
            }
          }
          var node = toElm.lastChild;
          if (node && isBr(node) && fromElm.hasChildNodes()) {
            dom.remove(node);
          }
          if (isEmpty(dom, toElm, true)) {
            dom.$(toElm).empty();
          }
          moveChildren(dom, fromElm, toElm);
          if (listNode) {
            toElm.appendChild(listNode);
          }
          var contains$12 = contains2(SugarElement.fromDom(toElm), SugarElement.fromDom(fromElm));
          var nestedLists = contains$12 ? dom.getParents(fromElm, isListNode, toElm) : [];
          dom.remove(fromElm);
          each$1(nestedLists, function(list) {
            if (isEmpty(dom, list) && list !== dom.getRoot()) {
              dom.remove(list);
            }
          });
        };
        var mergeIntoEmptyLi = function(editor, fromLi, toLi) {
          editor.dom.$(toLi).empty();
          mergeLiElements(editor.dom, fromLi, toLi);
          editor.selection.setCursorLocation(toLi, 0);
        };
        var mergeForward = function(editor, rng, fromLi, toLi) {
          var dom = editor.dom;
          if (dom.isEmpty(toLi)) {
            mergeIntoEmptyLi(editor, fromLi, toLi);
          } else {
            var bookmark = createBookmark(rng);
            mergeLiElements(dom, fromLi, toLi);
            editor.selection.setRng(resolveBookmark(bookmark));
          }
        };
        var mergeBackward = function(editor, rng, fromLi, toLi) {
          var bookmark = createBookmark(rng);
          mergeLiElements(editor.dom, fromLi, toLi);
          var resolvedBookmark = resolveBookmark(bookmark);
          editor.selection.setRng(resolvedBookmark);
        };
        var backspaceDeleteFromListToListCaret = function(editor, isForward) {
          var dom = editor.dom, selection = editor.selection;
          var selectionStartElm = selection.getStart();
          var root = getClosestListRootElm(editor, selectionStartElm);
          var li2 = dom.getParent(selection.getStart(), "LI", root);
          if (li2) {
            var ul = li2.parentNode;
            if (ul === editor.getBody() && isEmpty(dom, ul)) {
              return true;
            }
            var rng_1 = normalizeRange(selection.getRng());
            var otherLi_1 = dom.getParent(findNextCaretContainer(editor, rng_1, isForward, root), "LI", root);
            if (otherLi_1 && otherLi_1 !== li2) {
              editor.undoManager.transact(function() {
                if (isForward) {
                  mergeForward(editor, rng_1, otherLi_1, li2);
                } else {
                  if (isFirstChild(li2)) {
                    outdentListSelection(editor);
                  } else {
                    mergeBackward(editor, rng_1, li2, otherLi_1);
                  }
                }
              });
              return true;
            } else if (!otherLi_1) {
              if (!isForward && rng_1.startOffset === 0 && rng_1.endOffset === 0) {
                editor.undoManager.transact(function() {
                  flattenListSelection(editor);
                });
                return true;
              }
            }
          }
          return false;
        };
        var removeBlock = function(dom, block, root) {
          var parentBlock = dom.getParent(block.parentNode, dom.isBlock, root);
          dom.remove(block);
          if (parentBlock && dom.isEmpty(parentBlock)) {
            dom.remove(parentBlock);
          }
        };
        var backspaceDeleteIntoListCaret = function(editor, isForward) {
          var dom = editor.dom;
          var selectionStartElm = editor.selection.getStart();
          var root = getClosestListRootElm(editor, selectionStartElm);
          var block = dom.getParent(selectionStartElm, dom.isBlock, root);
          if (block && dom.isEmpty(block)) {
            var rng = normalizeRange(editor.selection.getRng());
            var otherLi_2 = dom.getParent(findNextCaretContainer(editor, rng, isForward, root), "LI", root);
            if (otherLi_2) {
              editor.undoManager.transact(function() {
                removeBlock(dom, block, root);
                mergeWithAdjacentLists(dom, otherLi_2.parentNode);
                editor.selection.select(otherLi_2, true);
                editor.selection.collapse(isForward);
              });
              return true;
            }
          }
          return false;
        };
        var backspaceDeleteCaret = function(editor, isForward) {
          return backspaceDeleteFromListToListCaret(editor, isForward) || backspaceDeleteIntoListCaret(editor, isForward);
        };
        var backspaceDeleteRange = function(editor) {
          var selectionStartElm = editor.selection.getStart();
          var root = getClosestListRootElm(editor, selectionStartElm);
          var startListParent = editor.dom.getParent(selectionStartElm, "LI,DT,DD", root);
          if (startListParent || getSelectedListItems(editor).length > 0) {
            editor.undoManager.transact(function() {
              editor.execCommand("Delete");
              normalizeLists(editor.dom, editor.getBody());
            });
            return true;
          }
          return false;
        };
        var backspaceDelete = function(editor, isForward) {
          return editor.selection.isCollapsed() ? backspaceDeleteCaret(editor, isForward) : backspaceDeleteRange(editor);
        };
        var setup$1 = function(editor) {
          editor.on("keydown", function(e2) {
            if (e2.keyCode === global$4.BACKSPACE) {
              if (backspaceDelete(editor, false)) {
                e2.preventDefault();
              }
            } else if (e2.keyCode === global$4.DELETE) {
              if (backspaceDelete(editor, true)) {
                e2.preventDefault();
              }
            }
          });
        };
        var get = function(editor) {
          return {
            backspaceDelete: function(isForward) {
              backspaceDelete(editor, isForward);
            }
          };
        };
        var updateList = function(editor, update) {
          var parentList = getParentList(editor);
          editor.undoManager.transact(function() {
            if (isObject2(update.styles)) {
              editor.dom.setStyles(parentList, update.styles);
            }
            if (isObject2(update.attrs)) {
              each2(update.attrs, function(v2, k2) {
                return editor.dom.setAttrib(parentList, k2, v2);
              });
            }
          });
        };
        var parseAlphabeticBase26 = function(str) {
          var chars = reverse(trim(str).split(""));
          var values = map3(chars, function(char, i2) {
            var charValue = char.toUpperCase().charCodeAt(0) - "A".charCodeAt(0) + 1;
            return Math.pow(26, i2) * charValue;
          });
          return foldl(values, function(sum, v2) {
            return sum + v2;
          }, 0);
        };
        var composeAlphabeticBase26 = function(value) {
          value--;
          if (value < 0) {
            return "";
          } else {
            var remainder = value % 26;
            var quotient = Math.floor(value / 26);
            var rest = composeAlphabeticBase26(quotient);
            var char = String.fromCharCode("A".charCodeAt(0) + remainder);
            return rest + char;
          }
        };
        var isUppercase = function(str) {
          return /^[A-Z]+$/.test(str);
        };
        var isLowercase = function(str) {
          return /^[a-z]+$/.test(str);
        };
        var isNumeric = function(str) {
          return /^[0-9]+$/.test(str);
        };
        var deduceListType = function(start4) {
          if (isNumeric(start4)) {
            return 2;
          } else if (isUppercase(start4)) {
            return 0;
          } else if (isLowercase(start4)) {
            return 1;
          } else if (isEmpty$1(start4)) {
            return 3;
          } else {
            return 4;
          }
        };
        var parseStartValue = function(start4) {
          switch (deduceListType(start4)) {
            case 2:
              return Optional.some({
                listStyleType: Optional.none(),
                start: start4
              });
            case 0:
              return Optional.some({
                listStyleType: Optional.some("upper-alpha"),
                start: parseAlphabeticBase26(start4).toString()
              });
            case 1:
              return Optional.some({
                listStyleType: Optional.some("lower-alpha"),
                start: parseAlphabeticBase26(start4).toString()
              });
            case 3:
              return Optional.some({
                listStyleType: Optional.none(),
                start: ""
              });
            case 4:
              return Optional.none();
          }
        };
        var parseDetail = function(detail) {
          var start4 = parseInt(detail.start, 10);
          if (is(detail.listStyleType, "upper-alpha")) {
            return composeAlphabeticBase26(start4);
          } else if (is(detail.listStyleType, "lower-alpha")) {
            return composeAlphabeticBase26(start4).toLowerCase();
          } else {
            return detail.start;
          }
        };
        var open = function(editor) {
          var currentList = getParentList(editor);
          if (!isOlNode(currentList)) {
            return;
          }
          editor.windowManager.open({
            title: "List Properties",
            body: {
              type: "panel",
              items: [{
                type: "input",
                name: "start",
                label: "Start list at number",
                inputMode: "numeric"
              }]
            },
            initialData: {
              start: parseDetail({
                start: editor.dom.getAttrib(currentList, "start", "1"),
                listStyleType: Optional.some(editor.dom.getStyle(currentList, "list-style-type"))
              })
            },
            buttons: [
              {
                type: "cancel",
                name: "cancel",
                text: "Cancel"
              },
              {
                type: "submit",
                name: "save",
                text: "Save",
                primary: true
              }
            ],
            onSubmit: function(api) {
              var data = api.getData();
              parseStartValue(data.start).each(function(detail) {
                editor.execCommand("mceListUpdate", false, {
                  attrs: { start: detail.start === "1" ? "" : detail.start },
                  styles: { "list-style-type": detail.listStyleType.getOr("") }
                });
              });
              api.close();
            }
          });
        };
        var queryListCommandState = function(editor, listName) {
          return function() {
            var parentList = getParentList(editor);
            return parentList && parentList.nodeName === listName;
          };
        };
        var registerDialog = function(editor) {
          editor.addCommand("mceListProps", function() {
            open(editor);
          });
        };
        var register$2 = function(editor) {
          editor.on("BeforeExecCommand", function(e2) {
            var cmd = e2.command.toLowerCase();
            if (cmd === "indent") {
              indentListSelection(editor);
            } else if (cmd === "outdent") {
              outdentListSelection(editor);
            }
          });
          editor.addCommand("InsertUnorderedList", function(ui2, detail) {
            toggleList(editor, "UL", detail);
          });
          editor.addCommand("InsertOrderedList", function(ui2, detail) {
            toggleList(editor, "OL", detail);
          });
          editor.addCommand("InsertDefinitionList", function(ui2, detail) {
            toggleList(editor, "DL", detail);
          });
          editor.addCommand("RemoveList", function() {
            flattenListSelection(editor);
          });
          registerDialog(editor);
          editor.addCommand("mceListUpdate", function(ui2, detail) {
            if (isObject2(detail)) {
              updateList(editor, detail);
            }
          });
          editor.addQueryStateHandler("InsertUnorderedList", queryListCommandState(editor, "UL"));
          editor.addQueryStateHandler("InsertOrderedList", queryListCommandState(editor, "OL"));
          editor.addQueryStateHandler("InsertDefinitionList", queryListCommandState(editor, "DL"));
        };
        var setupTabKey = function(editor) {
          editor.on("keydown", function(e2) {
            if (e2.keyCode !== global$4.TAB || global$4.metaKeyPressed(e2)) {
              return;
            }
            editor.undoManager.transact(function() {
              if (e2.shiftKey ? outdentListSelection(editor) : indentListSelection(editor)) {
                e2.preventDefault();
              }
            });
          });
        };
        var setup = function(editor) {
          if (shouldIndentOnTab(editor)) {
            setupTabKey(editor);
          }
          setup$1(editor);
        };
        var register$1 = function(editor) {
          var exec = function(command) {
            return function() {
              return editor.execCommand(command);
            };
          };
          if (!editor.hasPlugin("advlist")) {
            editor.ui.registry.addToggleButton("numlist", {
              icon: "ordered-list",
              active: false,
              tooltip: "Numbered list",
              onAction: exec("InsertOrderedList"),
              onSetup: function(api) {
                return listState(editor, "OL", api.setActive);
              }
            });
            editor.ui.registry.addToggleButton("bullist", {
              icon: "unordered-list",
              active: false,
              tooltip: "Bullet list",
              onAction: exec("InsertUnorderedList"),
              onSetup: function(api) {
                return listState(editor, "UL", api.setActive);
              }
            });
          }
        };
        var register = function(editor) {
          var listProperties = {
            text: "List properties...",
            icon: "ordered-list",
            onAction: function() {
              return editor.execCommand("mceListProps");
            },
            onSetup: function(api) {
              return listState(editor, "OL", function(active) {
                return api.setDisabled(!active);
              });
            }
          };
          editor.ui.registry.addMenuItem("listprops", listProperties);
          editor.ui.registry.addContextMenu("lists", {
            update: function(node) {
              var parentList = getParentList(editor, node);
              return isOlNode(parentList) ? ["listprops"] : [];
            }
          });
        };
        function Plugin() {
          global$7.add("lists", function(editor) {
            if (editor.hasPlugin("rtc", true) === false) {
              setup(editor);
              register$2(editor);
            } else {
              registerDialog(editor);
            }
            register$1(editor);
            register(editor);
            return get(editor);
          });
        }
        Plugin();
      })();
    }
  });

  // ../../node_modules/tinymce/plugins/textpattern/plugin.js
  var require_plugin24 = __commonJS({
    "../../node_modules/tinymce/plugins/textpattern/plugin.js"() {
      (function() {
        "use strict";
        var Cell = function(initial) {
          var value2 = initial;
          var get2 = function() {
            return value2;
          };
          var set2 = function(v2) {
            value2 = v2;
          };
          return {
            get: get2,
            set: set2
          };
        };
        var global$5 = tinymce.util.Tools.resolve("tinymce.PluginManager");
        var __assign = function() {
          __assign = Object.assign || function __assign2(t2) {
            for (var s2, i2 = 1, n2 = arguments.length; i2 < n2; i2++) {
              s2 = arguments[i2];
              for (var p2 in s2)
                if (Object.prototype.hasOwnProperty.call(s2, p2))
                  t2[p2] = s2[p2];
            }
            return t2;
          };
          return __assign.apply(this, arguments);
        };
        function __spreadArray(to, from2, pack) {
          if (pack || arguments.length === 2)
            for (var i2 = 0, l2 = from2.length, ar; i2 < l2; i2++) {
              if (ar || !(i2 in from2)) {
                if (!ar)
                  ar = Array.prototype.slice.call(from2, 0, i2);
                ar[i2] = from2[i2];
              }
            }
          return to.concat(ar || Array.prototype.slice.call(from2));
        }
        var typeOf = function(x2) {
          var t2 = typeof x2;
          if (x2 === null) {
            return "null";
          } else if (t2 === "object" && (Array.prototype.isPrototypeOf(x2) || x2.constructor && x2.constructor.name === "Array")) {
            return "array";
          } else if (t2 === "object" && (String.prototype.isPrototypeOf(x2) || x2.constructor && x2.constructor.name === "String")) {
            return "string";
          } else {
            return t2;
          }
        };
        var isType = function(type) {
          return function(value2) {
            return typeOf(value2) === type;
          };
        };
        var isString = isType("string");
        var isObject2 = isType("object");
        var isArray2 = isType("array");
        var noop3 = function() {
        };
        var constant = function(value2) {
          return function() {
            return value2;
          };
        };
        var identity = function(x2) {
          return x2;
        };
        var die = function(msg) {
          return function() {
            throw new Error(msg);
          };
        };
        var never = constant(false);
        var always = constant(true);
        var none = function() {
          return NONE;
        };
        var NONE = function() {
          var call = function(thunk) {
            return thunk();
          };
          var id2 = identity;
          var me2 = {
            fold: function(n2, _s) {
              return n2();
            },
            isSome: never,
            isNone: always,
            getOr: id2,
            getOrThunk: call,
            getOrDie: function(msg) {
              throw new Error(msg || "error: getOrDie called on none.");
            },
            getOrNull: constant(null),
            getOrUndefined: constant(void 0),
            or: id2,
            orThunk: call,
            map: none,
            each: noop3,
            bind: none,
            exists: never,
            forall: always,
            filter: function() {
              return none();
            },
            toArray: function() {
              return [];
            },
            toString: constant("none()")
          };
          return me2;
        }();
        var some = function(a2) {
          var constant_a = constant(a2);
          var self2 = function() {
            return me2;
          };
          var bind = function(f2) {
            return f2(a2);
          };
          var me2 = {
            fold: function(n2, s2) {
              return s2(a2);
            },
            isSome: always,
            isNone: never,
            getOr: constant_a,
            getOrThunk: constant_a,
            getOrDie: constant_a,
            getOrNull: constant_a,
            getOrUndefined: constant_a,
            or: self2,
            orThunk: self2,
            map: function(f2) {
              return some(f2(a2));
            },
            each: function(f2) {
              f2(a2);
            },
            bind,
            exists: bind,
            forall: bind,
            filter: function(f2) {
              return f2(a2) ? me2 : NONE;
            },
            toArray: function() {
              return [a2];
            },
            toString: function() {
              return "some(" + a2 + ")";
            }
          };
          return me2;
        };
        var from = function(value2) {
          return value2 === null || value2 === void 0 ? NONE : some(value2);
        };
        var Optional = {
          some,
          none,
          from
        };
        var nativeSlice = Array.prototype.slice;
        var nativeIndexOf = Array.prototype.indexOf;
        var rawIndexOf = function(ts, t2) {
          return nativeIndexOf.call(ts, t2);
        };
        var contains2 = function(xs, x2) {
          return rawIndexOf(xs, x2) > -1;
        };
        var map3 = function(xs, f2) {
          var len = xs.length;
          var r2 = new Array(len);
          for (var i2 = 0; i2 < len; i2++) {
            var x2 = xs[i2];
            r2[i2] = f2(x2, i2);
          }
          return r2;
        };
        var each2 = function(xs, f2) {
          for (var i2 = 0, len = xs.length; i2 < len; i2++) {
            var x2 = xs[i2];
            f2(x2, i2);
          }
        };
        var eachr = function(xs, f2) {
          for (var i2 = xs.length - 1; i2 >= 0; i2--) {
            var x2 = xs[i2];
            f2(x2, i2);
          }
        };
        var filter = function(xs, pred) {
          var r2 = [];
          for (var i2 = 0, len = xs.length; i2 < len; i2++) {
            var x2 = xs[i2];
            if (pred(x2, i2)) {
              r2.push(x2);
            }
          }
          return r2;
        };
        var foldr = function(xs, f2, acc) {
          eachr(xs, function(x2, i2) {
            acc = f2(acc, x2, i2);
          });
          return acc;
        };
        var foldl = function(xs, f2, acc) {
          each2(xs, function(x2, i2) {
            acc = f2(acc, x2, i2);
          });
          return acc;
        };
        var findUntil = function(xs, pred, until) {
          for (var i2 = 0, len = xs.length; i2 < len; i2++) {
            var x2 = xs[i2];
            if (pred(x2, i2)) {
              return Optional.some(x2);
            } else if (until(x2, i2)) {
              break;
            }
          }
          return Optional.none();
        };
        var find = function(xs, pred) {
          return findUntil(xs, pred, never);
        };
        var forall = function(xs, pred) {
          for (var i2 = 0, len = xs.length; i2 < len; ++i2) {
            var x2 = xs[i2];
            if (pred(x2, i2) !== true) {
              return false;
            }
          }
          return true;
        };
        var sort = function(xs, comparator) {
          var copy = nativeSlice.call(xs, 0);
          copy.sort(comparator);
          return copy;
        };
        var get$1 = function(xs, i2) {
          return i2 >= 0 && i2 < xs.length ? Optional.some(xs[i2]) : Optional.none();
        };
        var head = function(xs) {
          return get$1(xs, 0);
        };
        var keys = Object.keys;
        var hasOwnProperty = Object.hasOwnProperty;
        var has = function(obj, key) {
          return hasOwnProperty.call(obj, key);
        };
        var generate$1 = function(cases) {
          if (!isArray2(cases)) {
            throw new Error("cases must be an array");
          }
          if (cases.length === 0) {
            throw new Error("there must be at least one case");
          }
          var constructors = [];
          var adt = {};
          each2(cases, function(acase, count) {
            var keys$1 = keys(acase);
            if (keys$1.length !== 1) {
              throw new Error("one and only one name per case");
            }
            var key = keys$1[0];
            var value2 = acase[key];
            if (adt[key] !== void 0) {
              throw new Error("duplicate key detected:" + key);
            } else if (key === "cata") {
              throw new Error("cannot have a case named cata (sorry)");
            } else if (!isArray2(value2)) {
              throw new Error("case arguments must be an array");
            }
            constructors.push(key);
            adt[key] = function() {
              var args = [];
              for (var _i2 = 0; _i2 < arguments.length; _i2++) {
                args[_i2] = arguments[_i2];
              }
              var argLength = args.length;
              if (argLength !== value2.length) {
                throw new Error("Wrong number of arguments to case " + key + ". Expected " + value2.length + " (" + value2 + "), got " + argLength);
              }
              var match2 = function(branches) {
                var branchKeys = keys(branches);
                if (constructors.length !== branchKeys.length) {
                  throw new Error("Wrong number of arguments to match. Expected: " + constructors.join(",") + "\nActual: " + branchKeys.join(","));
                }
                var allReqd = forall(constructors, function(reqKey) {
                  return contains2(branchKeys, reqKey);
                });
                if (!allReqd) {
                  throw new Error("Not all branches were specified when using match. Specified: " + branchKeys.join(", ") + "\nRequired: " + constructors.join(", "));
                }
                return branches[key].apply(null, args);
              };
              return {
                fold: function() {
                  var foldArgs = [];
                  for (var _i3 = 0; _i3 < arguments.length; _i3++) {
                    foldArgs[_i3] = arguments[_i3];
                  }
                  if (foldArgs.length !== cases.length) {
                    throw new Error("Wrong number of arguments to fold. Expected " + cases.length + ", got " + foldArgs.length);
                  }
                  var target = foldArgs[count];
                  return target.apply(null, args);
                },
                match: match2,
                log: function(label) {
                  console.log(label, {
                    constructors,
                    constructor: key,
                    params: args
                  });
                }
              };
            };
          });
          return adt;
        };
        var Adt = { generate: generate$1 };
        Adt.generate([
          {
            bothErrors: [
              "error1",
              "error2"
            ]
          },
          {
            firstError: [
              "error1",
              "value2"
            ]
          },
          {
            secondError: [
              "value1",
              "error2"
            ]
          },
          {
            bothValues: [
              "value1",
              "value2"
            ]
          }
        ]);
        var partition = function(results) {
          var errors = [];
          var values = [];
          each2(results, function(result) {
            result.fold(function(err) {
              errors.push(err);
            }, function(value2) {
              values.push(value2);
            });
          });
          return {
            errors,
            values
          };
        };
        var value = function(o2) {
          var or = function(_opt) {
            return value(o2);
          };
          var orThunk = function(_f) {
            return value(o2);
          };
          var map4 = function(f2) {
            return value(f2(o2));
          };
          var mapError = function(_f) {
            return value(o2);
          };
          var each3 = function(f2) {
            f2(o2);
          };
          var bind = function(f2) {
            return f2(o2);
          };
          var fold = function(_2, onValue) {
            return onValue(o2);
          };
          var exists = function(f2) {
            return f2(o2);
          };
          var forall2 = function(f2) {
            return f2(o2);
          };
          var toOptional = function() {
            return Optional.some(o2);
          };
          return {
            isValue: always,
            isError: never,
            getOr: constant(o2),
            getOrThunk: constant(o2),
            getOrDie: constant(o2),
            or,
            orThunk,
            fold,
            map: map4,
            mapError,
            each: each3,
            bind,
            exists,
            forall: forall2,
            toOptional
          };
        };
        var error$1 = function(message) {
          var getOrThunk = function(f2) {
            return f2();
          };
          var getOrDie = function() {
            return die(String(message))();
          };
          var or = identity;
          var orThunk = function(f2) {
            return f2();
          };
          var map4 = function(_f) {
            return error$1(message);
          };
          var mapError = function(f2) {
            return error$1(f2(message));
          };
          var bind = function(_f) {
            return error$1(message);
          };
          var fold = function(onError, _2) {
            return onError(message);
          };
          return {
            isValue: never,
            isError: always,
            getOr: identity,
            getOrThunk,
            getOrDie,
            or,
            orThunk,
            fold,
            map: map4,
            mapError,
            each: noop3,
            bind,
            exists: never,
            forall: always,
            toOptional: Optional.none
          };
        };
        var fromOption = function(opt, err) {
          return opt.fold(function() {
            return error$1(err);
          }, value);
        };
        var Result = {
          value,
          error: error$1,
          fromOption
        };
        var isInlinePattern = function(pattern) {
          return pattern.type === "inline-command" || pattern.type === "inline-format";
        };
        var isBlockPattern = function(pattern) {
          return pattern.type === "block-command" || pattern.type === "block-format";
        };
        var sortPatterns = function(patterns2) {
          return sort(patterns2, function(a2, b2) {
            if (a2.start.length === b2.start.length) {
              return 0;
            }
            return a2.start.length > b2.start.length ? -1 : 1;
          });
        };
        var normalizePattern = function(pattern) {
          var err = function(message) {
            return Result.error({
              message,
              pattern
            });
          };
          var formatOrCmd = function(name, onFormat, onCommand) {
            if (pattern.format !== void 0) {
              var formats = void 0;
              if (isArray2(pattern.format)) {
                if (!forall(pattern.format, isString)) {
                  return err(name + " pattern has non-string items in the `format` array");
                }
                formats = pattern.format;
              } else if (isString(pattern.format)) {
                formats = [pattern.format];
              } else {
                return err(name + " pattern has non-string `format` parameter");
              }
              return Result.value(onFormat(formats));
            } else if (pattern.cmd !== void 0) {
              if (!isString(pattern.cmd)) {
                return err(name + " pattern has non-string `cmd` parameter");
              }
              return Result.value(onCommand(pattern.cmd, pattern.value));
            } else {
              return err(name + " pattern is missing both `format` and `cmd` parameters");
            }
          };
          if (!isObject2(pattern)) {
            return err("Raw pattern is not an object");
          }
          if (!isString(pattern.start)) {
            return err("Raw pattern is missing `start` parameter");
          }
          if (pattern.end !== void 0) {
            if (!isString(pattern.end)) {
              return err("Inline pattern has non-string `end` parameter");
            }
            if (pattern.start.length === 0 && pattern.end.length === 0) {
              return err("Inline pattern has empty `start` and `end` parameters");
            }
            var start_1 = pattern.start;
            var end_1 = pattern.end;
            if (end_1.length === 0) {
              end_1 = start_1;
              start_1 = "";
            }
            return formatOrCmd("Inline", function(format3) {
              return {
                type: "inline-format",
                start: start_1,
                end: end_1,
                format: format3
              };
            }, function(cmd, value2) {
              return {
                type: "inline-command",
                start: start_1,
                end: end_1,
                cmd,
                value: value2
              };
            });
          } else if (pattern.replacement !== void 0) {
            if (!isString(pattern.replacement)) {
              return err("Replacement pattern has non-string `replacement` parameter");
            }
            if (pattern.start.length === 0) {
              return err("Replacement pattern has empty `start` parameter");
            }
            return Result.value({
              type: "inline-command",
              start: "",
              end: pattern.start,
              cmd: "mceInsertContent",
              value: pattern.replacement
            });
          } else {
            if (pattern.start.length === 0) {
              return err("Block pattern has empty `start` parameter");
            }
            return formatOrCmd("Block", function(formats) {
              return {
                type: "block-format",
                start: pattern.start,
                format: formats[0]
              };
            }, function(command, commandValue) {
              return {
                type: "block-command",
                start: pattern.start,
                cmd: command,
                value: commandValue
              };
            });
          }
        };
        var denormalizePattern = function(pattern) {
          if (pattern.type === "block-command") {
            return {
              start: pattern.start,
              cmd: pattern.cmd,
              value: pattern.value
            };
          } else if (pattern.type === "block-format") {
            return {
              start: pattern.start,
              format: pattern.format
            };
          } else if (pattern.type === "inline-command") {
            if (pattern.cmd === "mceInsertContent" && pattern.start === "") {
              return {
                start: pattern.end,
                replacement: pattern.value
              };
            } else {
              return {
                start: pattern.start,
                end: pattern.end,
                cmd: pattern.cmd,
                value: pattern.value
              };
            }
          } else if (pattern.type === "inline-format") {
            return {
              start: pattern.start,
              end: pattern.end,
              format: pattern.format.length === 1 ? pattern.format[0] : pattern.format
            };
          }
        };
        var createPatternSet = function(patterns2) {
          return {
            inlinePatterns: filter(patterns2, isInlinePattern),
            blockPatterns: sortPatterns(filter(patterns2, isBlockPattern))
          };
        };
        var get = function(patternsState) {
          var setPatterns = function(newPatterns) {
            var normalized = partition(map3(newPatterns, normalizePattern));
            if (normalized.errors.length > 0) {
              var firstError = normalized.errors[0];
              throw new Error(firstError.message + ":\n" + JSON.stringify(firstError.pattern, null, 2));
            }
            patternsState.set(createPatternSet(normalized.values));
          };
          var getPatterns = function() {
            return __spreadArray(__spreadArray([], map3(patternsState.get().inlinePatterns, denormalizePattern), true), map3(patternsState.get().blockPatterns, denormalizePattern), true);
          };
          return {
            setPatterns,
            getPatterns
          };
        };
        var Global = typeof window !== "undefined" ? window : Function("return this;")();
        var error3 = function() {
          var args = [];
          for (var _i2 = 0; _i2 < arguments.length; _i2++) {
            args[_i2] = arguments[_i2];
          }
          var console2 = Global.console;
          if (console2) {
            if (console2.error) {
              console2.error.apply(console2, args);
            } else {
              console2.log.apply(console2, args);
            }
          }
        };
        var defaultPatterns = [
          {
            start: "*",
            end: "*",
            format: "italic"
          },
          {
            start: "**",
            end: "**",
            format: "bold"
          },
          {
            start: "#",
            format: "h1"
          },
          {
            start: "##",
            format: "h2"
          },
          {
            start: "###",
            format: "h3"
          },
          {
            start: "####",
            format: "h4"
          },
          {
            start: "#####",
            format: "h5"
          },
          {
            start: "######",
            format: "h6"
          },
          {
            start: "1. ",
            cmd: "InsertOrderedList"
          },
          {
            start: "* ",
            cmd: "InsertUnorderedList"
          },
          {
            start: "- ",
            cmd: "InsertUnorderedList"
          }
        ];
        var getPatternSet = function(editor) {
          var patterns2 = editor.getParam("textpattern_patterns", defaultPatterns, "array");
          if (!isArray2(patterns2)) {
            error3("The setting textpattern_patterns should be an array");
            return {
              inlinePatterns: [],
              blockPatterns: []
            };
          }
          var normalized = partition(map3(patterns2, normalizePattern));
          each2(normalized.errors, function(err) {
            return error3(err.message, err.pattern);
          });
          return createPatternSet(normalized.values);
        };
        var getForcedRootBlock = function(editor) {
          var block = editor.getParam("forced_root_block", "p");
          if (block === false) {
            return "";
          } else if (block === true) {
            return "p";
          } else {
            return block;
          }
        };
        var global$4 = tinymce.util.Tools.resolve("tinymce.util.Delay");
        var global$3 = tinymce.util.Tools.resolve("tinymce.util.VK");
        var zeroWidth = "\uFEFF";
        var nbsp = "\xA0";
        var global$2 = tinymce.util.Tools.resolve("tinymce.util.Tools");
        var global$1 = tinymce.util.Tools.resolve("tinymce.dom.DOMUtils");
        var global2 = tinymce.util.Tools.resolve("tinymce.dom.TextSeeker");
        var point = function(container, offset2) {
          return {
            container,
            offset: offset2
          };
        };
        var isText = function(node) {
          return node.nodeType === Node.TEXT_NODE;
        };
        var cleanEmptyNodes = function(dom, node, isRoot) {
          if (node && dom.isEmpty(node) && !isRoot(node)) {
            var parent_1 = node.parentNode;
            dom.remove(node);
            cleanEmptyNodes(dom, parent_1, isRoot);
          }
        };
        var deleteRng = function(dom, rng, isRoot, clean) {
          if (clean === void 0) {
            clean = true;
          }
          var startParent = rng.startContainer.parentNode;
          var endParent = rng.endContainer.parentNode;
          rng.deleteContents();
          if (clean && !isRoot(rng.startContainer)) {
            if (isText(rng.startContainer) && rng.startContainer.data.length === 0) {
              dom.remove(rng.startContainer);
            }
            if (isText(rng.endContainer) && rng.endContainer.data.length === 0) {
              dom.remove(rng.endContainer);
            }
            cleanEmptyNodes(dom, startParent, isRoot);
            if (startParent !== endParent) {
              cleanEmptyNodes(dom, endParent, isRoot);
            }
          }
        };
        var isBlockFormatName = function(name, formatter) {
          var formatSet = formatter.get(name);
          return isArray2(formatSet) && head(formatSet).exists(function(format3) {
            return has(format3, "block");
          });
        };
        var isReplacementPattern = function(pattern) {
          return pattern.start.length === 0;
        };
        var getParentBlock = function(editor, rng) {
          var parentBlockOpt = Optional.from(editor.dom.getParent(rng.startContainer, editor.dom.isBlock));
          if (getForcedRootBlock(editor) === "") {
            return parentBlockOpt.orThunk(function() {
              return Optional.some(editor.getBody());
            });
          } else {
            return parentBlockOpt;
          }
        };
        var DOM = global$1.DOM;
        var alwaysNext = function(startNode) {
          return function(node) {
            return startNode === node ? -1 : 0;
          };
        };
        var isBoundary = function(dom) {
          return function(node) {
            return dom.isBlock(node) || contains2([
              "BR",
              "IMG",
              "HR",
              "INPUT"
            ], node.nodeName) || dom.getContentEditable(node) === "false";
          };
        };
        var textBefore = function(node, offset2, rootNode) {
          if (isText(node) && offset2 >= 0) {
            return Optional.some(point(node, offset2));
          } else {
            var textSeeker = global2(DOM);
            return Optional.from(textSeeker.backwards(node, offset2, alwaysNext(node), rootNode)).map(function(prev) {
              return point(prev.container, prev.container.data.length);
            });
          }
        };
        var textAfter = function(node, offset2, rootNode) {
          if (isText(node) && offset2 >= node.length) {
            return Optional.some(point(node, offset2));
          } else {
            var textSeeker = global2(DOM);
            return Optional.from(textSeeker.forwards(node, offset2, alwaysNext(node), rootNode)).map(function(prev) {
              return point(prev.container, 0);
            });
          }
        };
        var scanLeft = function(node, offset2, rootNode) {
          if (!isText(node)) {
            return Optional.none();
          }
          var text = node.textContent;
          if (offset2 >= 0 && offset2 <= text.length) {
            return Optional.some(point(node, offset2));
          } else {
            var textSeeker = global2(DOM);
            return Optional.from(textSeeker.backwards(node, offset2, alwaysNext(node), rootNode)).bind(function(prev) {
              var prevText = prev.container.data;
              return scanLeft(prev.container, offset2 + prevText.length, rootNode);
            });
          }
        };
        var scanRight = function(node, offset2, rootNode) {
          if (!isText(node)) {
            return Optional.none();
          }
          var text = node.textContent;
          if (offset2 <= text.length) {
            return Optional.some(point(node, offset2));
          } else {
            var textSeeker = global2(DOM);
            return Optional.from(textSeeker.forwards(node, offset2, alwaysNext(node), rootNode)).bind(function(next) {
              return scanRight(next.container, offset2 - text.length, rootNode);
            });
          }
        };
        var repeatLeft = function(dom, node, offset2, process2, rootNode) {
          var search = global2(dom, isBoundary(dom));
          return Optional.from(search.backwards(node, offset2, process2, rootNode));
        };
        var generatePath = function(root, node, offset2) {
          if (isText(node) && (offset2 < 0 || offset2 > node.data.length)) {
            return [];
          }
          var p2 = [offset2];
          var current = node;
          while (current !== root && current.parentNode) {
            var parent_1 = current.parentNode;
            for (var i2 = 0; i2 < parent_1.childNodes.length; i2++) {
              if (parent_1.childNodes[i2] === current) {
                p2.push(i2);
                break;
              }
            }
            current = parent_1;
          }
          return current === root ? p2.reverse() : [];
        };
        var generatePathRange = function(root, startNode, startOffset, endNode, endOffset) {
          var start4 = generatePath(root, startNode, startOffset);
          var end2 = generatePath(root, endNode, endOffset);
          return {
            start: start4,
            end: end2
          };
        };
        var resolvePath = function(root, path) {
          var nodePath = path.slice();
          var offset2 = nodePath.pop();
          var resolvedNode = foldl(nodePath, function(optNode, index) {
            return optNode.bind(function(node) {
              return Optional.from(node.childNodes[index]);
            });
          }, Optional.some(root));
          return resolvedNode.bind(function(node) {
            if (isText(node) && (offset2 < 0 || offset2 > node.data.length)) {
              return Optional.none();
            } else {
              return Optional.some({
                node,
                offset: offset2
              });
            }
          });
        };
        var resolvePathRange = function(root, range) {
          return resolvePath(root, range.start).bind(function(_a) {
            var startNode = _a.node, startOffset = _a.offset;
            return resolvePath(root, range.end).map(function(_a2) {
              var endNode = _a2.node, endOffset = _a2.offset;
              var rng = document.createRange();
              rng.setStart(startNode, startOffset);
              rng.setEnd(endNode, endOffset);
              return rng;
            });
          });
        };
        var generatePathRangeFromRange = function(root, range) {
          return generatePathRange(root, range.startContainer, range.startOffset, range.endContainer, range.endOffset);
        };
        var stripPattern = function(dom, block, pattern) {
          var firstTextNode = textAfter(block, 0, block);
          firstTextNode.each(function(spot) {
            var node = spot.container;
            scanRight(node, pattern.start.length, block).each(function(end2) {
              var rng = dom.createRng();
              rng.setStart(node, 0);
              rng.setEnd(end2.container, end2.offset);
              deleteRng(dom, rng, function(e2) {
                return e2 === block;
              });
            });
          });
        };
        var applyPattern$1 = function(editor, match2) {
          var dom = editor.dom;
          var pattern = match2.pattern;
          var rng = resolvePathRange(dom.getRoot(), match2.range).getOrDie("Unable to resolve path range");
          getParentBlock(editor, rng).each(function(block) {
            if (pattern.type === "block-format") {
              if (isBlockFormatName(pattern.format, editor.formatter)) {
                editor.undoManager.transact(function() {
                  stripPattern(editor.dom, block, pattern);
                  editor.formatter.apply(pattern.format);
                });
              }
            } else if (pattern.type === "block-command") {
              editor.undoManager.transact(function() {
                stripPattern(editor.dom, block, pattern);
                editor.execCommand(pattern.cmd, false, pattern.value);
              });
            }
          });
          return true;
        };
        var findPattern$1 = function(patterns2, text) {
          var nuText = text.replace(nbsp, " ");
          return find(patterns2, function(pattern) {
            return text.indexOf(pattern.start) === 0 || nuText.indexOf(pattern.start) === 0;
          });
        };
        var findPatterns$1 = function(editor, patterns2) {
          var dom = editor.dom;
          var rng = editor.selection.getRng();
          return getParentBlock(editor, rng).filter(function(block) {
            var forcedRootBlock = getForcedRootBlock(editor);
            var matchesForcedRootBlock = forcedRootBlock === "" && dom.is(block, "body") || dom.is(block, forcedRootBlock);
            return block !== null && matchesForcedRootBlock;
          }).bind(function(block) {
            var blockText = block.textContent;
            var matchedPattern = findPattern$1(patterns2, blockText);
            return matchedPattern.map(function(pattern) {
              if (global$2.trim(blockText).length === pattern.start.length) {
                return [];
              }
              return [{
                pattern,
                range: generatePathRange(dom.getRoot(), block, 0, block, 0)
              }];
            });
          }).getOr([]);
        };
        var applyMatches$1 = function(editor, matches) {
          if (matches.length === 0) {
            return;
          }
          var bookmark = editor.selection.getBookmark();
          each2(matches, function(match2) {
            return applyPattern$1(editor, match2);
          });
          editor.selection.moveToBookmark(bookmark);
        };
        var unique = 0;
        var generate = function(prefix) {
          var date = new Date();
          var time = date.getTime();
          var random = Math.floor(Math.random() * 1e9);
          unique++;
          return prefix + "_" + random + unique + String(time);
        };
        var checkRange = function(str, substr, start4) {
          return substr === "" || str.length >= substr.length && str.substr(start4, start4 + substr.length) === substr;
        };
        var endsWith = function(str, suffix) {
          return checkRange(str, suffix, str.length - suffix.length);
        };
        var newMarker = function(dom, id2) {
          return dom.create("span", {
            "data-mce-type": "bookmark",
            id: id2
          });
        };
        var rangeFromMarker = function(dom, marker) {
          var rng = dom.createRng();
          rng.setStartAfter(marker.start);
          rng.setEndBefore(marker.end);
          return rng;
        };
        var createMarker = function(dom, markerPrefix, pathRange) {
          var rng = resolvePathRange(dom.getRoot(), pathRange).getOrDie("Unable to resolve path range");
          var startNode = rng.startContainer;
          var endNode = rng.endContainer;
          var textEnd = rng.endOffset === 0 ? endNode : endNode.splitText(rng.endOffset);
          var textStart = rng.startOffset === 0 ? startNode : startNode.splitText(rng.startOffset);
          return {
            prefix: markerPrefix,
            end: textEnd.parentNode.insertBefore(newMarker(dom, markerPrefix + "-end"), textEnd),
            start: textStart.parentNode.insertBefore(newMarker(dom, markerPrefix + "-start"), textStart)
          };
        };
        var removeMarker = function(dom, marker, isRoot) {
          cleanEmptyNodes(dom, dom.get(marker.prefix + "-end"), isRoot);
          cleanEmptyNodes(dom, dom.get(marker.prefix + "-start"), isRoot);
        };
        var matchesPattern = function(dom, block, patternContent) {
          return function(element, offset2) {
            var text = element.data;
            var searchText = text.substring(0, offset2);
            var startEndIndex = searchText.lastIndexOf(patternContent.charAt(patternContent.length - 1));
            var startIndex = searchText.lastIndexOf(patternContent);
            if (startIndex !== -1) {
              return startIndex + patternContent.length;
            } else if (startEndIndex !== -1) {
              return startEndIndex + 1;
            } else {
              return -1;
            }
          };
        };
        var findPatternStartFromSpot = function(dom, pattern, block, spot) {
          var startPattern = pattern.start;
          var startSpot = repeatLeft(dom, spot.container, spot.offset, matchesPattern(dom, block, startPattern), block);
          return startSpot.bind(function(spot2) {
            if (spot2.offset >= startPattern.length) {
              var rng = dom.createRng();
              rng.setStart(spot2.container, spot2.offset - startPattern.length);
              rng.setEnd(spot2.container, spot2.offset);
              return Optional.some(rng);
            } else {
              var offset2 = spot2.offset - startPattern.length;
              return scanLeft(spot2.container, offset2, block).map(function(nextSpot) {
                var rng2 = dom.createRng();
                rng2.setStart(nextSpot.container, nextSpot.offset);
                rng2.setEnd(spot2.container, spot2.offset);
                return rng2;
              }).filter(function(rng2) {
                return rng2.toString() === startPattern;
              }).orThunk(function() {
                return findPatternStartFromSpot(dom, pattern, block, point(spot2.container, 0));
              });
            }
          });
        };
        var findPatternStart = function(dom, pattern, node, offset2, block, requireGap) {
          if (requireGap === void 0) {
            requireGap = false;
          }
          if (pattern.start.length === 0 && !requireGap) {
            var rng = dom.createRng();
            rng.setStart(node, offset2);
            rng.setEnd(node, offset2);
            return Optional.some(rng);
          }
          return textBefore(node, offset2, block).bind(function(spot) {
            var start4 = findPatternStartFromSpot(dom, pattern, block, spot);
            return start4.bind(function(startRange) {
              if (requireGap) {
                if (startRange.endContainer === spot.container && startRange.endOffset === spot.offset) {
                  return Optional.none();
                } else if (spot.offset === 0 && startRange.endContainer.textContent.length === startRange.endOffset) {
                  return Optional.none();
                }
              }
              return Optional.some(startRange);
            });
          });
        };
        var findPattern = function(editor, block, details) {
          var dom = editor.dom;
          var root = dom.getRoot();
          var pattern = details.pattern;
          var endNode = details.position.container;
          var endOffset = details.position.offset;
          return scanLeft(endNode, endOffset - details.pattern.end.length, block).bind(function(spot) {
            var endPathRng = generatePathRange(root, spot.container, spot.offset, endNode, endOffset);
            if (isReplacementPattern(pattern)) {
              return Optional.some({
                matches: [{
                  pattern,
                  startRng: endPathRng,
                  endRng: endPathRng
                }],
                position: spot
              });
            } else {
              var resultsOpt = findPatternsRec(editor, details.remainingPatterns, spot.container, spot.offset, block);
              var results_1 = resultsOpt.getOr({
                matches: [],
                position: spot
              });
              var pos = results_1.position;
              var start4 = findPatternStart(dom, pattern, pos.container, pos.offset, block, resultsOpt.isNone());
              return start4.map(function(startRng) {
                var startPathRng = generatePathRangeFromRange(root, startRng);
                return {
                  matches: results_1.matches.concat([{
                    pattern,
                    startRng: startPathRng,
                    endRng: endPathRng
                  }]),
                  position: point(startRng.startContainer, startRng.startOffset)
                };
              });
            }
          });
        };
        var findPatternsRec = function(editor, patterns2, node, offset2, block) {
          var dom = editor.dom;
          return textBefore(node, offset2, dom.getRoot()).bind(function(endSpot) {
            var rng = dom.createRng();
            rng.setStart(block, 0);
            rng.setEnd(node, offset2);
            var text = rng.toString();
            for (var i2 = 0; i2 < patterns2.length; i2++) {
              var pattern = patterns2[i2];
              if (!endsWith(text, pattern.end)) {
                continue;
              }
              var patternsWithoutCurrent = patterns2.slice();
              patternsWithoutCurrent.splice(i2, 1);
              var result = findPattern(editor, block, {
                pattern,
                remainingPatterns: patternsWithoutCurrent,
                position: endSpot
              });
              if (result.isSome()) {
                return result;
              }
            }
            return Optional.none();
          });
        };
        var applyPattern = function(editor, pattern, patternRange) {
          editor.selection.setRng(patternRange);
          if (pattern.type === "inline-format") {
            each2(pattern.format, function(format3) {
              editor.formatter.apply(format3);
            });
          } else {
            editor.execCommand(pattern.cmd, false, pattern.value);
          }
        };
        var applyReplacementPattern = function(editor, pattern, marker, isRoot) {
          var markerRange = rangeFromMarker(editor.dom, marker);
          deleteRng(editor.dom, markerRange, isRoot);
          applyPattern(editor, pattern, markerRange);
        };
        var applyPatternWithContent = function(editor, pattern, startMarker, endMarker, isRoot) {
          var dom = editor.dom;
          var markerEndRange = rangeFromMarker(dom, endMarker);
          var markerStartRange = rangeFromMarker(dom, startMarker);
          deleteRng(dom, markerStartRange, isRoot);
          deleteRng(dom, markerEndRange, isRoot);
          var patternMarker = {
            prefix: startMarker.prefix,
            start: startMarker.end,
            end: endMarker.start
          };
          var patternRange = rangeFromMarker(dom, patternMarker);
          applyPattern(editor, pattern, patternRange);
        };
        var addMarkers = function(dom, matches) {
          var markerPrefix = generate("mce_textpattern");
          var matchesWithEnds = foldr(matches, function(acc, match2) {
            var endMarker = createMarker(dom, markerPrefix + ("_end" + acc.length), match2.endRng);
            return acc.concat([__assign(__assign({}, match2), { endMarker })]);
          }, []);
          return foldr(matchesWithEnds, function(acc, match2) {
            var idx = matchesWithEnds.length - acc.length - 1;
            var startMarker = isReplacementPattern(match2.pattern) ? match2.endMarker : createMarker(dom, markerPrefix + ("_start" + idx), match2.startRng);
            return acc.concat([__assign(__assign({}, match2), { startMarker })]);
          }, []);
        };
        var findPatterns = function(editor, patterns2, space) {
          var rng = editor.selection.getRng();
          if (rng.collapsed === false) {
            return [];
          }
          return getParentBlock(editor, rng).bind(function(block) {
            var offset2 = rng.startOffset - (space ? 1 : 0);
            return findPatternsRec(editor, patterns2, rng.startContainer, offset2, block);
          }).fold(function() {
            return [];
          }, function(result) {
            return result.matches;
          });
        };
        var applyMatches = function(editor, matches) {
          if (matches.length === 0) {
            return;
          }
          var dom = editor.dom;
          var bookmark = editor.selection.getBookmark();
          var matchesWithMarkers = addMarkers(dom, matches);
          each2(matchesWithMarkers, function(match2) {
            var block = dom.getParent(match2.startMarker.start, dom.isBlock);
            var isRoot = function(node) {
              return node === block;
            };
            if (isReplacementPattern(match2.pattern)) {
              applyReplacementPattern(editor, match2.pattern, match2.endMarker, isRoot);
            } else {
              applyPatternWithContent(editor, match2.pattern, match2.startMarker, match2.endMarker, isRoot);
            }
            removeMarker(dom, match2.endMarker, isRoot);
            removeMarker(dom, match2.startMarker, isRoot);
          });
          editor.selection.moveToBookmark(bookmark);
        };
        var handleEnter = function(editor, patternSet) {
          if (!editor.selection.isCollapsed()) {
            return false;
          }
          var inlineMatches = findPatterns(editor, patternSet.inlinePatterns, false);
          var blockMatches = findPatterns$1(editor, patternSet.blockPatterns);
          if (blockMatches.length > 0 || inlineMatches.length > 0) {
            editor.undoManager.add();
            editor.undoManager.extra(function() {
              editor.execCommand("mceInsertNewLine");
            }, function() {
              editor.insertContent(zeroWidth);
              applyMatches(editor, inlineMatches);
              applyMatches$1(editor, blockMatches);
              var range = editor.selection.getRng();
              var spot = textBefore(range.startContainer, range.startOffset, editor.dom.getRoot());
              editor.execCommand("mceInsertNewLine");
              spot.each(function(s2) {
                var node = s2.container;
                if (node.data.charAt(s2.offset - 1) === zeroWidth) {
                  node.deleteData(s2.offset - 1, 1);
                  cleanEmptyNodes(editor.dom, node.parentNode, function(e2) {
                    return e2 === editor.dom.getRoot();
                  });
                }
              });
            });
            return true;
          }
          return false;
        };
        var handleInlineKey = function(editor, patternSet) {
          var inlineMatches = findPatterns(editor, patternSet.inlinePatterns, true);
          if (inlineMatches.length > 0) {
            editor.undoManager.transact(function() {
              applyMatches(editor, inlineMatches);
            });
          }
        };
        var checkKeyEvent = function(codes, event, predicate) {
          for (var i2 = 0; i2 < codes.length; i2++) {
            if (predicate(codes[i2], event)) {
              return true;
            }
          }
          return false;
        };
        var checkKeyCode = function(codes, event) {
          return checkKeyEvent(codes, event, function(code, event2) {
            return code === event2.keyCode && global$3.modifierPressed(event2) === false;
          });
        };
        var checkCharCode = function(chars, event) {
          return checkKeyEvent(chars, event, function(chr, event2) {
            return chr.charCodeAt(0) === event2.charCode;
          });
        };
        var setup = function(editor, patternsState) {
          var charCodes = [
            ",",
            ".",
            ";",
            ":",
            "!",
            "?"
          ];
          var keyCodes = [32];
          editor.on("keydown", function(e2) {
            if (e2.keyCode === 13 && !global$3.modifierPressed(e2)) {
              if (handleEnter(editor, patternsState.get())) {
                e2.preventDefault();
              }
            }
          }, true);
          editor.on("keyup", function(e2) {
            if (checkKeyCode(keyCodes, e2)) {
              handleInlineKey(editor, patternsState.get());
            }
          });
          editor.on("keypress", function(e2) {
            if (checkCharCode(charCodes, e2)) {
              global$4.setEditorTimeout(editor, function() {
                handleInlineKey(editor, patternsState.get());
              });
            }
          });
        };
        function Plugin() {
          global$5.add("textpattern", function(editor) {
            var patternsState = Cell(getPatternSet(editor));
            setup(editor, patternsState);
            return get(patternsState);
          });
        }
        Plugin();
      })();
    }
  });

  // ../../node_modules/tinymce/plugins/noneditable/plugin.js
  var require_plugin25 = __commonJS({
    "../../node_modules/tinymce/plugins/noneditable/plugin.js"() {
      (function() {
        "use strict";
        var global$1 = tinymce.util.Tools.resolve("tinymce.PluginManager");
        var global2 = tinymce.util.Tools.resolve("tinymce.util.Tools");
        var getNonEditableClass = function(editor) {
          return editor.getParam("noneditable_noneditable_class", "mceNonEditable");
        };
        var getEditableClass = function(editor) {
          return editor.getParam("noneditable_editable_class", "mceEditable");
        };
        var getNonEditableRegExps = function(editor) {
          var nonEditableRegExps = editor.getParam("noneditable_regexp", []);
          if (nonEditableRegExps && nonEditableRegExps.constructor === RegExp) {
            return [nonEditableRegExps];
          } else {
            return nonEditableRegExps;
          }
        };
        var hasClass = function(checkClassName) {
          return function(node) {
            return (" " + node.attr("class") + " ").indexOf(checkClassName) !== -1;
          };
        };
        var replaceMatchWithSpan = function(editor, content, cls) {
          return function(match2) {
            var args = arguments, index = args[args.length - 2];
            var prevChar = index > 0 ? content.charAt(index - 1) : "";
            if (prevChar === '"') {
              return match2;
            }
            if (prevChar === ">") {
              var findStartTagIndex = content.lastIndexOf("<", index);
              if (findStartTagIndex !== -1) {
                var tagHtml = content.substring(findStartTagIndex, index);
                if (tagHtml.indexOf('contenteditable="false"') !== -1) {
                  return match2;
                }
              }
            }
            return '<span class="' + cls + '" data-mce-content="' + editor.dom.encode(args[0]) + '">' + editor.dom.encode(typeof args[1] === "string" ? args[1] : args[0]) + "</span>";
          };
        };
        var convertRegExpsToNonEditable = function(editor, nonEditableRegExps, e2) {
          var i2 = nonEditableRegExps.length, content = e2.content;
          if (e2.format === "raw") {
            return;
          }
          while (i2--) {
            content = content.replace(nonEditableRegExps[i2], replaceMatchWithSpan(editor, content, getNonEditableClass(editor)));
          }
          e2.content = content;
        };
        var setup = function(editor) {
          var contentEditableAttrName = "contenteditable";
          var editClass = " " + global2.trim(getEditableClass(editor)) + " ";
          var nonEditClass = " " + global2.trim(getNonEditableClass(editor)) + " ";
          var hasEditClass = hasClass(editClass);
          var hasNonEditClass = hasClass(nonEditClass);
          var nonEditableRegExps = getNonEditableRegExps(editor);
          editor.on("PreInit", function() {
            if (nonEditableRegExps.length > 0) {
              editor.on("BeforeSetContent", function(e2) {
                convertRegExpsToNonEditable(editor, nonEditableRegExps, e2);
              });
            }
            editor.parser.addAttributeFilter("class", function(nodes) {
              var i2 = nodes.length, node;
              while (i2--) {
                node = nodes[i2];
                if (hasEditClass(node)) {
                  node.attr(contentEditableAttrName, "true");
                } else if (hasNonEditClass(node)) {
                  node.attr(contentEditableAttrName, "false");
                }
              }
            });
            editor.serializer.addAttributeFilter(contentEditableAttrName, function(nodes) {
              var i2 = nodes.length, node;
              while (i2--) {
                node = nodes[i2];
                if (!hasEditClass(node) && !hasNonEditClass(node)) {
                  continue;
                }
                if (nonEditableRegExps.length > 0 && node.attr("data-mce-content")) {
                  node.name = "#text";
                  node.type = 3;
                  node.raw = true;
                  node.value = node.attr("data-mce-content");
                } else {
                  node.attr(contentEditableAttrName, null);
                }
              }
            });
          });
        };
        function Plugin() {
          global$1.add("noneditable", function(editor) {
            setup(editor);
          });
        }
        Plugin();
      })();
    }
  });

  // ../../node_modules/tinymce/plugins/help/plugin.js
  var require_plugin26 = __commonJS({
    "../../node_modules/tinymce/plugins/help/plugin.js"() {
      (function() {
        "use strict";
        var Cell = function(initial) {
          var value = initial;
          var get2 = function() {
            return value;
          };
          var set2 = function(v2) {
            value = v2;
          };
          return {
            get: get2,
            set: set2
          };
        };
        var global$3 = tinymce.util.Tools.resolve("tinymce.PluginManager");
        var get$1 = function(customTabs) {
          var addTab = function(spec) {
            var currentCustomTabs = customTabs.get();
            currentCustomTabs[spec.name] = spec;
            customTabs.set(currentCustomTabs);
          };
          return { addTab };
        };
        var register$1 = function(editor, dialogOpener) {
          editor.addCommand("mceHelp", dialogOpener);
        };
        var register = function(editor, dialogOpener) {
          editor.ui.registry.addButton("help", {
            icon: "help",
            tooltip: "Help",
            onAction: dialogOpener
          });
          editor.ui.registry.addMenuItem("help", {
            text: "Help",
            icon: "help",
            shortcut: "Alt+0",
            onAction: dialogOpener
          });
        };
        var __assign = function() {
          __assign = Object.assign || function __assign2(t2) {
            for (var s2, i2 = 1, n2 = arguments.length; i2 < n2; i2++) {
              s2 = arguments[i2];
              for (var p2 in s2)
                if (Object.prototype.hasOwnProperty.call(s2, p2))
                  t2[p2] = s2[p2];
            }
            return t2;
          };
          return __assign.apply(this, arguments);
        };
        var noop3 = function() {
        };
        var constant = function(value) {
          return function() {
            return value;
          };
        };
        var identity = function(x2) {
          return x2;
        };
        var never = constant(false);
        var always = constant(true);
        var none = function() {
          return NONE;
        };
        var NONE = function() {
          var call = function(thunk) {
            return thunk();
          };
          var id2 = identity;
          var me2 = {
            fold: function(n2, _s) {
              return n2();
            },
            isSome: never,
            isNone: always,
            getOr: id2,
            getOrThunk: call,
            getOrDie: function(msg) {
              throw new Error(msg || "error: getOrDie called on none.");
            },
            getOrNull: constant(null),
            getOrUndefined: constant(void 0),
            or: id2,
            orThunk: call,
            map: none,
            each: noop3,
            bind: none,
            exists: never,
            forall: always,
            filter: function() {
              return none();
            },
            toArray: function() {
              return [];
            },
            toString: constant("none()")
          };
          return me2;
        }();
        var some = function(a2) {
          var constant_a = constant(a2);
          var self2 = function() {
            return me2;
          };
          var bind = function(f2) {
            return f2(a2);
          };
          var me2 = {
            fold: function(n2, s2) {
              return s2(a2);
            },
            isSome: always,
            isNone: never,
            getOr: constant_a,
            getOrThunk: constant_a,
            getOrDie: constant_a,
            getOrNull: constant_a,
            getOrUndefined: constant_a,
            or: self2,
            orThunk: self2,
            map: function(f2) {
              return some(f2(a2));
            },
            each: function(f2) {
              f2(a2);
            },
            bind,
            exists: bind,
            forall: bind,
            filter: function(f2) {
              return f2(a2) ? me2 : NONE;
            },
            toArray: function() {
              return [a2];
            },
            toString: function() {
              return "some(" + a2 + ")";
            }
          };
          return me2;
        };
        var from = function(value) {
          return value === null || value === void 0 ? NONE : some(value);
        };
        var Optional = {
          some,
          none,
          from
        };
        var nativeIndexOf = Array.prototype.indexOf;
        var rawIndexOf = function(ts, t2) {
          return nativeIndexOf.call(ts, t2);
        };
        var contains2 = function(xs, x2) {
          return rawIndexOf(xs, x2) > -1;
        };
        var map3 = function(xs, f2) {
          var len = xs.length;
          var r2 = new Array(len);
          for (var i2 = 0; i2 < len; i2++) {
            var x2 = xs[i2];
            r2[i2] = f2(x2, i2);
          }
          return r2;
        };
        var filter = function(xs, pred) {
          var r2 = [];
          for (var i2 = 0, len = xs.length; i2 < len; i2++) {
            var x2 = xs[i2];
            if (pred(x2, i2)) {
              r2.push(x2);
            }
          }
          return r2;
        };
        var findUntil = function(xs, pred, until) {
          for (var i2 = 0, len = xs.length; i2 < len; i2++) {
            var x2 = xs[i2];
            if (pred(x2, i2)) {
              return Optional.some(x2);
            } else if (until(x2, i2)) {
              break;
            }
          }
          return Optional.none();
        };
        var find = function(xs, pred) {
          return findUntil(xs, pred, never);
        };
        var keys = Object.keys;
        var hasOwnProperty = Object.hasOwnProperty;
        var get = function(obj, key) {
          return has(obj, key) ? Optional.from(obj[key]) : Optional.none();
        };
        var has = function(obj, key) {
          return hasOwnProperty.call(obj, key);
        };
        var cat = function(arr) {
          var r2 = [];
          var push = function(x2) {
            r2.push(x2);
          };
          for (var i2 = 0; i2 < arr.length; i2++) {
            arr[i2].each(push);
          }
          return r2;
        };
        var getHelpTabs = function(editor) {
          return Optional.from(editor.getParam("help_tabs"));
        };
        var getForcedPlugins = function(editor) {
          return editor.getParam("forced_plugins");
        };
        var description = "<h1>Editor UI keyboard navigation</h1>\n\n<h2>Activating keyboard navigation</h2>\n\n<p>The sections of the outer UI of the editor - the menubar, toolbar, sidebar and footer - are all keyboard navigable. As such, there are multiple ways to activate keyboard navigation:</p>\n<ul>\n  <li>Focus the menubar: Alt + F9 (Windows) or &#x2325;F9 (MacOS)</li>\n  <li>Focus the toolbar: Alt + F10 (Windows) or &#x2325;F10 (MacOS)</li>\n  <li>Focus the footer: Alt + F11 (Windows) or &#x2325;F11 (MacOS)</li>\n</ul>\n\n<p>Focusing the menubar or toolbar will start keyboard navigation at the first item in the menubar or toolbar, which will be highlighted with a gray background. Focusing the footer will start keyboard navigation at the first item in the element path, which will be highlighted with an underline. </p>\n\n<h2>Moving between UI sections</h2>\n\n<p>When keyboard navigation is active, pressing tab will move the focus to the next major section of the UI, where applicable. These sections are:</p>\n<ul>\n  <li>the menubar</li>\n  <li>each group of the toolbar </li>\n  <li>the sidebar</li>\n  <li>the element path in the footer </li>\n  <li>the wordcount toggle button in the footer </li>\n  <li>the branding link in the footer </li>\n  <li>the editor resize handle in the footer</li>\n</ul>\n\n<p>Pressing shift + tab will move backwards through the same sections, except when moving from the footer to the toolbar. Focusing the element path then pressing shift + tab will move focus to the first toolbar group, not the last.</p>\n\n<h2>Moving within UI sections</h2>\n\n<p>Keyboard navigation within UI sections can usually be achieved using the left and right arrow keys. This includes:</p>\n<ul>\n  <li>moving between menus in the menubar</li>\n  <li>moving between buttons in a toolbar group</li>\n  <li>moving between items in the element path</li>\n</ul>\n\n<p>In all these UI sections, keyboard navigation will cycle within the section. For example, focusing the last button in a toolbar group then pressing right arrow will move focus to the first item in the same toolbar group. </p>\n\n<h1>Executing buttons</h1>\n\n<p>To execute a button, navigate the selection to the desired button and hit space or enter.</p>\n\n<h1>Opening, navigating and closing menus</h1>\n\n<p>When focusing a menubar button or a toolbar button with a menu, pressing space, enter or down arrow will open the menu. When the menu opens the first item will be selected. To move up or down the menu, press the up or down arrow key respectively. This is the same for submenus, which can also be opened and closed using the left and right arrow keys.</p>\n\n<p>To close any active menu, hit the escape key. When a menu is closed the selection will be restored to its previous selection. This also works for closing submenus.</p>\n\n<h1>Context toolbars and menus</h1>\n\n<p>To focus an open context toolbar such as the table context toolbar, press Ctrl + F9 (Windows) or &#x2303;F9 (MacOS).</p>\n\n<p>Context toolbar navigation is the same as toolbar navigation, and context menu navigation is the same as standard menu navigation.</p>\n\n<h1>Dialog navigation</h1>\n\n<p>There are two types of dialog UIs in TinyMCE: tabbed dialogs and non-tabbed dialogs.</p>\n\n<p>When a non-tabbed dialog is opened, the first interactive component in the dialog will be focused. Users can navigate between interactive components by pressing tab. This includes any footer buttons. Navigation will cycle back to the first dialog component if tab is pressed while focusing the last component in the dialog. Pressing shift + tab will navigate backwards.</p>\n\n<p>When a tabbed dialog is opened, the first button in the tab menu is focused. Pressing tab will navigate to the first interactive component in that tab, and will cycle through the tab\u2019s components, the footer buttons, then back to the tab button. To switch to another tab, focus the tab button for the current tab, then use the arrow keys to cycle through the tab buttons.</p>";
        var tab$3 = function() {
          var body = {
            type: "htmlpanel",
            presets: "document",
            html: description
          };
          return {
            name: "keyboardnav",
            title: "Keyboard Navigation",
            items: [body]
          };
        };
        var global$2 = tinymce.util.Tools.resolve("tinymce.Env");
        var convertText = function(source) {
          var mac = {
            alt: "&#x2325;",
            ctrl: "&#x2303;",
            shift: "&#x21E7;",
            meta: "&#x2318;",
            access: "&#x2303;&#x2325;"
          };
          var other = {
            meta: "Ctrl ",
            access: "Shift + Alt "
          };
          var replace = global$2.mac ? mac : other;
          var shortcut = source.split("+");
          var updated = map3(shortcut, function(segment) {
            var search = segment.toLowerCase().trim();
            return has(replace, search) ? replace[search] : segment;
          });
          return global$2.mac ? updated.join("").replace(/\s/, "") : updated.join("+");
        };
        var shortcuts = [
          {
            shortcuts: ["Meta + B"],
            action: "Bold"
          },
          {
            shortcuts: ["Meta + I"],
            action: "Italic"
          },
          {
            shortcuts: ["Meta + U"],
            action: "Underline"
          },
          {
            shortcuts: ["Meta + A"],
            action: "Select all"
          },
          {
            shortcuts: [
              "Meta + Y",
              "Meta + Shift + Z"
            ],
            action: "Redo"
          },
          {
            shortcuts: ["Meta + Z"],
            action: "Undo"
          },
          {
            shortcuts: ["Access + 1"],
            action: "Heading 1"
          },
          {
            shortcuts: ["Access + 2"],
            action: "Heading 2"
          },
          {
            shortcuts: ["Access + 3"],
            action: "Heading 3"
          },
          {
            shortcuts: ["Access + 4"],
            action: "Heading 4"
          },
          {
            shortcuts: ["Access + 5"],
            action: "Heading 5"
          },
          {
            shortcuts: ["Access + 6"],
            action: "Heading 6"
          },
          {
            shortcuts: ["Access + 7"],
            action: "Paragraph"
          },
          {
            shortcuts: ["Access + 8"],
            action: "Div"
          },
          {
            shortcuts: ["Access + 9"],
            action: "Address"
          },
          {
            shortcuts: ["Alt + 0"],
            action: "Open help dialog"
          },
          {
            shortcuts: ["Alt + F9"],
            action: "Focus to menubar"
          },
          {
            shortcuts: ["Alt + F10"],
            action: "Focus to toolbar"
          },
          {
            shortcuts: ["Alt + F11"],
            action: "Focus to element path"
          },
          {
            shortcuts: ["Ctrl + F9"],
            action: "Focus to contextual toolbar"
          },
          {
            shortcuts: ["Shift + Enter"],
            action: "Open popup menu for split buttons"
          },
          {
            shortcuts: ["Meta + K"],
            action: "Insert link (if link plugin activated)"
          },
          {
            shortcuts: ["Meta + S"],
            action: "Save (if save plugin activated)"
          },
          {
            shortcuts: ["Meta + F"],
            action: "Find (if searchreplace plugin activated)"
          },
          {
            shortcuts: ["Meta + Shift + F"],
            action: "Switch to or from fullscreen mode"
          }
        ];
        var tab$2 = function() {
          var shortcutList = map3(shortcuts, function(shortcut) {
            var shortcutText = map3(shortcut.shortcuts, convertText).join(" or ");
            return [
              shortcut.action,
              shortcutText
            ];
          });
          var tablePanel = {
            type: "table",
            header: [
              "Action",
              "Shortcut"
            ],
            cells: shortcutList
          };
          return {
            name: "shortcuts",
            title: "Handy Shortcuts",
            items: [tablePanel]
          };
        };
        var global$1 = tinymce.util.Tools.resolve("tinymce.util.I18n");
        var urls = map3([
          {
            key: "advlist",
            name: "Advanced List"
          },
          {
            key: "anchor",
            name: "Anchor"
          },
          {
            key: "autolink",
            name: "Autolink"
          },
          {
            key: "autoresize",
            name: "Autoresize"
          },
          {
            key: "autosave",
            name: "Autosave"
          },
          {
            key: "bbcode",
            name: "BBCode"
          },
          {
            key: "charmap",
            name: "Character Map"
          },
          {
            key: "code",
            name: "Code"
          },
          {
            key: "codesample",
            name: "Code Sample"
          },
          {
            key: "colorpicker",
            name: "Color Picker"
          },
          {
            key: "directionality",
            name: "Directionality"
          },
          {
            key: "emoticons",
            name: "Emoticons"
          },
          {
            key: "fullpage",
            name: "Full Page"
          },
          {
            key: "fullscreen",
            name: "Full Screen"
          },
          {
            key: "help",
            name: "Help"
          },
          {
            key: "hr",
            name: "Horizontal Rule"
          },
          {
            key: "image",
            name: "Image"
          },
          {
            key: "imagetools",
            name: "Image Tools"
          },
          {
            key: "importcss",
            name: "Import CSS"
          },
          {
            key: "insertdatetime",
            name: "Insert Date/Time"
          },
          {
            key: "legacyoutput",
            name: "Legacy Output"
          },
          {
            key: "link",
            name: "Link"
          },
          {
            key: "lists",
            name: "Lists"
          },
          {
            key: "media",
            name: "Media"
          },
          {
            key: "nonbreaking",
            name: "Nonbreaking"
          },
          {
            key: "noneditable",
            name: "Noneditable"
          },
          {
            key: "pagebreak",
            name: "Page Break"
          },
          {
            key: "paste",
            name: "Paste"
          },
          {
            key: "preview",
            name: "Preview"
          },
          {
            key: "print",
            name: "Print"
          },
          {
            key: "quickbars",
            name: "Quick Toolbars"
          },
          {
            key: "save",
            name: "Save"
          },
          {
            key: "searchreplace",
            name: "Search and Replace"
          },
          {
            key: "spellchecker",
            name: "Spell Checker"
          },
          {
            key: "tabfocus",
            name: "Tab Focus"
          },
          {
            key: "table",
            name: "Table"
          },
          {
            key: "template",
            name: "Template"
          },
          {
            key: "textcolor",
            name: "Text Color"
          },
          {
            key: "textpattern",
            name: "Text Pattern"
          },
          {
            key: "toc",
            name: "Table of Contents"
          },
          {
            key: "visualblocks",
            name: "Visual Blocks"
          },
          {
            key: "visualchars",
            name: "Visual Characters"
          },
          {
            key: "wordcount",
            name: "Word Count"
          },
          {
            key: "a11ychecker",
            name: "Accessibility Checker",
            type: "premium"
          },
          {
            key: "advcode",
            name: "Advanced Code Editor",
            type: "premium"
          },
          {
            key: "advtable",
            name: "Advanced Tables",
            type: "premium"
          },
          {
            key: "autocorrect",
            name: "Autocorrect",
            type: "premium"
          },
          {
            key: "casechange",
            name: "Case Change",
            type: "premium"
          },
          {
            key: "checklist",
            name: "Checklist",
            type: "premium"
          },
          {
            key: "export",
            name: "Export",
            type: "premium"
          },
          {
            key: "mediaembed",
            name: "Enhanced Media Embed",
            type: "premium"
          },
          {
            key: "formatpainter",
            name: "Format Painter",
            type: "premium"
          },
          {
            key: "linkchecker",
            name: "Link Checker",
            type: "premium"
          },
          {
            key: "mentions",
            name: "Mentions",
            type: "premium"
          },
          {
            key: "pageembed",
            name: "Page Embed",
            type: "premium"
          },
          {
            key: "permanentpen",
            name: "Permanent Pen",
            type: "premium"
          },
          {
            key: "powerpaste",
            name: "PowerPaste",
            type: "premium"
          },
          {
            key: "rtc",
            name: "Real-Time Collaboration",
            type: "premium"
          },
          {
            key: "tinymcespellchecker",
            name: "Spell Checker Pro",
            type: "premium"
          },
          {
            key: "tinycomments",
            name: "Tiny Comments",
            type: "premium",
            slug: "comments"
          },
          {
            key: "tinydrive",
            name: "Tiny Drive",
            type: "premium"
          }
        ], function(item) {
          return __assign(__assign({}, item), {
            type: item.type || "opensource",
            slug: item.slug || item.key
          });
        });
        var tab$1 = function(editor) {
          var availablePlugins = function() {
            var premiumPlugins = filter(urls, function(_a) {
              var key = _a.key, type = _a.type;
              return key !== "autocorrect" && type === "premium";
            });
            var premiumPluginList = map3(premiumPlugins, function(plugin) {
              return "<li>" + global$1.translate(plugin.name) + "</li>";
            }).join("");
            return '<div data-mce-tabstop="1" tabindex="-1"><p><b>' + global$1.translate("Premium plugins:") + "</b></p><ul>" + premiumPluginList + '<li class="tox-help__more-link" "><a href="https://www.tiny.cloud/pricing/?utm_campaign=editor_referral&utm_medium=help_dialog&utm_source=tinymce" target="_blank">' + global$1.translate("Learn more...") + "</a></li></ul></div>";
          };
          var makeLink = function(p2) {
            return '<a href="' + p2.url + '" target="_blank" rel="noopener">' + p2.name + "</a>";
          };
          var maybeUrlize = function(editor2, key) {
            return find(urls, function(x2) {
              return x2.key === key;
            }).fold(function() {
              var getMetadata = editor2.plugins[key].getMetadata;
              return typeof getMetadata === "function" ? makeLink(getMetadata()) : key;
            }, function(x2) {
              var name = x2.type === "premium" ? x2.name + "*" : x2.name;
              return makeLink({
                name,
                url: "https://www.tiny.cloud/docs/plugins/" + x2.type + "/" + x2.slug
              });
            });
          };
          var getPluginKeys = function(editor2) {
            var keys$1 = keys(editor2.plugins);
            var forced_plugins = getForcedPlugins(editor2);
            return forced_plugins === void 0 ? keys$1 : filter(keys$1, function(k2) {
              return !contains2(forced_plugins, k2);
            });
          };
          var pluginLister = function(editor2) {
            var pluginKeys = getPluginKeys(editor2);
            var pluginLis = map3(pluginKeys, function(key) {
              return "<li>" + maybeUrlize(editor2, key) + "</li>";
            });
            var count = pluginLis.length;
            var pluginsString = pluginLis.join("");
            var html = "<p><b>" + global$1.translate([
              "Plugins installed ({0}):",
              count
            ]) + "</b></p><ul>" + pluginsString + "</ul>";
            return html;
          };
          var installedPlugins = function(editor2) {
            if (editor2 == null) {
              return "";
            }
            return '<div data-mce-tabstop="1" tabindex="-1">' + pluginLister(editor2) + "</div>";
          };
          var htmlPanel = {
            type: "htmlpanel",
            presets: "document",
            html: [
              installedPlugins(editor),
              availablePlugins()
            ].join("")
          };
          return {
            name: "plugins",
            title: "Plugins",
            items: [htmlPanel]
          };
        };
        var global2 = tinymce.util.Tools.resolve("tinymce.EditorManager");
        var tab = function() {
          var getVersion = function(major, minor) {
            return major.indexOf("@") === 0 ? "X.X.X" : major + "." + minor;
          };
          var version2 = getVersion(global2.majorVersion, global2.minorVersion);
          var changeLogLink = '<a href="https://www.tiny.cloud/docs/changelog/?utm_campaign=editor_referral&utm_medium=help_dialog&utm_source=tinymce" target="_blank">TinyMCE ' + version2 + "</a>";
          var htmlPanel = {
            type: "htmlpanel",
            html: "<p>" + global$1.translate([
              "You are using {0}",
              changeLogLink
            ]) + "</p>",
            presets: "document"
          };
          return {
            name: "versions",
            title: "Version",
            items: [htmlPanel]
          };
        };
        var parseHelpTabsSetting = function(tabsFromSettings, tabs) {
          var newTabs = {};
          var names2 = map3(tabsFromSettings, function(t2) {
            if (typeof t2 === "string") {
              if (has(tabs, t2)) {
                newTabs[t2] = tabs[t2];
              }
              return t2;
            } else {
              newTabs[t2.name] = t2;
              return t2.name;
            }
          });
          return {
            tabs: newTabs,
            names: names2
          };
        };
        var getNamesFromTabs = function(tabs) {
          var names2 = keys(tabs);
          var idx = names2.indexOf("versions");
          if (idx !== -1) {
            names2.splice(idx, 1);
            names2.push("versions");
          }
          return {
            tabs,
            names: names2
          };
        };
        var parseCustomTabs = function(editor, customTabs) {
          var _a;
          var shortcuts2 = tab$2();
          var nav = tab$3();
          var plugins2 = tab$1(editor);
          var versions = tab();
          var tabs = __assign((_a = {}, _a[shortcuts2.name] = shortcuts2, _a[nav.name] = nav, _a[plugins2.name] = plugins2, _a[versions.name] = versions, _a), customTabs.get());
          return getHelpTabs(editor).fold(function() {
            return getNamesFromTabs(tabs);
          }, function(tabsFromSettings) {
            return parseHelpTabsSetting(tabsFromSettings, tabs);
          });
        };
        var init = function(editor, customTabs) {
          return function() {
            var _a = parseCustomTabs(editor, customTabs), tabs = _a.tabs, names2 = _a.names;
            var foundTabs = map3(names2, function(name) {
              return get(tabs, name);
            });
            var dialogTabs = cat(foundTabs);
            var body = {
              type: "tabpanel",
              tabs: dialogTabs
            };
            editor.windowManager.open({
              title: "Help",
              size: "medium",
              body,
              buttons: [{
                type: "cancel",
                name: "close",
                text: "Close",
                primary: true
              }],
              initialData: {}
            });
          };
        };
        function Plugin() {
          global$3.add("help", function(editor) {
            var customTabs = Cell({});
            var api = get$1(customTabs);
            var dialogOpener = init(editor, customTabs);
            register(editor, dialogOpener);
            register$1(editor, dialogOpener);
            editor.shortcuts.add("Alt+0", "Open help dialog", "mceHelp");
            return api;
          });
        }
        Plugin();
      })();
    }
  });

  // ../../node_modules/tinymce/plugins/quickbars/plugin.js
  var require_plugin27 = __commonJS({
    "../../node_modules/tinymce/plugins/quickbars/plugin.js"() {
      (function() {
        "use strict";
        var global$3 = tinymce.util.Tools.resolve("tinymce.PluginManager");
        var unique = 0;
        var generate = function(prefix) {
          var date = new Date();
          var time = date.getTime();
          var random = Math.floor(Math.random() * 1e9);
          unique++;
          return prefix + "_" + random + unique + String(time);
        };
        var createTableHtml = function(cols, rows) {
          var html = '<table data-mce-id="mce" style="width: 100%">';
          html += "<tbody>";
          for (var y2 = 0; y2 < rows; y2++) {
            html += "<tr>";
            for (var x2 = 0; x2 < cols; x2++) {
              html += "<td><br></td>";
            }
            html += "</tr>";
          }
          html += "</tbody>";
          html += "</table>";
          return html;
        };
        var getInsertedElement = function(editor) {
          var elms = editor.dom.select("*[data-mce-id]");
          return elms[0];
        };
        var insertTableHtml = function(editor, cols, rows) {
          editor.undoManager.transact(function() {
            editor.insertContent(createTableHtml(cols, rows));
            var tableElm = getInsertedElement(editor);
            tableElm.removeAttribute("data-mce-id");
            var cellElm = editor.dom.select("td,th", tableElm);
            editor.selection.setCursorLocation(cellElm[0], 0);
          });
        };
        var insertTable = function(editor, cols, rows) {
          editor.plugins.table ? editor.plugins.table.insertTable(cols, rows) : insertTableHtml(editor, cols, rows);
        };
        var insertBlob = function(editor, base64, blob) {
          var blobCache = editor.editorUpload.blobCache;
          var blobInfo = blobCache.create(generate("mceu"), blob, base64);
          blobCache.add(blobInfo);
          editor.insertContent(editor.dom.createHTML("img", { src: blobInfo.blobUri() }));
        };
        var global$2 = tinymce.util.Tools.resolve("tinymce.util.Promise");
        var blobToBase64 = function(blob) {
          return new global$2(function(resolve2) {
            var reader = new FileReader();
            reader.onloadend = function() {
              resolve2(reader.result.split(",")[1]);
            };
            reader.readAsDataURL(blob);
          });
        };
        var global$1 = tinymce.util.Tools.resolve("tinymce.Env");
        var global2 = tinymce.util.Tools.resolve("tinymce.util.Delay");
        var pickFile = function(editor) {
          return new global$2(function(resolve2) {
            var fileInput = document.createElement("input");
            fileInput.type = "file";
            fileInput.accept = "image/*";
            fileInput.style.position = "fixed";
            fileInput.style.left = "0";
            fileInput.style.top = "0";
            fileInput.style.opacity = "0.001";
            document.body.appendChild(fileInput);
            var changeHandler = function(e2) {
              resolve2(Array.prototype.slice.call(e2.target.files));
            };
            fileInput.addEventListener("change", changeHandler);
            var cancelHandler = function(e2) {
              var cleanup = function() {
                resolve2([]);
                fileInput.parentNode.removeChild(fileInput);
              };
              if (global$1.os.isAndroid() && e2.type !== "remove") {
                global2.setEditorTimeout(editor, cleanup, 0);
              } else {
                cleanup();
              }
              editor.off("focusin remove", cancelHandler);
            };
            editor.on("focusin remove", cancelHandler);
            fileInput.click();
          });
        };
        var setupButtons = function(editor) {
          editor.ui.registry.addButton("quickimage", {
            icon: "image",
            tooltip: "Insert image",
            onAction: function() {
              pickFile(editor).then(function(files) {
                if (files.length > 0) {
                  var blob_1 = files[0];
                  blobToBase64(blob_1).then(function(base64) {
                    insertBlob(editor, base64, blob_1);
                  });
                }
              });
            }
          });
          editor.ui.registry.addButton("quicktable", {
            icon: "table",
            tooltip: "Insert table",
            onAction: function() {
              insertTable(editor, 2, 2);
            }
          });
        };
        var typeOf = function(x2) {
          var t2 = typeof x2;
          if (x2 === null) {
            return "null";
          } else if (t2 === "object" && (Array.prototype.isPrototypeOf(x2) || x2.constructor && x2.constructor.name === "Array")) {
            return "array";
          } else if (t2 === "object" && (String.prototype.isPrototypeOf(x2) || x2.constructor && x2.constructor.name === "String")) {
            return "string";
          } else {
            return t2;
          }
        };
        var isType = function(type) {
          return function(value) {
            return typeOf(value) === type;
          };
        };
        var isSimpleType = function(type) {
          return function(value) {
            return typeof value === type;
          };
        };
        var eq2 = function(t2) {
          return function(a2) {
            return t2 === a2;
          };
        };
        var isString = isType("string");
        var isObject2 = isType("object");
        var isArray2 = isType("array");
        var isBoolean = isSimpleType("boolean");
        var isUndefined = eq2(void 0);
        var isFunction2 = isSimpleType("function");
        var noop3 = function() {
        };
        var constant = function(value) {
          return function() {
            return value;
          };
        };
        var identity = function(x2) {
          return x2;
        };
        var never = constant(false);
        var always = constant(true);
        var none = function() {
          return NONE;
        };
        var NONE = function() {
          var call = function(thunk) {
            return thunk();
          };
          var id2 = identity;
          var me2 = {
            fold: function(n2, _s) {
              return n2();
            },
            isSome: never,
            isNone: always,
            getOr: id2,
            getOrThunk: call,
            getOrDie: function(msg) {
              throw new Error(msg || "error: getOrDie called on none.");
            },
            getOrNull: constant(null),
            getOrUndefined: constant(void 0),
            or: id2,
            orThunk: call,
            map: none,
            each: noop3,
            bind: none,
            exists: never,
            forall: always,
            filter: function() {
              return none();
            },
            toArray: function() {
              return [];
            },
            toString: constant("none()")
          };
          return me2;
        }();
        var some = function(a2) {
          var constant_a = constant(a2);
          var self2 = function() {
            return me2;
          };
          var bind = function(f2) {
            return f2(a2);
          };
          var me2 = {
            fold: function(n2, s2) {
              return s2(a2);
            },
            isSome: always,
            isNone: never,
            getOr: constant_a,
            getOrThunk: constant_a,
            getOrDie: constant_a,
            getOrNull: constant_a,
            getOrUndefined: constant_a,
            or: self2,
            orThunk: self2,
            map: function(f2) {
              return some(f2(a2));
            },
            each: function(f2) {
              f2(a2);
            },
            bind,
            exists: bind,
            forall: bind,
            filter: function(f2) {
              return f2(a2) ? me2 : NONE;
            },
            toArray: function() {
              return [a2];
            },
            toString: function() {
              return "some(" + a2 + ")";
            }
          };
          return me2;
        };
        var from = function(value) {
          return value === null || value === void 0 ? NONE : some(value);
        };
        var Optional = {
          some,
          none,
          from
        };
        function ClosestOrAncestor(is2, ancestor2, scope, a2, isRoot) {
          if (is2(scope, a2)) {
            return Optional.some(scope);
          } else if (isFunction2(isRoot) && isRoot(scope)) {
            return Optional.none();
          } else {
            return ancestor2(scope, a2, isRoot);
          }
        }
        var ELEMENT = 1;
        var fromHtml = function(html, scope) {
          var doc = scope || document;
          var div = doc.createElement("div");
          div.innerHTML = html;
          if (!div.hasChildNodes() || div.childNodes.length > 1) {
            console.error("HTML does not have a single root node", html);
            throw new Error("HTML must have a single root node");
          }
          return fromDom(div.childNodes[0]);
        };
        var fromTag = function(tag, scope) {
          var doc = scope || document;
          var node = doc.createElement(tag);
          return fromDom(node);
        };
        var fromText = function(text, scope) {
          var doc = scope || document;
          var node = doc.createTextNode(text);
          return fromDom(node);
        };
        var fromDom = function(node) {
          if (node === null || node === void 0) {
            throw new Error("Node cannot be null or undefined");
          }
          return { dom: node };
        };
        var fromPoint = function(docElm, x2, y2) {
          return Optional.from(docElm.dom.elementFromPoint(x2, y2)).map(fromDom);
        };
        var SugarElement = {
          fromHtml,
          fromTag,
          fromText,
          fromDom,
          fromPoint
        };
        var is = function(element, selector) {
          var dom = element.dom;
          if (dom.nodeType !== ELEMENT) {
            return false;
          } else {
            var elem = dom;
            if (elem.matches !== void 0) {
              return elem.matches(selector);
            } else if (elem.msMatchesSelector !== void 0) {
              return elem.msMatchesSelector(selector);
            } else if (elem.webkitMatchesSelector !== void 0) {
              return elem.webkitMatchesSelector(selector);
            } else if (elem.mozMatchesSelector !== void 0) {
              return elem.mozMatchesSelector(selector);
            } else {
              throw new Error("Browser lacks native selectors");
            }
          }
        };
        typeof window !== "undefined" ? window : Function("return this;")();
        var name = function(element) {
          var r2 = element.dom.nodeName;
          return r2.toLowerCase();
        };
        var ancestor$1 = function(scope, predicate, isRoot) {
          var element = scope.dom;
          var stop = isFunction2(isRoot) ? isRoot : never;
          while (element.parentNode) {
            element = element.parentNode;
            var el = SugarElement.fromDom(element);
            if (predicate(el)) {
              return Optional.some(el);
            } else if (stop(el)) {
              break;
            }
          }
          return Optional.none();
        };
        var closest$1 = function(scope, predicate, isRoot) {
          var is2 = function(s2, test) {
            return test(s2);
          };
          return ClosestOrAncestor(is2, ancestor$1, scope, predicate, isRoot);
        };
        var ancestor = function(scope, selector, isRoot) {
          return ancestor$1(scope, function(e2) {
            return is(e2, selector);
          }, isRoot);
        };
        var closest = function(scope, selector, isRoot) {
          var is$1 = function(element, selector2) {
            return is(element, selector2);
          };
          return ClosestOrAncestor(is$1, ancestor, scope, selector, isRoot);
        };
        var validDefaultOrDie = function(value, predicate) {
          if (predicate(value)) {
            return true;
          }
          throw new Error("Default value doesn't match requested type.");
        };
        var items = function(value, defaultValue) {
          if (isArray2(value) || isObject2(value)) {
            throw new Error("expected a string but found: " + value);
          }
          if (isUndefined(value)) {
            return defaultValue;
          }
          if (isBoolean(value)) {
            return value === false ? "" : defaultValue;
          }
          return value;
        };
        var getToolbarItemsOr_ = function(predicate) {
          return function(editor, name2, defaultValue) {
            validDefaultOrDie(defaultValue, predicate);
            var value = editor.getParam(name2, defaultValue);
            return items(value, defaultValue);
          };
        };
        var getToolbarItemsOr = getToolbarItemsOr_(isString);
        var getTextSelectionToolbarItems = function(editor) {
          return getToolbarItemsOr(editor, "quickbars_selection_toolbar", "bold italic | quicklink h2 h3 blockquote");
        };
        var getInsertToolbarItems = function(editor) {
          return getToolbarItemsOr(editor, "quickbars_insert_toolbar", "quickimage quicktable");
        };
        var getImageToolbarItems = function(editor) {
          return getToolbarItemsOr(editor, "quickbars_image_toolbar", "alignleft aligncenter alignright");
        };
        var addToEditor$1 = function(editor) {
          var insertToolbarItems = getInsertToolbarItems(editor);
          if (insertToolbarItems.trim().length > 0) {
            editor.ui.registry.addContextToolbar("quickblock", {
              predicate: function(node) {
                var sugarNode = SugarElement.fromDom(node);
                var textBlockElementsMap = editor.schema.getTextBlockElements();
                var isRoot = function(elem) {
                  return elem.dom === editor.getBody();
                };
                return closest(sugarNode, "table", isRoot).fold(function() {
                  return closest$1(sugarNode, function(elem) {
                    return name(elem) in textBlockElementsMap && editor.dom.isEmpty(elem.dom);
                  }, isRoot).isSome();
                }, never);
              },
              items: insertToolbarItems,
              position: "line",
              scope: "editor"
            });
          }
        };
        var addToEditor = function(editor) {
          var isEditable = function(node) {
            return editor.dom.getContentEditableParent(node) !== "false";
          };
          var isImage = function(node) {
            return node.nodeName === "IMG" || node.nodeName === "FIGURE" && /image/i.test(node.className);
          };
          var imageToolbarItems = getImageToolbarItems(editor);
          if (imageToolbarItems.trim().length > 0) {
            editor.ui.registry.addContextToolbar("imageselection", {
              predicate: isImage,
              items: imageToolbarItems,
              position: "node"
            });
          }
          var textToolbarItems = getTextSelectionToolbarItems(editor);
          if (textToolbarItems.trim().length > 0) {
            editor.ui.registry.addContextToolbar("textselection", {
              predicate: function(node) {
                return !isImage(node) && !editor.selection.isCollapsed() && isEditable(node);
              },
              items: textToolbarItems,
              position: "selection",
              scope: "editor"
            });
          }
        };
        function Plugin() {
          global$3.add("quickbars", function(editor) {
            setupButtons(editor);
            addToEditor$1(editor);
            addToEditor(editor);
          });
        }
        Plugin();
      })();
    }
  });

  // ../../node_modules/@honeybadger-io/js/dist/browser/honeybadger.js
  var require_honeybadger = __commonJS({
    "../../node_modules/@honeybadger-io/js/dist/browser/honeybadger.js"(exports, module) {
      (function(global2, factory) {
        typeof exports === "object" && typeof module !== "undefined" ? module.exports = factory() : typeof define === "function" && define.amd ? define(factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, global2.Honeybadger = factory());
      })(exports, function() {
        "use strict";
        var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
        function getDefaultExportFromCjs(x2) {
          return x2 && x2.__esModule && Object.prototype.hasOwnProperty.call(x2, "default") ? x2["default"] : x2;
        }
        function getAugmentedNamespace(n2) {
          var f2 = n2.default;
          if (typeof f2 == "function") {
            var a2 = function() {
              return f2.apply(this, arguments);
            };
            a2.prototype = f2.prototype;
          } else
            a2 = {};
          Object.defineProperty(a2, "__esModule", { value: true });
          Object.keys(n2).forEach(function(k2) {
            var d2 = Object.getOwnPropertyDescriptor(n2, k2);
            Object.defineProperty(a2, k2, d2.get ? d2 : {
              enumerable: true,
              get: function() {
                return n2[k2];
              }
            });
          });
          return a2;
        }
        var browser$1 = {};
        var src = {};
        var client = {};
        var util$1 = {};
        var UNKNOWN_FUNCTION = "<unknown>";
        function parse3(stackString) {
          var lines = stackString.split("\n");
          return lines.reduce(function(stack, line) {
            var parseResult = parseChrome(line) || parseWinjs(line) || parseGecko(line) || parseNode(line) || parseJSC(line);
            if (parseResult) {
              stack.push(parseResult);
            }
            return stack;
          }, []);
        }
        var chromeRe = /^\s*at (.*?) ?\(((?:file|https?|blob|chrome-extension|native|eval|webpack|<anonymous>|\/|[a-z]:\\|\\\\).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i;
        var chromeEvalRe = /\((\S*)(?::(\d+))(?::(\d+))\)/;
        function parseChrome(line) {
          var parts = chromeRe.exec(line);
          if (!parts) {
            return null;
          }
          var isNative2 = parts[2] && parts[2].indexOf("native") === 0;
          var isEval = parts[2] && parts[2].indexOf("eval") === 0;
          var submatch = chromeEvalRe.exec(parts[2]);
          if (isEval && submatch != null) {
            parts[2] = submatch[1];
            parts[3] = submatch[2];
            parts[4] = submatch[3];
          }
          return {
            file: !isNative2 ? parts[2] : null,
            methodName: parts[1] || UNKNOWN_FUNCTION,
            arguments: isNative2 ? [parts[2]] : [],
            lineNumber: parts[3] ? +parts[3] : null,
            column: parts[4] ? +parts[4] : null
          };
        }
        var winjsRe = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i;
        function parseWinjs(line) {
          var parts = winjsRe.exec(line);
          if (!parts) {
            return null;
          }
          return {
            file: parts[2],
            methodName: parts[1] || UNKNOWN_FUNCTION,
            arguments: [],
            lineNumber: +parts[3],
            column: parts[4] ? +parts[4] : null
          };
        }
        var geckoRe = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i;
        var geckoEvalRe = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i;
        function parseGecko(line) {
          var parts = geckoRe.exec(line);
          if (!parts) {
            return null;
          }
          var isEval = parts[3] && parts[3].indexOf(" > eval") > -1;
          var submatch = geckoEvalRe.exec(parts[3]);
          if (isEval && submatch != null) {
            parts[3] = submatch[1];
            parts[4] = submatch[2];
            parts[5] = null;
          }
          return {
            file: parts[3],
            methodName: parts[1] || UNKNOWN_FUNCTION,
            arguments: parts[2] ? parts[2].split(",") : [],
            lineNumber: parts[4] ? +parts[4] : null,
            column: parts[5] ? +parts[5] : null
          };
        }
        var javaScriptCoreRe = /^\s*(?:([^@]*)(?:\((.*?)\))?@)?(\S.*?):(\d+)(?::(\d+))?\s*$/i;
        function parseJSC(line) {
          var parts = javaScriptCoreRe.exec(line);
          if (!parts) {
            return null;
          }
          return {
            file: parts[3],
            methodName: parts[1] || UNKNOWN_FUNCTION,
            arguments: [],
            lineNumber: +parts[4],
            column: parts[5] ? +parts[5] : null
          };
        }
        var nodeRe = /^\s*at (?:((?:\[object object\])?[^\\/]+(?: \[as \S+\])?) )?\(?(.*?):(\d+)(?::(\d+))?\)?\s*$/i;
        function parseNode(line) {
          var parts = nodeRe.exec(line);
          if (!parts) {
            return null;
          }
          return {
            file: parts[2],
            methodName: parts[1] || UNKNOWN_FUNCTION,
            arguments: [],
            lineNumber: +parts[3],
            column: parts[4] ? +parts[4] : null
          };
        }
        var stackTraceParser_esm = /* @__PURE__ */ Object.freeze({
          __proto__: null,
          parse: parse3
        });
        var require$$0$1 = /* @__PURE__ */ getAugmentedNamespace(stackTraceParser_esm);
        (function(exports2) {
          var __createBinding = commonjsGlobal && commonjsGlobal.__createBinding || (Object.create ? function(o2, m2, k2, k22) {
            if (k22 === void 0)
              k22 = k2;
            var desc = Object.getOwnPropertyDescriptor(m2, k2);
            if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) {
              desc = { enumerable: true, get: function() {
                return m2[k2];
              } };
            }
            Object.defineProperty(o2, k22, desc);
          } : function(o2, m2, k2, k22) {
            if (k22 === void 0)
              k22 = k2;
            o2[k22] = m2[k2];
          });
          var __setModuleDefault = commonjsGlobal && commonjsGlobal.__setModuleDefault || (Object.create ? function(o2, v2) {
            Object.defineProperty(o2, "default", { enumerable: true, value: v2 });
          } : function(o2, v2) {
            o2["default"] = v2;
          });
          var __importStar = commonjsGlobal && commonjsGlobal.__importStar || function(mod) {
            if (mod && mod.__esModule)
              return mod;
            var result = {};
            if (mod != null) {
              for (var k2 in mod)
                if (k2 !== "default" && Object.prototype.hasOwnProperty.call(mod, k2))
                  __createBinding(result, mod, k2);
            }
            __setModuleDefault(result, mod);
            return result;
          };
          var __awaiter3 = commonjsGlobal && commonjsGlobal.__awaiter || function(thisArg, _arguments, P2, generator) {
            function adopt(value) {
              return value instanceof P2 ? value : new P2(function(resolve2) {
                resolve2(value);
              });
            }
            return new (P2 || (P2 = Promise))(function(resolve2, reject) {
              function fulfilled(value) {
                try {
                  step(generator.next(value));
                } catch (e2) {
                  reject(e2);
                }
              }
              function rejected(value) {
                try {
                  step(generator["throw"](value));
                } catch (e2) {
                  reject(e2);
                }
              }
              function step(result) {
                result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
              }
              step((generator = generator.apply(thisArg, _arguments || [])).next());
            });
          };
          var __generator3 = commonjsGlobal && commonjsGlobal.__generator || function(thisArg, body) {
            var _2 = { label: 0, sent: function() {
              if (t2[0] & 1)
                throw t2[1];
              return t2[1];
            }, trys: [], ops: [] }, f2, y2, t2, g2;
            return g2 = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g2[Symbol.iterator] = function() {
              return this;
            }), g2;
            function verb(n2) {
              return function(v2) {
                return step([n2, v2]);
              };
            }
            function step(op) {
              if (f2)
                throw new TypeError("Generator is already executing.");
              while (_2)
                try {
                  if (f2 = 1, y2 && (t2 = op[0] & 2 ? y2["return"] : op[0] ? y2["throw"] || ((t2 = y2["return"]) && t2.call(y2), 0) : y2.next) && !(t2 = t2.call(y2, op[1])).done)
                    return t2;
                  if (y2 = 0, t2)
                    op = [op[0] & 2, t2.value];
                  switch (op[0]) {
                    case 0:
                    case 1:
                      t2 = op;
                      break;
                    case 4:
                      _2.label++;
                      return { value: op[1], done: false };
                    case 5:
                      _2.label++;
                      y2 = op[1];
                      op = [0];
                      continue;
                    case 7:
                      op = _2.ops.pop();
                      _2.trys.pop();
                      continue;
                    default:
                      if (!(t2 = _2.trys, t2 = t2.length > 0 && t2[t2.length - 1]) && (op[0] === 6 || op[0] === 2)) {
                        _2 = 0;
                        continue;
                      }
                      if (op[0] === 3 && (!t2 || op[1] > t2[0] && op[1] < t2[3])) {
                        _2.label = op[1];
                        break;
                      }
                      if (op[0] === 6 && _2.label < t2[1]) {
                        _2.label = t2[1];
                        t2 = op;
                        break;
                      }
                      if (t2 && _2.label < t2[2]) {
                        _2.label = t2[2];
                        _2.ops.push(op);
                        break;
                      }
                      if (t2[2])
                        _2.ops.pop();
                      _2.trys.pop();
                      continue;
                  }
                  op = body.call(thisArg, _2);
                } catch (e2) {
                  op = [6, e2];
                  y2 = 0;
                } finally {
                  f2 = t2 = 0;
                }
              if (op[0] & 5)
                throw op[1];
              return { value: op[0] ? op[1] : void 0, done: true };
            }
          };
          Object.defineProperty(exports2, "__esModule", { value: true });
          exports2.isBrowserConfig = exports2.clone = exports2.formatCGIData = exports2.filterUrl = exports2.filter = exports2.generateStackTrace = exports2.endpoint = exports2.instrumentConsole = exports2.instrument = exports2.isErrorObject = exports2.makeNotice = exports2.logger = exports2.sanitize = exports2.shallowClone = exports2.runAfterNotifyHandlers = exports2.runBeforeNotifyHandlers = exports2.getSourceForBacktrace = exports2.getCauses = exports2.calculateBacktraceShift = exports2.DEFAULT_BACKTRACE_SHIFT = exports2.makeBacktrace = exports2.objectIsExtensible = exports2.objectIsEmpty = exports2.mergeNotice = exports2.merge = void 0;
          var stackTraceParser = __importStar(require$$0$1);
          function merge2(obj1, obj2) {
            var result = {};
            for (var k2 in obj1) {
              result[k2] = obj1[k2];
            }
            for (var k2 in obj2) {
              result[k2] = obj2[k2];
            }
            return result;
          }
          exports2.merge = merge2;
          function mergeNotice(notice1, notice2) {
            var result = merge2(notice1, notice2);
            if (notice1.context && notice2.context) {
              result.context = merge2(notice1.context, notice2.context);
            }
            return result;
          }
          exports2.mergeNotice = mergeNotice;
          function objectIsEmpty(obj) {
            for (var k2 in obj) {
              if (Object.prototype.hasOwnProperty.call(obj, k2)) {
                return false;
              }
            }
            return true;
          }
          exports2.objectIsEmpty = objectIsEmpty;
          function objectIsExtensible(obj) {
            if (typeof Object.isExtensible !== "function") {
              return true;
            }
            return Object.isExtensible(obj);
          }
          exports2.objectIsExtensible = objectIsExtensible;
          function makeBacktrace(stack, filterHbSourceCode, logger2) {
            if (filterHbSourceCode === void 0) {
              filterHbSourceCode = false;
            }
            if (logger2 === void 0) {
              logger2 = console;
            }
            if (!stack) {
              return [];
            }
            try {
              var backtrace = stackTraceParser.parse(stack).map(function(line) {
                return {
                  file: line.file,
                  method: line.methodName,
                  number: line.lineNumber,
                  column: line.column
                };
              });
              if (filterHbSourceCode) {
                backtrace.splice(0, calculateBacktraceShift(backtrace));
              }
              return backtrace;
            } catch (err) {
              logger2.debug(err);
              return [];
            }
          }
          exports2.makeBacktrace = makeBacktrace;
          function isFrameFromHbSourceCode(frame) {
            var hasHbFile = false;
            var hasHbMethod = false;
            if (frame.file) {
              hasHbFile = frame.file.toLowerCase().indexOf("@honeybadger-io") > -1;
            }
            if (frame.method) {
              hasHbMethod = frame.method.toLowerCase().indexOf("@honeybadger-io") > -1;
            }
            return hasHbFile || hasHbMethod;
          }
          exports2.DEFAULT_BACKTRACE_SHIFT = 3;
          function calculateBacktraceShift(backtrace) {
            var shift = 0;
            for (var i2 = 0; i2 < backtrace.length; i2++) {
              var frame = backtrace[i2];
              if (isFrameFromHbSourceCode(frame)) {
                shift++;
                continue;
              }
              if (!frame.file || frame.file === "<anonymous>") {
                var nextFrame = backtrace[i2 + 1];
                if (nextFrame && isFrameFromHbSourceCode(nextFrame)) {
                  shift++;
                  continue;
                }
              }
              break;
            }
            return shift || exports2.DEFAULT_BACKTRACE_SHIFT;
          }
          exports2.calculateBacktraceShift = calculateBacktraceShift;
          function getCauses(notice, logger2) {
            if (notice.cause) {
              var causes = [];
              var cause = notice;
              while (causes.length < 3 && (cause = cause.cause)) {
                causes.push({
                  class: cause.name,
                  message: cause.message,
                  backtrace: typeof cause.stack == "string" ? makeBacktrace(cause.stack, false, logger2) : null
                });
              }
              return causes;
            }
            return [];
          }
          exports2.getCauses = getCauses;
          function getSourceForBacktrace(backtrace, getSourceFileHandler) {
            return __awaiter3(this, void 0, void 0, function() {
              var result, index, trace, fileContent;
              return __generator3(this, function(_a) {
                switch (_a.label) {
                  case 0:
                    result = [];
                    if (!getSourceFileHandler || !backtrace || !backtrace.length) {
                      return [2, result];
                    }
                    index = 0;
                    _a.label = 1;
                  case 1:
                    if (!backtrace.length)
                      return [3, 3];
                    trace = backtrace.splice(0)[index];
                    return [4, getSourceFileHandler(trace.file)];
                  case 2:
                    fileContent = _a.sent();
                    result[index] = getSourceCodeSnippet(fileContent, trace.number);
                    index++;
                    return [3, 1];
                  case 3:
                    return [2, result];
                }
              });
            });
          }
          exports2.getSourceForBacktrace = getSourceForBacktrace;
          function runBeforeNotifyHandlers(notice, handlers) {
            var results = [];
            var result = true;
            for (var i2 = 0, len = handlers.length; i2 < len; i2++) {
              var handler = handlers[i2];
              var handlerResult = handler(notice);
              if (handlerResult === false) {
                result = false;
              }
              results.push(handlerResult);
            }
            return {
              results,
              result
            };
          }
          exports2.runBeforeNotifyHandlers = runBeforeNotifyHandlers;
          function runAfterNotifyHandlers(notice, handlers, error3) {
            if (notice && notice.afterNotify) {
              notice.afterNotify(error3, notice);
            }
            for (var i2 = 0, len = handlers.length; i2 < len; i2++) {
              handlers[i2](error3, notice);
            }
            return true;
          }
          exports2.runAfterNotifyHandlers = runAfterNotifyHandlers;
          function shallowClone(obj) {
            if (typeof obj !== "object" || obj === null) {
              return {};
            }
            var result = {};
            for (var k2 in obj) {
              result[k2] = obj[k2];
            }
            return result;
          }
          exports2.shallowClone = shallowClone;
          function sanitize2(obj, maxDepth) {
            if (maxDepth === void 0) {
              maxDepth = 8;
            }
            var seenObjects = [];
            function seen(obj2) {
              if (!obj2 || typeof obj2 !== "object") {
                return false;
              }
              for (var i2 = 0; i2 < seenObjects.length; i2++) {
                var value = seenObjects[i2];
                if (value === obj2) {
                  return true;
                }
              }
              seenObjects.push(obj2);
              return false;
            }
            function canSerialize(obj2) {
              var typeOfObj = typeof obj2;
              if (/function/.test(typeOfObj)) {
                return obj2.name === "toJSON";
              }
              if (/symbol/.test(typeOfObj)) {
                return false;
              }
              if (obj2 === null) {
                return false;
              }
              if (typeof obj2 === "object" && typeof obj2.hasOwnProperty === "undefined") {
                return false;
              }
              return true;
            }
            function serialize(obj2, depth) {
              if (depth === void 0) {
                depth = 0;
              }
              if (depth >= maxDepth) {
                return "[DEPTH]";
              }
              if (!canSerialize(obj2)) {
                return Object.prototype.toString.call(obj2);
              }
              if (seen(obj2)) {
                return "[RECURSION]";
              }
              if (Array.isArray(obj2)) {
                return obj2.map(function(o2) {
                  return safeSerialize(o2, depth + 1);
                });
              }
              if (typeof obj2 === "object") {
                var ret = {};
                for (var k2 in obj2) {
                  var v2 = obj2[k2];
                  if (Object.prototype.hasOwnProperty.call(obj2, k2) && k2 != null && v2 != null) {
                    ret[k2] = safeSerialize(v2, depth + 1);
                  }
                }
                return ret;
              }
              return obj2;
            }
            function safeSerialize(obj2, depth) {
              if (depth === void 0) {
                depth = 0;
              }
              try {
                return serialize(obj2, depth);
              } catch (e2) {
                return "[ERROR] ".concat(e2);
              }
            }
            return safeSerialize(obj);
          }
          exports2.sanitize = sanitize2;
          function logger(client2) {
            var log = function(method) {
              return function() {
                var _a;
                var args = [];
                for (var _i2 = 0; _i2 < arguments.length; _i2++) {
                  args[_i2] = arguments[_i2];
                }
                if (method === "debug") {
                  if (!client2.config.debug) {
                    return;
                  }
                  method = "log";
                }
                args.unshift("[Honeybadger]");
                (_a = client2.config.logger)[method].apply(_a, args);
              };
            };
            return {
              log: log("log"),
              info: log("info"),
              debug: log("debug"),
              warn: log("warn"),
              error: log("error")
            };
          }
          exports2.logger = logger;
          function makeNotice2(thing) {
            var notice;
            if (!thing) {
              notice = {};
            } else if (isErrorObject(thing)) {
              var e2 = thing;
              notice = merge2(thing, { name: e2.name, message: e2.message, stack: e2.stack, cause: e2.cause });
            } else if (typeof thing === "object") {
              notice = shallowClone(thing);
            } else {
              var m2 = String(thing);
              notice = { message: m2 };
            }
            return notice;
          }
          exports2.makeNotice = makeNotice2;
          function isErrorObject(thing) {
            return thing instanceof Error || Object.prototype.toString.call(thing) === "[object Error]";
          }
          exports2.isErrorObject = isErrorObject;
          function instrument2(object, name, replacement) {
            if (!object || !name || !replacement || !(name in object)) {
              return;
            }
            try {
              var original = object[name];
              while (original && original.__hb_original) {
                original = original.__hb_original;
              }
              object[name] = replacement(original);
              object[name].__hb_original = original;
            } catch (_e2) {
            }
          }
          exports2.instrument = instrument2;
          var _consoleAlreadyInstrumented = false;
          var listeners = [];
          function instrumentConsole2(_window, handler) {
            if (!_window || !_window.console || !handler) {
              return;
            }
            listeners.push(handler);
            if (_consoleAlreadyInstrumented) {
              return;
            }
            _consoleAlreadyInstrumented = true;
            ["debug", "info", "warn", "error", "log"].forEach(function(level) {
              instrument2(_window.console, level, function hbLogger(original) {
                return function() {
                  var args = Array.prototype.slice.call(arguments);
                  listeners.forEach(function(listener) {
                    try {
                      listener(level, args);
                    } catch (_e2) {
                    }
                  });
                  if (typeof original === "function") {
                    Function.prototype.apply.call(original, _window.console, arguments);
                  }
                };
              });
            });
          }
          exports2.instrumentConsole = instrumentConsole2;
          function endpoint(base, path) {
            var endpoint2 = base.trim().replace(/\/$/, "");
            path = path.trim().replace(/(^\/|\/$)/g, "");
            return "".concat(endpoint2, "/").concat(path);
          }
          exports2.endpoint = endpoint;
          function generateStackTrace() {
            try {
              throw new Error("");
            } catch (e2) {
              if (e2.stack) {
                return e2.stack;
              }
            }
            var maxStackSize = 10;
            var stack = [];
            var curr = arguments.callee;
            while (curr && stack.length < maxStackSize) {
              if (/function(?:\s+([\w$]+))+\s*\(/.test(curr.toString())) {
                stack.push(RegExp.$1 || "<anonymous>");
              } else {
                stack.push("<anonymous>");
              }
              try {
                curr = curr.caller;
              } catch (e2) {
                break;
              }
            }
            return stack.join("\n");
          }
          exports2.generateStackTrace = generateStackTrace;
          function filter(obj, filters) {
            if (!is("Object", obj)) {
              return;
            }
            if (!is("Array", filters)) {
              filters = [];
            }
            var seen = [];
            function filter2(obj2) {
              var k2, newObj;
              if (is("Object", obj2) || is("Array", obj2)) {
                if (seen.indexOf(obj2) !== -1) {
                  return "[CIRCULAR DATA STRUCTURE]";
                }
                seen.push(obj2);
              }
              if (is("Object", obj2)) {
                newObj = {};
                for (k2 in obj2) {
                  if (filterMatch(k2, filters)) {
                    newObj[k2] = "[FILTERED]";
                  } else {
                    newObj[k2] = filter2(obj2[k2]);
                  }
                }
                return newObj;
              }
              if (is("Array", obj2)) {
                return obj2.map(function(v2) {
                  return filter2(v2);
                });
              }
              if (is("Function", obj2)) {
                return "[FUNC]";
              }
              return obj2;
            }
            return filter2(obj);
          }
          exports2.filter = filter;
          function filterMatch(key, filters) {
            for (var i2 = 0; i2 < filters.length; i2++) {
              if (key.toLowerCase().indexOf(filters[i2].toLowerCase()) !== -1) {
                return true;
              }
            }
            return false;
          }
          function is(type, obj) {
            var klass = Object.prototype.toString.call(obj).slice(8, -1);
            return obj !== void 0 && obj !== null && klass === type;
          }
          function filterUrl(url, filters) {
            if (!filters) {
              return url;
            }
            if (typeof url !== "string") {
              return url;
            }
            var query = url.split(/\?/, 2)[1];
            if (!query) {
              return url;
            }
            var result = url;
            query.split(/[&]\s?/).forEach(function(pair) {
              var _a = pair.split("=", 2), key = _a[0], value = _a[1];
              if (filterMatch(key, filters)) {
                result = result.replace("".concat(key, "=").concat(value), "".concat(key, "=[FILTERED]"));
              }
            });
            return result;
          }
          exports2.filterUrl = filterUrl;
          function formatCGIData(vars, prefix) {
            if (prefix === void 0) {
              prefix = "";
            }
            var formattedVars = {};
            Object.keys(vars).forEach(function(key) {
              var formattedKey = prefix + key.replace(/\W/g, "_").toUpperCase();
              formattedVars[formattedKey] = vars[key];
            });
            return formattedVars;
          }
          exports2.formatCGIData = formatCGIData;
          function clone2(obj) {
            return JSON.parse(JSON.stringify(obj));
          }
          exports2.clone = clone2;
          function getSourceCodeSnippet(fileData, lineNumber, sourceRadius) {
            if (sourceRadius === void 0) {
              sourceRadius = 2;
            }
            if (!fileData) {
              return null;
            }
            var lines = fileData.split("\n");
            lines.unshift("");
            var start4 = lineNumber - sourceRadius;
            var end2 = lineNumber + sourceRadius;
            var result = {};
            for (var i2 = start4; i2 <= end2; i2++) {
              var line = lines[i2];
              if (typeof line === "string") {
                result[i2] = line;
              }
            }
            return result;
          }
          function isBrowserConfig(config) {
            return config.async !== void 0;
          }
          exports2.isBrowserConfig = isBrowserConfig;
        })(util$1);
        var store = {};
        Object.defineProperty(store, "__esModule", { value: true });
        store.GlobalStore = void 0;
        var util_1$9 = util$1;
        var GlobalStore = function() {
          function GlobalStore2(contents, breadcrumbsLimit) {
            this.contents = contents;
            this.breadcrumbsLimit = breadcrumbsLimit;
          }
          GlobalStore2.create = function(contents, breadcrumbsLimit) {
            return new GlobalStore2(contents, breadcrumbsLimit);
          };
          GlobalStore2.prototype.available = function() {
            return true;
          };
          GlobalStore2.prototype.getContents = function(key) {
            var value = key ? this.contents[key] : this.contents;
            return JSON.parse(JSON.stringify(value));
          };
          GlobalStore2.prototype.setContext = function(context) {
            this.contents.context = (0, util_1$9.merge)(this.contents.context, context || {});
          };
          GlobalStore2.prototype.addBreadcrumb = function(breadcrumb) {
            if (this.contents.breadcrumbs.length == this.breadcrumbsLimit) {
              this.contents.breadcrumbs.shift();
            }
            this.contents.breadcrumbs.push(breadcrumb);
          };
          GlobalStore2.prototype.clear = function() {
            this.contents.context = {};
            this.contents.breadcrumbs = [];
          };
          GlobalStore2.prototype.run = function(callback2) {
            return callback2();
          };
          return GlobalStore2;
        }();
        store.GlobalStore = GlobalStore;
        var throttled_events_logger = {};
        class NdJson {
          static parse(data) {
            const lines = data.trim().split("\n");
            return lines.map((line) => JSON.parse(line));
          }
          static stringify(data) {
            return data.map((item) => JSON.stringify(item)).join("\n");
          }
        }
        var module2 = /* @__PURE__ */ Object.freeze({
          __proto__: null,
          NdJson
        });
        var require$$0 = /* @__PURE__ */ getAugmentedNamespace(module2);
        var defaults2 = {};
        Object.defineProperty(defaults2, "__esModule", { value: true });
        defaults2.CONFIG = void 0;
        defaults2.CONFIG = {
          apiKey: null,
          endpoint: "https://api.honeybadger.io",
          environment: null,
          hostname: null,
          projectRoot: null,
          component: null,
          action: null,
          revision: null,
          reportData: null,
          breadcrumbsEnabled: true,
          eventsEnabled: false,
          maxBreadcrumbs: 40,
          maxObjectDepth: 8,
          logger: console,
          developmentEnvironments: ["dev", "development", "test"],
          debug: false,
          tags: null,
          enableUncaught: true,
          enableUnhandledRejection: true,
          afterUncaught: function() {
            return true;
          },
          filters: ["creditcard", "password"],
          __plugins: []
        };
        var __assign$1 = commonjsGlobal && commonjsGlobal.__assign || function() {
          __assign$1 = Object.assign || function(t2) {
            for (var s2, i2 = 1, n2 = arguments.length; i2 < n2; i2++) {
              s2 = arguments[i2];
              for (var p2 in s2)
                if (Object.prototype.hasOwnProperty.call(s2, p2))
                  t2[p2] = s2[p2];
            }
            return t2;
          };
          return __assign$1.apply(this, arguments);
        };
        var __awaiter$2 = commonjsGlobal && commonjsGlobal.__awaiter || function(thisArg, _arguments, P2, generator) {
          function adopt(value) {
            return value instanceof P2 ? value : new P2(function(resolve2) {
              resolve2(value);
            });
          }
          return new (P2 || (P2 = Promise))(function(resolve2, reject) {
            function fulfilled(value) {
              try {
                step(generator.next(value));
              } catch (e2) {
                reject(e2);
              }
            }
            function rejected(value) {
              try {
                step(generator["throw"](value));
              } catch (e2) {
                reject(e2);
              }
            }
            function step(result) {
              result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
            }
            step((generator = generator.apply(thisArg, _arguments || [])).next());
          });
        };
        var __generator$2 = commonjsGlobal && commonjsGlobal.__generator || function(thisArg, body) {
          var _2 = { label: 0, sent: function() {
            if (t2[0] & 1)
              throw t2[1];
            return t2[1];
          }, trys: [], ops: [] }, f2, y2, t2, g2;
          return g2 = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g2[Symbol.iterator] = function() {
            return this;
          }), g2;
          function verb(n2) {
            return function(v2) {
              return step([n2, v2]);
            };
          }
          function step(op) {
            if (f2)
              throw new TypeError("Generator is already executing.");
            while (_2)
              try {
                if (f2 = 1, y2 && (t2 = op[0] & 2 ? y2["return"] : op[0] ? y2["throw"] || ((t2 = y2["return"]) && t2.call(y2), 0) : y2.next) && !(t2 = t2.call(y2, op[1])).done)
                  return t2;
                if (y2 = 0, t2)
                  op = [op[0] & 2, t2.value];
                switch (op[0]) {
                  case 0:
                  case 1:
                    t2 = op;
                    break;
                  case 4:
                    _2.label++;
                    return { value: op[1], done: false };
                  case 5:
                    _2.label++;
                    y2 = op[1];
                    op = [0];
                    continue;
                  case 7:
                    op = _2.ops.pop();
                    _2.trys.pop();
                    continue;
                  default:
                    if (!(t2 = _2.trys, t2 = t2.length > 0 && t2[t2.length - 1]) && (op[0] === 6 || op[0] === 2)) {
                      _2 = 0;
                      continue;
                    }
                    if (op[0] === 3 && (!t2 || op[1] > t2[0] && op[1] < t2[3])) {
                      _2.label = op[1];
                      break;
                    }
                    if (op[0] === 6 && _2.label < t2[1]) {
                      _2.label = t2[1];
                      t2 = op;
                      break;
                    }
                    if (t2 && _2.label < t2[2]) {
                      _2.label = t2[2];
                      _2.ops.push(op);
                      break;
                    }
                    if (t2[2])
                      _2.ops.pop();
                    _2.trys.pop();
                    continue;
                }
                op = body.call(thisArg, _2);
              } catch (e2) {
                op = [6, e2];
                y2 = 0;
              } finally {
                f2 = t2 = 0;
              }
            if (op[0] & 5)
              throw op[1];
            return { value: op[0] ? op[1] : void 0, done: true };
          }
        };
        Object.defineProperty(throttled_events_logger, "__esModule", { value: true });
        throttled_events_logger.ThrottledEventsLogger = void 0;
        var json_nd_1 = require$$0;
        var util_1$8 = util$1;
        var defaults_1$1 = defaults2;
        var ThrottledEventsLogger = function() {
          function ThrottledEventsLogger2(config, transport2) {
            this.config = config;
            this.transport = transport2;
            this.queue = [];
            this.isProcessing = false;
            this.config = __assign$1(__assign$1({}, defaults_1$1.CONFIG), config);
            this.logger = this.originalLogger();
          }
          ThrottledEventsLogger2.prototype.configure = function(opts) {
            for (var k2 in opts) {
              this.config[k2] = opts[k2];
            }
          };
          ThrottledEventsLogger2.prototype.logEvent = function(data) {
            this.queue.push(data);
            if (!this.isProcessing) {
              this.processQueue();
            }
          };
          ThrottledEventsLogger2.prototype.processQueue = function() {
            var _this = this;
            if (this.queue.length === 0 || this.isProcessing) {
              return;
            }
            this.isProcessing = true;
            var eventsData = this.queue.slice();
            this.queue = [];
            var data = json_nd_1.NdJson.stringify(eventsData);
            this.makeHttpRequest(data).then(function() {
              setTimeout(function() {
                _this.isProcessing = false;
                _this.processQueue();
              }, 50);
            }).catch(function(error3) {
              _this.logger.error("[Honeybadger] Error making HTTP request:", error3);
              setTimeout(function() {
                _this.isProcessing = false;
                _this.processQueue();
              }, 50);
            });
          };
          ThrottledEventsLogger2.prototype.makeHttpRequest = function(data) {
            return __awaiter$2(this, void 0, void 0, function() {
              var _this = this;
              return __generator$2(this, function(_a) {
                return [2, this.transport.send({
                  headers: {
                    "X-API-Key": this.config.apiKey,
                    "Content-Type": "application/json"
                  },
                  method: "POST",
                  endpoint: (0, util_1$8.endpoint)(this.config.endpoint, "/v1/events"),
                  maxObjectDepth: this.config.maxObjectDepth,
                  logger: this.logger
                }, data).then(function() {
                  if (_this.config.debug) {
                    _this.logger.debug("[Honeybadger] Events sent successfully");
                  }
                }).catch(function(err) {
                  _this.logger.error("[Honeybadger] Error sending events: ".concat(err.message));
                })];
              });
            });
          };
          ThrottledEventsLogger2.prototype.originalLogger = function() {
            var _a, _b, _c, _d, _e2;
            return {
              log: (_a = console.log.__hb_original) !== null && _a !== void 0 ? _a : console.log,
              info: (_b = console.info.__hb_original) !== null && _b !== void 0 ? _b : console.info,
              debug: (_c = console.debug.__hb_original) !== null && _c !== void 0 ? _c : console.debug,
              warn: (_d = console.warn.__hb_original) !== null && _d !== void 0 ? _d : console.warn,
              error: (_e2 = console.error.__hb_original) !== null && _e2 !== void 0 ? _e2 : console.error
            };
          };
          return ThrottledEventsLogger2;
        }();
        throttled_events_logger.ThrottledEventsLogger = ThrottledEventsLogger;
        var __assign = commonjsGlobal && commonjsGlobal.__assign || function() {
          __assign = Object.assign || function(t2) {
            for (var s2, i2 = 1, n2 = arguments.length; i2 < n2; i2++) {
              s2 = arguments[i2];
              for (var p2 in s2)
                if (Object.prototype.hasOwnProperty.call(s2, p2))
                  t2[p2] = s2[p2];
            }
            return t2;
          };
          return __assign.apply(this, arguments);
        };
        var __awaiter$1 = commonjsGlobal && commonjsGlobal.__awaiter || function(thisArg, _arguments, P2, generator) {
          function adopt(value) {
            return value instanceof P2 ? value : new P2(function(resolve2) {
              resolve2(value);
            });
          }
          return new (P2 || (P2 = Promise))(function(resolve2, reject) {
            function fulfilled(value) {
              try {
                step(generator.next(value));
              } catch (e2) {
                reject(e2);
              }
            }
            function rejected(value) {
              try {
                step(generator["throw"](value));
              } catch (e2) {
                reject(e2);
              }
            }
            function step(result) {
              result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
            }
            step((generator = generator.apply(thisArg, _arguments || [])).next());
          });
        };
        var __generator$1 = commonjsGlobal && commonjsGlobal.__generator || function(thisArg, body) {
          var _2 = { label: 0, sent: function() {
            if (t2[0] & 1)
              throw t2[1];
            return t2[1];
          }, trys: [], ops: [] }, f2, y2, t2, g2;
          return g2 = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g2[Symbol.iterator] = function() {
            return this;
          }), g2;
          function verb(n2) {
            return function(v2) {
              return step([n2, v2]);
            };
          }
          function step(op) {
            if (f2)
              throw new TypeError("Generator is already executing.");
            while (_2)
              try {
                if (f2 = 1, y2 && (t2 = op[0] & 2 ? y2["return"] : op[0] ? y2["throw"] || ((t2 = y2["return"]) && t2.call(y2), 0) : y2.next) && !(t2 = t2.call(y2, op[1])).done)
                  return t2;
                if (y2 = 0, t2)
                  op = [op[0] & 2, t2.value];
                switch (op[0]) {
                  case 0:
                  case 1:
                    t2 = op;
                    break;
                  case 4:
                    _2.label++;
                    return { value: op[1], done: false };
                  case 5:
                    _2.label++;
                    y2 = op[1];
                    op = [0];
                    continue;
                  case 7:
                    op = _2.ops.pop();
                    _2.trys.pop();
                    continue;
                  default:
                    if (!(t2 = _2.trys, t2 = t2.length > 0 && t2[t2.length - 1]) && (op[0] === 6 || op[0] === 2)) {
                      _2 = 0;
                      continue;
                    }
                    if (op[0] === 3 && (!t2 || op[1] > t2[0] && op[1] < t2[3])) {
                      _2.label = op[1];
                      break;
                    }
                    if (op[0] === 6 && _2.label < t2[1]) {
                      _2.label = t2[1];
                      t2 = op;
                      break;
                    }
                    if (t2 && _2.label < t2[2]) {
                      _2.label = t2[2];
                      _2.ops.push(op);
                      break;
                    }
                    if (t2[2])
                      _2.ops.pop();
                    _2.trys.pop();
                    continue;
                }
                op = body.call(thisArg, _2);
              } catch (e2) {
                op = [6, e2];
                y2 = 0;
              } finally {
                f2 = t2 = 0;
              }
            if (op[0] & 5)
              throw op[1];
            return { value: op[0] ? op[1] : void 0, done: true };
          }
        };
        Object.defineProperty(client, "__esModule", { value: true });
        client.Client = void 0;
        var util_1$7 = util$1;
        var store_1 = store;
        var throttled_events_logger_1 = throttled_events_logger;
        var defaults_1 = defaults2;
        var TAG_SEPARATOR = /,|\s+/;
        var NOT_BLANK = /\S/;
        var Client = function() {
          function Client2(opts, transport2) {
            if (opts === void 0) {
              opts = {};
            }
            this.__pluginsLoaded = false;
            this.__store = null;
            this.__beforeNotifyHandlers = [];
            this.__afterNotifyHandlers = [];
            this.__notifier = {
              name: "@honeybadger-io/core",
              url: "https://github.com/honeybadger-io/honeybadger-js/tree/master/packages/core",
              version: "6.8.3"
            };
            this.config = __assign(__assign({}, defaults_1.CONFIG), opts);
            this.__initStore();
            this.__transport = transport2;
            this.__eventsLogger = new throttled_events_logger_1.ThrottledEventsLogger(this.config, this.__transport);
            this.logger = (0, util_1$7.logger)(this);
          }
          Client2.prototype.getVersion = function() {
            return this.__notifier.version;
          };
          Client2.prototype.getNotifier = function() {
            return this.__notifier;
          };
          Client2.prototype.setNotifier = function(notifier) {
            this.__notifier = notifier;
          };
          Client2.prototype.configure = function(opts) {
            if (opts === void 0) {
              opts = {};
            }
            for (var k2 in opts) {
              this.config[k2] = opts[k2];
            }
            this.__eventsLogger.configure(this.config);
            this.loadPlugins();
            return this;
          };
          Client2.prototype.loadPlugins = function() {
            var _this = this;
            var pluginsToLoad = this.__pluginsLoaded ? this.config.__plugins.filter(function(plugin) {
              return plugin.shouldReloadOnConfigure;
            }) : this.config.__plugins;
            pluginsToLoad.forEach(function(plugin) {
              return plugin.load(_this);
            });
            this.__pluginsLoaded = true;
          };
          Client2.prototype.__initStore = function() {
            this.__store = new store_1.GlobalStore({ context: {}, breadcrumbs: [] }, this.config.maxBreadcrumbs);
          };
          Client2.prototype.beforeNotify = function(handler) {
            this.__beforeNotifyHandlers.push(handler);
            return this;
          };
          Client2.prototype.afterNotify = function(handler) {
            this.__afterNotifyHandlers.push(handler);
            return this;
          };
          Client2.prototype.setContext = function(context) {
            if (typeof context === "object" && context != null) {
              this.__store.setContext(context);
            }
            return this;
          };
          Client2.prototype.resetContext = function(context) {
            this.logger.warn("Deprecation warning: `Honeybadger.resetContext()` has been deprecated; please use `Honeybadger.clear()` instead.");
            this.__store.clear();
            if (typeof context === "object" && context !== null) {
              this.__store.setContext(context);
            }
            return this;
          };
          Client2.prototype.clear = function() {
            this.__store.clear();
            return this;
          };
          Client2.prototype.notify = function(noticeable, name, extra) {
            var _this = this;
            if (name === void 0) {
              name = void 0;
            }
            if (extra === void 0) {
              extra = void 0;
            }
            var notice = this.makeNotice(noticeable, name, extra);
            var sourceCodeData = notice && notice.backtrace ? notice.backtrace.map(function(trace) {
              return (0, util_1$7.shallowClone)(trace);
            }) : null;
            var preConditionsResult = this.__runPreconditions(notice);
            if (preConditionsResult instanceof Error) {
              (0, util_1$7.runAfterNotifyHandlers)(notice, this.__afterNotifyHandlers, preConditionsResult);
              return false;
            }
            if (preConditionsResult instanceof Promise) {
              preConditionsResult.then(function(result) {
                if (result instanceof Error) {
                  (0, util_1$7.runAfterNotifyHandlers)(notice, _this.__afterNotifyHandlers, result);
                  return false;
                }
                return _this.__send(notice, sourceCodeData);
              });
              return true;
            }
            this.__send(notice, sourceCodeData).catch(function(_err) {
            });
            return true;
          };
          Client2.prototype.notifyAsync = function(noticeable, name, extra) {
            var _this = this;
            if (name === void 0) {
              name = void 0;
            }
            if (extra === void 0) {
              extra = void 0;
            }
            return new Promise(function(resolve2, reject) {
              var applyAfterNotify = function(partialNotice) {
                var originalAfterNotify = partialNotice.afterNotify;
                partialNotice.afterNotify = function(err) {
                  originalAfterNotify === null || originalAfterNotify === void 0 ? void 0 : originalAfterNotify.call(_this, err);
                  if (err) {
                    return reject(err);
                  }
                  resolve2();
                };
              };
              var objectToOverride;
              if (noticeable.afterNotify) {
                objectToOverride = noticeable;
              } else if (name && name.afterNotify) {
                objectToOverride = name;
              } else if (extra && extra.afterNotify) {
                objectToOverride = extra;
              } else if (name && typeof name === "object") {
                objectToOverride = name;
              } else if (extra) {
                objectToOverride = extra;
              } else {
                objectToOverride = name = {};
              }
              applyAfterNotify(objectToOverride);
              _this.notify(noticeable, name, extra);
            });
          };
          Client2.prototype.makeNotice = function(noticeable, name, extra) {
            if (name === void 0) {
              name = void 0;
            }
            if (extra === void 0) {
              extra = void 0;
            }
            var notice = (0, util_1$7.makeNotice)(noticeable);
            if (name && !(typeof name === "object")) {
              var n2 = String(name);
              name = { name: n2 };
            }
            if (name) {
              notice = (0, util_1$7.mergeNotice)(notice, name);
            }
            if (typeof extra === "object" && extra !== null) {
              notice = (0, util_1$7.mergeNotice)(notice, extra);
            }
            if ((0, util_1$7.objectIsEmpty)(notice)) {
              return null;
            }
            var context = this.__store.getContents("context");
            var noticeTags = this.__constructTags(notice.tags);
            var contextTags = this.__constructTags(context["tags"]);
            var configTags = this.__constructTags(this.config.tags);
            var tags = noticeTags.concat(contextTags).concat(configTags);
            var uniqueTags = tags.filter(function(item, index) {
              return tags.indexOf(item) === index;
            });
            notice = (0, util_1$7.merge)(notice, {
              name: notice.name || "Error",
              context: (0, util_1$7.merge)(context, notice.context),
              projectRoot: notice.projectRoot || this.config.projectRoot,
              environment: notice.environment || this.config.environment,
              component: notice.component || this.config.component,
              action: notice.action || this.config.action,
              revision: notice.revision || this.config.revision,
              tags: uniqueTags
            });
            if (!Array.isArray(notice.backtrace) || !notice.backtrace.length) {
              if (typeof notice.stack !== "string" || !notice.stack.trim()) {
                notice.stack = (0, util_1$7.generateStackTrace)();
                notice.backtrace = (0, util_1$7.makeBacktrace)(notice.stack, true, this.logger);
              } else {
                notice.backtrace = (0, util_1$7.makeBacktrace)(notice.stack, false, this.logger);
              }
            }
            return notice;
          };
          Client2.prototype.addBreadcrumb = function(message, opts) {
            if (!this.config.breadcrumbsEnabled) {
              return;
            }
            opts = opts || {};
            var metadata = (0, util_1$7.shallowClone)(opts.metadata);
            var category = opts.category || "custom";
            var timestamp = new Date().toISOString();
            this.__store.addBreadcrumb({
              category,
              message,
              metadata,
              timestamp
            });
            return this;
          };
          Client2.prototype.logEvent = function(data) {
            this.__eventsLogger.logEvent(data);
          };
          Client2.prototype.__getBreadcrumbs = function() {
            return this.__store.getContents("breadcrumbs").slice();
          };
          Client2.prototype.__getContext = function() {
            return this.__store.getContents("context");
          };
          Client2.prototype.__developmentMode = function() {
            if (this.config.reportData === true) {
              return false;
            }
            return this.config.environment && this.config.developmentEnvironments.includes(this.config.environment);
          };
          Client2.prototype.__buildPayload = function(notice) {
            var headers = (0, util_1$7.filter)(notice.headers, this.config.filters) || {};
            var cgiData = (0, util_1$7.filter)(__assign(__assign({}, notice.cgiData), (0, util_1$7.formatCGIData)(headers, "HTTP_")), this.config.filters);
            return {
              notifier: this.__notifier,
              breadcrumbs: {
                enabled: !!this.config.breadcrumbsEnabled,
                trail: notice.__breadcrumbs || []
              },
              error: {
                class: notice.name,
                message: notice.message,
                backtrace: notice.backtrace,
                fingerprint: notice.fingerprint,
                tags: notice.tags,
                causes: (0, util_1$7.getCauses)(notice, this.logger)
              },
              request: {
                url: (0, util_1$7.filterUrl)(notice.url, this.config.filters),
                component: notice.component,
                action: notice.action,
                context: notice.context,
                cgi_data: cgiData,
                params: (0, util_1$7.filter)(notice.params, this.config.filters) || {},
                session: (0, util_1$7.filter)(notice.session, this.config.filters) || {}
              },
              server: {
                project_root: notice.projectRoot,
                environment_name: notice.environment,
                revision: notice.revision,
                hostname: this.config.hostname,
                time: new Date().toUTCString()
              },
              details: notice.details || {}
            };
          };
          Client2.prototype.__constructTags = function(tags) {
            if (!tags) {
              return [];
            }
            return tags.toString().split(TAG_SEPARATOR).filter(function(tag) {
              return NOT_BLANK.test(tag);
            });
          };
          Client2.prototype.__runPreconditions = function(notice) {
            var _this = this;
            var preConditionError = null;
            if (!notice) {
              this.logger.debug("failed to build error report");
              preConditionError = new Error("failed to build error report");
            }
            if (this.config.reportData === false) {
              this.logger.debug("skipping error report: honeybadger.js is disabled", notice);
              preConditionError = new Error("honeybadger.js is disabled");
            }
            if (this.__developmentMode()) {
              this.logger.log("honeybadger.js is in development mode; the following error report will be sent in production.", notice);
              preConditionError = new Error("honeybadger.js is in development mode");
            }
            if (!this.config.apiKey) {
              this.logger.warn("could not send error report: no API key has been configured", notice);
              preConditionError = new Error("missing API key");
            }
            var beforeNotifyResult = (0, util_1$7.runBeforeNotifyHandlers)(notice, this.__beforeNotifyHandlers);
            if (!preConditionError && !beforeNotifyResult.result) {
              this.logger.debug("skipping error report: one or more beforeNotify handlers returned false", notice);
              preConditionError = new Error("beforeNotify handlers returned false");
            }
            if (beforeNotifyResult.results.length && beforeNotifyResult.results.some(function(result) {
              return result instanceof Promise;
            })) {
              return Promise.allSettled(beforeNotifyResult.results).then(function(results) {
                if (!preConditionError && results.some(function(result) {
                  return result.status === "rejected" || result.value === false;
                })) {
                  _this.logger.debug("skipping error report: one or more beforeNotify handlers returned false", notice);
                  preConditionError = new Error("beforeNotify handlers (async) returned false");
                }
                if (preConditionError) {
                  return preConditionError;
                }
              });
            }
            return preConditionError;
          };
          Client2.prototype.__send = function(notice, originalBacktrace) {
            var _this = this;
            if (this.config.breadcrumbsEnabled) {
              this.addBreadcrumb("Honeybadger Notice", {
                category: "notice",
                metadata: {
                  message: notice.message,
                  name: notice.name,
                  stack: notice.stack
                }
              });
              notice.__breadcrumbs = this.__store.getContents("breadcrumbs");
            } else {
              notice.__breadcrumbs = [];
            }
            return (0, util_1$7.getSourceForBacktrace)(originalBacktrace, this.__getSourceFileHandler).then(function(sourcePerTrace) {
              return __awaiter$1(_this, void 0, void 0, function() {
                var payload;
                return __generator$1(this, function(_a) {
                  sourcePerTrace.forEach(function(source, index) {
                    notice.backtrace[index].source = source;
                  });
                  payload = this.__buildPayload(notice);
                  return [2, this.__transport.send({
                    headers: {
                      "X-API-Key": this.config.apiKey,
                      "Content-Type": "application/json",
                      "Accept": "text/json, application/json"
                    },
                    method: "POST",
                    endpoint: (0, util_1$7.endpoint)(this.config.endpoint, "/v1/notices/js"),
                    maxObjectDepth: this.config.maxObjectDepth,
                    logger: this.logger
                  }, payload)];
                });
              });
            }).then(function(res) {
              if (res.statusCode !== 201) {
                (0, util_1$7.runAfterNotifyHandlers)(notice, _this.__afterNotifyHandlers, new Error("Bad HTTP response: ".concat(res.statusCode)));
                _this.logger.warn("Error report failed: unknown response from server. code=".concat(res.statusCode));
                return false;
              }
              var uuid2 = JSON.parse(res.body).id;
              (0, util_1$7.runAfterNotifyHandlers)((0, util_1$7.merge)(notice, {
                id: uuid2
              }), _this.__afterNotifyHandlers);
              _this.logger.info("Error report sent \u26A1 https://app.honeybadger.io/notice/".concat(uuid2));
              return true;
            }).catch(function(err) {
              _this.logger.error("Error report failed: an unknown error occurred.", "message=".concat(err.message));
              (0, util_1$7.runAfterNotifyHandlers)(notice, _this.__afterNotifyHandlers, err);
              return false;
            });
          };
          return Client2;
        }();
        client.Client = Client;
        var types = {};
        Object.defineProperty(types, "__esModule", { value: true });
        (function(exports2) {
          var __createBinding = commonjsGlobal && commonjsGlobal.__createBinding || (Object.create ? function(o2, m2, k2, k22) {
            if (k22 === void 0)
              k22 = k2;
            var desc = Object.getOwnPropertyDescriptor(m2, k2);
            if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) {
              desc = { enumerable: true, get: function() {
                return m2[k2];
              } };
            }
            Object.defineProperty(o2, k22, desc);
          } : function(o2, m2, k2, k22) {
            if (k22 === void 0)
              k22 = k2;
            o2[k22] = m2[k2];
          });
          var __setModuleDefault = commonjsGlobal && commonjsGlobal.__setModuleDefault || (Object.create ? function(o2, v2) {
            Object.defineProperty(o2, "default", { enumerable: true, value: v2 });
          } : function(o2, v2) {
            o2["default"] = v2;
          });
          var __exportStar = commonjsGlobal && commonjsGlobal.__exportStar || function(m2, exports3) {
            for (var p2 in m2)
              if (p2 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p2))
                __createBinding(exports3, m2, p2);
          };
          var __importStar = commonjsGlobal && commonjsGlobal.__importStar || function(mod) {
            if (mod && mod.__esModule)
              return mod;
            var result = {};
            if (mod != null) {
              for (var k2 in mod)
                if (k2 !== "default" && Object.prototype.hasOwnProperty.call(mod, k2))
                  __createBinding(result, mod, k2);
            }
            __setModuleDefault(result, mod);
            return result;
          };
          Object.defineProperty(exports2, "__esModule", { value: true });
          exports2.Util = exports2.Types = exports2.Client = void 0;
          var client_1 = client;
          Object.defineProperty(exports2, "Client", { enumerable: true, get: function() {
            return client_1.Client;
          } });
          __exportStar(store, exports2);
          exports2.Types = __importStar(types);
          exports2.Util = __importStar(util$1);
        })(src);
        var util = {};
        Object.defineProperty(util, "__esModule", { value: true });
        util.globalThisOrWindow = util.preferCatch = util.encodeCookie = util.decodeCookie = util.localURLPathname = util.parseURL = util.nativeFetch = util.stringTextOfElement = util.stringSelectorOfElement = util.stringNameOfElement = void 0;
        function stringNameOfElement(element) {
          if (!element || !element.tagName) {
            return "";
          }
          var name = element.tagName.toLowerCase();
          if (name === "html") {
            return "";
          }
          if (element.id) {
            name += "#".concat(element.id);
          }
          var stringClassNames = element.getAttribute("class");
          if (stringClassNames) {
            stringClassNames.split(/\s+/).forEach(function(className) {
              name += ".".concat(className);
            });
          }
          ["alt", "name", "title", "type"].forEach(function(attrName) {
            var attr = element.getAttribute(attrName);
            if (attr) {
              name += "[".concat(attrName, '="').concat(attr, '"]');
            }
          });
          var siblings = getSiblings(element);
          if (siblings.length > 1) {
            name += ":nth-child(".concat(Array.prototype.indexOf.call(siblings, element) + 1, ")");
          }
          return name;
        }
        util.stringNameOfElement = stringNameOfElement;
        function stringSelectorOfElement(element) {
          var name = stringNameOfElement(element);
          if (element.parentNode && element.parentNode.tagName) {
            var parentName = stringSelectorOfElement(element.parentNode);
            if (parentName.length > 0) {
              return "".concat(parentName, " > ").concat(name);
            }
          }
          return name;
        }
        util.stringSelectorOfElement = stringSelectorOfElement;
        function stringTextOfElement(element) {
          var text = element.textContent || element.innerText || "";
          if (!text && (element.type === "submit" || element.type === "button")) {
            text = element.value;
          }
          return truncate(text.trim(), 300);
        }
        util.stringTextOfElement = stringTextOfElement;
        function nativeFetch2() {
          var global2 = globalThisOrWindow();
          if (!global2.fetch) {
            return false;
          }
          if (isNative(global2.fetch)) {
            return true;
          }
          if (typeof document === "undefined") {
            return false;
          }
          try {
            var sandbox = document.createElement("iframe");
            sandbox.style.display = "none";
            document.head.appendChild(sandbox);
            var result = sandbox.contentWindow.fetch && isNative(sandbox.contentWindow.fetch);
            document.head.removeChild(sandbox);
            return result;
          } catch (err) {
            if (console && console.warn) {
              console.warn("failed to detect native fetch via iframe: " + err);
            }
          }
          return false;
        }
        util.nativeFetch = nativeFetch2;
        function isNative(func) {
          return func.toString().indexOf("native") !== -1;
        }
        function parseURL(url) {
          var match2 = url.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/) || {};
          return {
            protocol: match2[2],
            host: match2[4],
            pathname: match2[5]
          };
        }
        util.parseURL = parseURL;
        function localURLPathname(url) {
          var parsed = parseURL(url);
          var parsedDocURL = parseURL(document.URL);
          if (!parsed.host || !parsed.protocol) {
            return parsed.pathname;
          }
          if (parsed.protocol === parsedDocURL.protocol && parsed.host === parsedDocURL.host) {
            return parsed.pathname;
          }
          return "".concat(parsed.protocol, "://").concat(parsed.host).concat(parsed.pathname);
        }
        util.localURLPathname = localURLPathname;
        function decodeCookie(string) {
          var result = {};
          string.split(/[;,]\s?/).forEach(function(pair) {
            var _a = pair.split("=", 2), key = _a[0], value = _a[1];
            result[key] = value;
          });
          return result;
        }
        util.decodeCookie = decodeCookie;
        function encodeCookie(object) {
          if (typeof object !== "object") {
            return void 0;
          }
          var cookies = [];
          for (var k2 in object) {
            cookies.push(k2 + "=" + object[k2]);
          }
          return cookies.join(";");
        }
        util.encodeCookie = encodeCookie;
        function getSiblings(element) {
          try {
            var nodes = element.parentNode.childNodes;
            var siblings_1 = [];
            Array.prototype.forEach.call(nodes, function(node) {
              if (node.tagName && node.tagName === element.tagName) {
                siblings_1.push(node);
              }
            });
            return siblings_1;
          } catch (e2) {
            return [];
          }
        }
        function truncate(string, length) {
          if (string.length > length) {
            string = string.substr(0, length) + "...";
          }
          return string;
        }
        util.preferCatch = function() {
          var preferCatch = true;
          if (typeof window === "undefined")
            return preferCatch;
          if (!window.atob) {
            preferCatch = false;
          }
          if (window.ErrorEvent) {
            try {
              if (new window.ErrorEvent("").colno === 0) {
                preferCatch = false;
              }
            } catch (_e2) {
            }
          }
          return preferCatch;
        }();
        function globalThisOrWindow() {
          if (typeof globalThis !== "undefined") {
            return globalThis;
          }
          if (typeof self !== "undefined") {
            return self;
          }
          return window;
        }
        util.globalThisOrWindow = globalThisOrWindow;
        var onerror = {};
        Object.defineProperty(onerror, "__esModule", { value: true });
        onerror.onError = onerror.ignoreNextOnError = void 0;
        var core_1$6 = src;
        var util_1$6 = util;
        var instrument$4 = core_1$6.Util.instrument, makeNotice = core_1$6.Util.makeNotice;
        var ignoreOnError = 0;
        var currentTimeout;
        function ignoreNextOnError() {
          ignoreOnError += 1;
          clearTimeout(currentTimeout);
          currentTimeout = setTimeout(function() {
            ignoreOnError = 0;
          });
        }
        onerror.ignoreNextOnError = ignoreNextOnError;
        function onError(_window) {
          if (_window === void 0) {
            _window = (0, util_1$6.globalThisOrWindow)();
          }
          return {
            load: function(client2) {
              instrument$4(_window, "onerror", function(original) {
                var onerror2 = function(msg, url, line, col, err) {
                  client2.logger.debug("window.onerror callback invoked", arguments);
                  if (ignoreOnError > 0) {
                    client2.logger.debug("Ignoring window.onerror (error likely reported earlier)", arguments);
                    ignoreOnError -= 1;
                    return;
                  }
                  if (line === 0 && /Script error\.?/.test(msg)) {
                    if (client2.config.enableUncaught) {
                      client2.logger.warn("Ignoring cross-domain script error: enable CORS to track these types of errors", arguments);
                    }
                    return;
                  }
                  var notice = makeNotice(err);
                  if (!notice.name) {
                    notice.name = "window.onerror";
                  }
                  if (!notice.message) {
                    notice.message = msg;
                  }
                  if (!notice.stack) {
                    notice.stack = [notice.message, "\n    at ? (", url || "unknown", ":", line || 0, ":", col || 0, ")"].join("");
                  }
                  client2.addBreadcrumb(notice.name === "window.onerror" || !notice.name ? "window.onerror" : "window.onerror: ".concat(notice.name), {
                    category: "error",
                    metadata: {
                      name: notice.name,
                      message: notice.message,
                      stack: notice.stack
                    }
                  });
                  if (client2.config.enableUncaught) {
                    client2.notify(notice);
                  }
                };
                return function(msg, url, line, col, err) {
                  onerror2(msg, url, line, col, err);
                  if (typeof original === "function") {
                    return original.apply(_window, arguments);
                  }
                  return false;
                };
              });
            }
          };
        }
        onerror.onError = onError;
        var onunhandledrejection = {};
        Object.defineProperty(onunhandledrejection, "__esModule", { value: true });
        var core_1$5 = src;
        var util_1$5 = util;
        var instrument$3 = core_1$5.Util.instrument;
        function default_1$4(_window) {
          if (_window === void 0) {
            _window = (0, util_1$5.globalThisOrWindow)();
          }
          return {
            load: function(client2) {
              if (!client2.config.enableUnhandledRejection) {
                return;
              }
              instrument$3(_window, "onunhandledrejection", function(original) {
                function onunhandledrejection2(promiseRejectionEvent) {
                  var _a;
                  client2.logger.debug("window.onunhandledrejection callback invoked", arguments);
                  if (!client2.config.enableUnhandledRejection) {
                    return;
                  }
                  var reason = promiseRejectionEvent.reason;
                  if (reason instanceof Error) {
                    var fileName = "unknown";
                    var lineNumber = 0;
                    var stackFallback = "".concat(reason.message, "\n    at ? (").concat(fileName, ":").concat(lineNumber, ")");
                    var stack = reason.stack || stackFallback;
                    var err = {
                      name: reason.name,
                      message: "UnhandledPromiseRejectionWarning: ".concat(reason),
                      stack
                    };
                    client2.addBreadcrumb("window.onunhandledrejection: ".concat(err.name), {
                      category: "error",
                      metadata: err
                    });
                    client2.notify(err);
                    return;
                  }
                  var message = typeof reason === "string" ? reason : (_a = JSON.stringify(reason)) !== null && _a !== void 0 ? _a : "Unspecified reason";
                  client2.notify({
                    name: "window.onunhandledrejection",
                    message: "UnhandledPromiseRejectionWarning: ".concat(message)
                  });
                }
                return function(promiseRejectionEvent) {
                  onunhandledrejection2(promiseRejectionEvent);
                  if (typeof original === "function") {
                    original.apply(this, arguments);
                  }
                };
              });
            }
          };
        }
        onunhandledrejection.default = default_1$4;
        var breadcrumbs = {};
        Object.defineProperty(breadcrumbs, "__esModule", { value: true });
        var core_1$4 = src;
        var util_1$4 = util;
        var sanitize$1 = core_1$4.Util.sanitize, instrument$2 = core_1$4.Util.instrument, instrumentConsole$1 = core_1$4.Util.instrumentConsole;
        function default_1$3(_window) {
          if (_window === void 0) {
            _window = (0, util_1$4.globalThisOrWindow)();
          }
          return {
            load: function(client2) {
              function breadcrumbsEnabled(type) {
                if (client2.config.breadcrumbsEnabled === true) {
                  return true;
                }
                if (type) {
                  return client2.config.breadcrumbsEnabled[type] === true;
                }
                return client2.config.breadcrumbsEnabled !== false;
              }
              (function() {
                if (!breadcrumbsEnabled("console")) {
                  return;
                }
                function inspectArray(obj) {
                  if (!Array.isArray(obj)) {
                    return "";
                  }
                  return obj.map(function(value) {
                    try {
                      return String(value);
                    } catch (e2) {
                      return "[unknown]";
                    }
                  }).join(" ");
                }
                instrumentConsole$1(_window, function(level, args) {
                  var message = inspectArray(args);
                  var opts = {
                    category: "log",
                    metadata: {
                      level,
                      arguments: sanitize$1(args, 3)
                    }
                  };
                  client2.addBreadcrumb(message, opts);
                });
              })();
              (function() {
                if (!breadcrumbsEnabled("dom")) {
                  return;
                }
                if (typeof _window.addEventListener !== "function") {
                  return;
                }
                _window.addEventListener("click", function(event) {
                  var message, selector, text;
                  try {
                    message = (0, util_1$4.stringNameOfElement)(event.target);
                    selector = (0, util_1$4.stringSelectorOfElement)(event.target);
                    text = (0, util_1$4.stringTextOfElement)(event.target);
                  } catch (e2) {
                    message = "UI Click";
                    selector = "[unknown]";
                    text = "[unknown]";
                  }
                  if (message.length === 0) {
                    return;
                  }
                  client2.addBreadcrumb(message, {
                    category: "ui.click",
                    metadata: {
                      selector,
                      text,
                      event
                    }
                  });
                }, _window.location ? true : false);
              })();
              (function() {
                if (!breadcrumbsEnabled("network")) {
                  return;
                }
                if (typeof XMLHttpRequest === "undefined") {
                  return;
                }
                instrument$2(XMLHttpRequest.prototype, "open", function(original) {
                  return function() {
                    var xhr = this;
                    var rawUrl = arguments[1];
                    var url = typeof rawUrl === "string" ? rawUrl : String(rawUrl);
                    var method = typeof arguments[0] === "string" ? arguments[0].toUpperCase() : arguments[0];
                    var message = "".concat(method, " ").concat((0, util_1$4.localURLPathname)(url));
                    this.__hb_xhr = {
                      type: "xhr",
                      method,
                      url,
                      message
                    };
                    if (typeof original === "function") {
                      original.apply(xhr, arguments);
                    }
                  };
                });
                instrument$2(XMLHttpRequest.prototype, "send", function(original) {
                  return function() {
                    var xhr = this;
                    function onreadystatechangeHandler() {
                      if (xhr.readyState === 4) {
                        var message = void 0;
                        if (xhr.__hb_xhr) {
                          xhr.__hb_xhr.status_code = xhr.status;
                          message = xhr.__hb_xhr.message;
                          delete xhr.__hb_xhr.message;
                        }
                        client2.addBreadcrumb(message || "XMLHttpRequest", {
                          category: "request",
                          metadata: xhr.__hb_xhr
                        });
                      }
                    }
                    if ("onreadystatechange" in xhr && typeof xhr.onreadystatechange === "function") {
                      instrument$2(xhr, "onreadystatechange", function(original2) {
                        return function() {
                          onreadystatechangeHandler();
                          if (typeof original2 === "function") {
                            original2.apply(this, arguments);
                          }
                        };
                      });
                    } else {
                      xhr.onreadystatechange = onreadystatechangeHandler;
                    }
                    if (typeof original === "function") {
                      original.apply(xhr, arguments);
                    }
                  };
                });
              })();
              (function() {
                if (!breadcrumbsEnabled("network")) {
                  return;
                }
                if (!(0, util_1$4.nativeFetch)()) {
                  return;
                }
                instrument$2(_window, "fetch", function(original) {
                  return function() {
                    var input = arguments[0];
                    var method = "GET";
                    var url;
                    if (typeof input === "string") {
                      url = input;
                    } else if ("Request" in _window && input instanceof Request) {
                      url = input.url;
                      if (input.method) {
                        method = input.method;
                      }
                    } else {
                      url = String(input);
                    }
                    if (arguments[1] && arguments[1].method) {
                      method = arguments[1].method;
                    }
                    if (typeof method === "string") {
                      method = method.toUpperCase();
                    }
                    var message = "".concat(method, " ").concat(typeof document === "undefined" ? url : (0, util_1$4.localURLPathname)(url));
                    var metadata = {
                      type: "fetch",
                      method,
                      url
                    };
                    return original.apply(this, arguments).then(function(response) {
                      metadata["status_code"] = response.status;
                      client2.addBreadcrumb(message, {
                        category: "request",
                        metadata
                      });
                      return response;
                    }).catch(function(error3) {
                      client2.addBreadcrumb("fetch error", {
                        category: "error",
                        metadata
                      });
                      throw error3;
                    });
                  };
                });
              })();
              (function() {
                if (!breadcrumbsEnabled("navigation")) {
                  return;
                }
                if (_window.location == null) {
                  return;
                }
                var lastHref = _window.location.href;
                function recordUrlChange(from, to) {
                  lastHref = to;
                  client2.addBreadcrumb("Page changed", {
                    category: "navigation",
                    metadata: {
                      from,
                      to
                    }
                  });
                }
                if (typeof addEventListener === "function") {
                  addEventListener("popstate", function(_event) {
                    recordUrlChange(lastHref, _window.location.href);
                  });
                }
                if (typeof _window.history === "undefined") {
                  return;
                }
                function historyWrapper(original) {
                  return function() {
                    var url = arguments.length > 2 ? arguments[2] : void 0;
                    if (url) {
                      recordUrlChange(lastHref, String(url));
                    }
                    return original.apply(this, arguments);
                  };
                }
                instrument$2(_window.history, "pushState", historyWrapper);
                instrument$2(_window.history, "replaceState", historyWrapper);
              })();
            }
          };
        }
        breadcrumbs.default = default_1$3;
        var events = {};
        Object.defineProperty(events, "__esModule", { value: true });
        var core_1$3 = src;
        var util_1$3 = util;
        var instrumentConsole = core_1$3.Util.instrumentConsole;
        function default_1$2(_window) {
          if (_window === void 0) {
            _window = (0, util_1$3.globalThisOrWindow)();
          }
          return {
            shouldReloadOnConfigure: false,
            load: function(client2) {
              function sendEventsToInsights() {
                return client2.config.eventsEnabled;
              }
              if (!sendEventsToInsights()) {
                return;
              }
              instrumentConsole(_window, function(level, args) {
                if (!sendEventsToInsights()) {
                  return;
                }
                client2.logEvent({
                  level,
                  args
                });
              });
            }
          };
        }
        events.default = default_1$2;
        var timers = {};
        Object.defineProperty(timers, "__esModule", { value: true });
        var core_1$2 = src;
        var util_1$2 = util;
        var instrument$1 = core_1$2.Util.instrument;
        function default_1$1(_window) {
          if (_window === void 0) {
            _window = (0, util_1$2.globalThisOrWindow)();
          }
          return {
            load: function(client2) {
              (function() {
                function instrumentTimer(wrapOpts) {
                  return function(original) {
                    return function(func, delay) {
                      if (typeof func === "function") {
                        var args_1 = Array.prototype.slice.call(arguments, 2);
                        func = client2.__wrap(func, wrapOpts);
                        return original(function() {
                          func.apply(void 0, args_1);
                        }, delay);
                      } else {
                        return original(func, delay);
                      }
                    };
                  };
                }
                instrument$1(_window, "setTimeout", instrumentTimer({ component: "setTimeout" }));
                instrument$1(_window, "setInterval", instrumentTimer({ component: "setInterval" }));
              })();
            }
          };
        }
        timers.default = default_1$1;
        var event_listeners = {};
        Object.defineProperty(event_listeners, "__esModule", { value: true });
        var core_1$1 = src;
        var util_1$1 = util;
        var instrument = core_1$1.Util.instrument;
        function default_1(_window) {
          if (_window === void 0) {
            _window = (0, util_1$1.globalThisOrWindow)();
          }
          return {
            load: function(client2) {
              var targets = ["EventTarget", "Window", "Node", "ApplicationCache", "AudioTrackList", "ChannelMergerNode", "CryptoOperation", "EventSource", "FileReader", "HTMLUnknownElement", "IDBDatabase", "IDBRequest", "IDBTransaction", "KeyOperation", "MediaController", "MessagePort", "ModalWindow", "Notification", "SVGElementInstance", "Screen", "TextTrack", "TextTrackCue", "TextTrackList", "WebSocket", "WebSocketWorker", "Worker", "XMLHttpRequest", "XMLHttpRequestEventTarget", "XMLHttpRequestUpload"];
              targets.forEach(function(prop) {
                var prototype = _window[prop] && _window[prop].prototype;
                if (prototype && Object.prototype.hasOwnProperty.call(prototype, "addEventListener")) {
                  instrument(prototype, "addEventListener", function(original) {
                    var wrapOpts = { component: "".concat(prop, ".prototype.addEventListener") };
                    return function(type, listener, useCapture, wantsUntrusted) {
                      try {
                        if (listener && listener.handleEvent != null) {
                          listener.handleEvent = client2.__wrap(listener.handleEvent, wrapOpts);
                        }
                      } catch (e2) {
                        client2.logger.error(e2);
                      }
                      return original.call(this, type, client2.__wrap(listener, wrapOpts), useCapture, wantsUntrusted);
                    };
                  });
                  instrument(prototype, "removeEventListener", function(original) {
                    return function(type, listener, useCapture, wantsUntrusted) {
                      original.call(this, type, listener, useCapture, wantsUntrusted);
                      return original.call(this, type, client2.__wrap(listener), useCapture, wantsUntrusted);
                    };
                  });
                }
              });
            }
          };
        }
        event_listeners.default = default_1;
        var transport = {};
        var __awaiter2 = commonjsGlobal && commonjsGlobal.__awaiter || function(thisArg, _arguments, P2, generator) {
          function adopt(value) {
            return value instanceof P2 ? value : new P2(function(resolve2) {
              resolve2(value);
            });
          }
          return new (P2 || (P2 = Promise))(function(resolve2, reject) {
            function fulfilled(value) {
              try {
                step(generator.next(value));
              } catch (e2) {
                reject(e2);
              }
            }
            function rejected(value) {
              try {
                step(generator["throw"](value));
              } catch (e2) {
                reject(e2);
              }
            }
            function step(result) {
              result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
            }
            step((generator = generator.apply(thisArg, _arguments || [])).next());
          });
        };
        var __generator2 = commonjsGlobal && commonjsGlobal.__generator || function(thisArg, body) {
          var _2 = { label: 0, sent: function() {
            if (t2[0] & 1)
              throw t2[1];
            return t2[1];
          }, trys: [], ops: [] }, f2, y2, t2, g2;
          return g2 = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g2[Symbol.iterator] = function() {
            return this;
          }), g2;
          function verb(n2) {
            return function(v2) {
              return step([n2, v2]);
            };
          }
          function step(op) {
            if (f2)
              throw new TypeError("Generator is already executing.");
            while (_2)
              try {
                if (f2 = 1, y2 && (t2 = op[0] & 2 ? y2["return"] : op[0] ? y2["throw"] || ((t2 = y2["return"]) && t2.call(y2), 0) : y2.next) && !(t2 = t2.call(y2, op[1])).done)
                  return t2;
                if (y2 = 0, t2)
                  op = [op[0] & 2, t2.value];
                switch (op[0]) {
                  case 0:
                  case 1:
                    t2 = op;
                    break;
                  case 4:
                    _2.label++;
                    return { value: op[1], done: false };
                  case 5:
                    _2.label++;
                    y2 = op[1];
                    op = [0];
                    continue;
                  case 7:
                    op = _2.ops.pop();
                    _2.trys.pop();
                    continue;
                  default:
                    if (!(t2 = _2.trys, t2 = t2.length > 0 && t2[t2.length - 1]) && (op[0] === 6 || op[0] === 2)) {
                      _2 = 0;
                      continue;
                    }
                    if (op[0] === 3 && (!t2 || op[1] > t2[0] && op[1] < t2[3])) {
                      _2.label = op[1];
                      break;
                    }
                    if (op[0] === 6 && _2.label < t2[1]) {
                      _2.label = t2[1];
                      t2 = op;
                      break;
                    }
                    if (t2 && _2.label < t2[2]) {
                      _2.label = t2[2];
                      _2.ops.push(op);
                      break;
                    }
                    if (t2[2])
                      _2.ops.pop();
                    _2.trys.pop();
                    continue;
                }
                op = body.call(thisArg, _2);
              } catch (e2) {
                op = [6, e2];
                y2 = 0;
              } finally {
                f2 = t2 = 0;
              }
            if (op[0] & 5)
              throw op[1];
            return { value: op[0] ? op[1] : void 0, done: true };
          }
        };
        Object.defineProperty(transport, "__esModule", { value: true });
        transport.BrowserTransport = void 0;
        var core_1 = src;
        var util_1 = util;
        var sanitize = core_1.Util.sanitize;
        function objectEntries(obj) {
          return Object.entries(obj);
        }
        var BrowserTransport = function() {
          function BrowserTransport2(headers) {
            if (headers === void 0) {
              headers = {};
            }
            this.headers = {};
            this.headers = headers;
          }
          BrowserTransport2.prototype.defaultHeaders = function() {
            return this.headers;
          };
          BrowserTransport2.prototype.send = function(options, payload) {
            return __awaiter2(this, void 0, void 0, function() {
              var headerArray, headers, requestInit, response, body;
              return __generator2(this, function(_a) {
                switch (_a.label) {
                  case 0:
                    headerArray = options.headers ? objectEntries(options.headers) : [];
                    headers = this.defaultHeaders();
                    headerArray.forEach(function(_a2) {
                      var key = _a2[0], value = _a2[1];
                      if (key != null && value != null) {
                        headers[String(key)] = String(value);
                      }
                    });
                    requestInit = {
                      method: options.method,
                      headers
                    };
                    if (options.method === "POST" && payload) {
                      requestInit.body = typeof payload === "string" ? payload : JSON.stringify(sanitize(payload, options.maxObjectDepth));
                    }
                    return [4, (0, util_1.globalThisOrWindow)().fetch(options.endpoint, requestInit)];
                  case 1:
                    response = _a.sent();
                    return [4, response.text()];
                  case 2:
                    body = _a.sent();
                    return [2, Promise.resolve({ statusCode: response.status, body })];
                }
              });
            });
          };
          return BrowserTransport2;
        }();
        transport.BrowserTransport = BrowserTransport;
        (function(exports2) {
          var __extends3 = commonjsGlobal && commonjsGlobal.__extends || function() {
            var extendStatics = function(d2, b2) {
              extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d3, b3) {
                d3.__proto__ = b3;
              } || function(d3, b3) {
                for (var p2 in b3)
                  if (Object.prototype.hasOwnProperty.call(b3, p2))
                    d3[p2] = b3[p2];
              };
              return extendStatics(d2, b2);
            };
            return function(d2, b2) {
              if (typeof b2 !== "function" && b2 !== null)
                throw new TypeError("Class extends value " + String(b2) + " is not a constructor or null");
              extendStatics(d2, b2);
              function __() {
                this.constructor = d2;
              }
              d2.prototype = b2 === null ? Object.create(b2) : (__.prototype = b2.prototype, new __());
            };
          }();
          var __assign2 = commonjsGlobal && commonjsGlobal.__assign || function() {
            __assign2 = Object.assign || function(t2) {
              for (var s2, i2 = 1, n2 = arguments.length; i2 < n2; i2++) {
                s2 = arguments[i2];
                for (var p2 in s2)
                  if (Object.prototype.hasOwnProperty.call(s2, p2))
                    t2[p2] = s2[p2];
              }
              return t2;
            };
            return __assign2.apply(this, arguments);
          };
          var __awaiter3 = commonjsGlobal && commonjsGlobal.__awaiter || function(thisArg, _arguments, P2, generator) {
            function adopt(value) {
              return value instanceof P2 ? value : new P2(function(resolve2) {
                resolve2(value);
              });
            }
            return new (P2 || (P2 = Promise))(function(resolve2, reject) {
              function fulfilled(value) {
                try {
                  step(generator.next(value));
                } catch (e2) {
                  reject(e2);
                }
              }
              function rejected(value) {
                try {
                  step(generator["throw"](value));
                } catch (e2) {
                  reject(e2);
                }
              }
              function step(result) {
                result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
              }
              step((generator = generator.apply(thisArg, _arguments || [])).next());
            });
          };
          var __generator3 = commonjsGlobal && commonjsGlobal.__generator || function(thisArg, body) {
            var _2 = { label: 0, sent: function() {
              if (t2[0] & 1)
                throw t2[1];
              return t2[1];
            }, trys: [], ops: [] }, f2, y2, t2, g2;
            return g2 = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g2[Symbol.iterator] = function() {
              return this;
            }), g2;
            function verb(n2) {
              return function(v2) {
                return step([n2, v2]);
              };
            }
            function step(op) {
              if (f2)
                throw new TypeError("Generator is already executing.");
              while (_2)
                try {
                  if (f2 = 1, y2 && (t2 = op[0] & 2 ? y2["return"] : op[0] ? y2["throw"] || ((t2 = y2["return"]) && t2.call(y2), 0) : y2.next) && !(t2 = t2.call(y2, op[1])).done)
                    return t2;
                  if (y2 = 0, t2)
                    op = [op[0] & 2, t2.value];
                  switch (op[0]) {
                    case 0:
                    case 1:
                      t2 = op;
                      break;
                    case 4:
                      _2.label++;
                      return { value: op[1], done: false };
                    case 5:
                      _2.label++;
                      y2 = op[1];
                      op = [0];
                      continue;
                    case 7:
                      op = _2.ops.pop();
                      _2.trys.pop();
                      continue;
                    default:
                      if (!(t2 = _2.trys, t2 = t2.length > 0 && t2[t2.length - 1]) && (op[0] === 6 || op[0] === 2)) {
                        _2 = 0;
                        continue;
                      }
                      if (op[0] === 3 && (!t2 || op[1] > t2[0] && op[1] < t2[3])) {
                        _2.label = op[1];
                        break;
                      }
                      if (op[0] === 6 && _2.label < t2[1]) {
                        _2.label = t2[1];
                        t2 = op;
                        break;
                      }
                      if (t2 && _2.label < t2[2]) {
                        _2.label = t2[2];
                        _2.ops.push(op);
                        break;
                      }
                      if (t2[2])
                        _2.ops.pop();
                      _2.trys.pop();
                      continue;
                  }
                  op = body.call(thisArg, _2);
                } catch (e2) {
                  op = [6, e2];
                  y2 = 0;
                } finally {
                  f2 = t2 = 0;
                }
              if (op[0] & 5)
                throw op[1];
              return { value: op[0] ? op[1] : void 0, done: true };
            }
          };
          var __importDefault = commonjsGlobal && commonjsGlobal.__importDefault || function(mod) {
            return mod && mod.__esModule ? mod : { "default": mod };
          };
          Object.defineProperty(exports2, "__esModule", { value: true });
          exports2.Types = exports2.getUserFeedbackScriptUrl = void 0;
          var core_12 = src;
          var util_12 = util;
          var onerror_1 = onerror;
          var onunhandledrejection_1 = __importDefault(onunhandledrejection);
          var breadcrumbs_1 = __importDefault(breadcrumbs);
          var events_1 = __importDefault(events);
          var timers_1 = __importDefault(timers);
          var event_listeners_1 = __importDefault(event_listeners);
          var transport_1 = transport;
          var merge2 = core_12.Util.merge, filter = core_12.Util.filter, objectIsExtensible = core_12.Util.objectIsExtensible;
          var getProjectRoot = function() {
            var global2 = (0, util_12.globalThisOrWindow)();
            var projectRoot = "";
            if (global2.location != null) {
              projectRoot = global2.location.protocol + "//" + global2.location.host;
            }
            return projectRoot;
          };
          var getUserFeedbackScriptUrl = function(version2) {
            var majorMinorVersion = version2.split(".").slice(0, 2).join(".");
            return "https://js.honeybadger.io/v".concat(majorMinorVersion, "/honeybadger-feedback-form.js");
          };
          exports2.getUserFeedbackScriptUrl = getUserFeedbackScriptUrl;
          var Honeybadger2 = function(_super) {
            __extends3(Honeybadger3, _super);
            function Honeybadger3(opts) {
              if (opts === void 0) {
                opts = {};
              }
              var _this = _super.call(this, __assign2({ userFeedbackEndpoint: "https://api.honeybadger.io/v2/feedback", async: true, maxErrors: null, projectRoot: getProjectRoot() }, opts), new transport_1.BrowserTransport({
                "User-Agent": userAgent()
              })) || this;
              _this.__errorsSent = 0;
              _this.__lastWrapErr = void 0;
              _this.__lastNoticeId = void 0;
              _this.__beforeNotifyHandlers = [
                function(notice) {
                  if (_this.__exceedsMaxErrors()) {
                    _this.logger.debug("Dropping notice: max errors exceeded", notice);
                    return false;
                  }
                  if (notice && !notice.url && typeof document !== "undefined") {
                    notice.url = document.URL;
                  }
                  _this.__incrementErrorsCount();
                  return true;
                }
              ];
              _this.__afterNotifyHandlers = [
                function(_error, notice) {
                  if (notice) {
                    _this.__lastNoticeId = notice.id;
                  }
                }
              ];
              return _this;
            }
            Honeybadger3.prototype.configure = function(opts) {
              if (opts === void 0) {
                opts = {};
              }
              return _super.prototype.configure.call(this, opts);
            };
            Honeybadger3.prototype.resetMaxErrors = function() {
              return this.__errorsSent = 0;
            };
            Honeybadger3.prototype.factory = function(opts) {
              var clone2 = new Honeybadger3(opts);
              clone2.setNotifier(this.getNotifier());
              return clone2;
            };
            Honeybadger3.prototype.checkIn = function(_id) {
              throw new Error("Honeybadger.checkIn() is not supported on the browser");
            };
            Honeybadger3.prototype.showUserFeedbackForm = function(options) {
              if (options === void 0) {
                options = {};
              }
              return __awaiter3(this, void 0, void 0, function() {
                var global2;
                return __generator3(this, function(_a) {
                  if (!this.config || !this.config.apiKey) {
                    this.logger.debug("Client not initialized");
                    return [2];
                  }
                  if (!this.__lastNoticeId) {
                    this.logger.debug("Can't show user feedback form without a notice already reported");
                    return [2];
                  }
                  global2 = (0, util_12.globalThisOrWindow)();
                  if (typeof global2.document === "undefined") {
                    this.logger.debug("global.document is undefined. Cannot attach script");
                    return [2];
                  }
                  if (this.isUserFeedbackScriptUrlAlreadyVisible()) {
                    this.logger.debug("User feedback form is already visible");
                    return [2];
                  }
                  global2["honeybadgerUserFeedbackOptions"] = __assign2(__assign2({}, options), { apiKey: this.config.apiKey, endpoint: this.config.userFeedbackEndpoint, noticeId: this.__lastNoticeId });
                  this.appendUserFeedbackScriptTag(global2, options);
                  return [2];
                });
              });
            };
            Honeybadger3.prototype.appendUserFeedbackScriptTag = function(window2, options) {
              if (options === void 0) {
                options = {};
              }
              var script = window2.document.createElement("script");
              script.setAttribute("src", this.getUserFeedbackSubmitUrl());
              script.setAttribute("async", "true");
              if (options.onLoad) {
                script.onload = options.onLoad;
              }
              (commonjsGlobal.document.head || commonjsGlobal.document.body).appendChild(script);
            };
            Honeybadger3.prototype.isUserFeedbackScriptUrlAlreadyVisible = function() {
              var global2 = (0, util_12.globalThisOrWindow)();
              var feedbackScriptUrl = this.getUserFeedbackSubmitUrl();
              for (var i2 = 0; i2 < global2.document.scripts.length; i2++) {
                var script = global2.document.scripts[i2];
                if (script.src === feedbackScriptUrl) {
                  return true;
                }
              }
              return false;
            };
            Honeybadger3.prototype.getUserFeedbackSubmitUrl = function() {
              return (0, exports2.getUserFeedbackScriptUrl)(this.getVersion());
            };
            Honeybadger3.prototype.__buildPayload = function(notice) {
              var cgiData = {
                HTTP_USER_AGENT: void 0,
                HTTP_REFERER: void 0,
                HTTP_COOKIE: void 0
              };
              if (typeof navigator !== "undefined" && navigator.userAgent) {
                cgiData.HTTP_USER_AGENT = navigator.userAgent;
              }
              if (typeof document !== "undefined" && document.referrer.match(/\S/)) {
                cgiData.HTTP_REFERER = document.referrer;
              }
              var cookiesObject;
              if (typeof notice.cookies === "string") {
                cookiesObject = (0, util_12.decodeCookie)(notice.cookies);
              } else {
                cookiesObject = notice.cookies;
              }
              if (cookiesObject) {
                cgiData.HTTP_COOKIE = (0, util_12.encodeCookie)(filter(cookiesObject, this.config.filters));
              }
              var payload = _super.prototype.__buildPayload.call(this, notice);
              payload.request.cgi_data = merge2(cgiData, payload.request.cgi_data);
              return payload;
            };
            Honeybadger3.prototype.__wrap = function(f2, opts) {
              if (opts === void 0) {
                opts = {};
              }
              var func = f2;
              if (!opts) {
                opts = {};
              }
              try {
                if (typeof func !== "function") {
                  return func;
                }
                if (!objectIsExtensible(func)) {
                  return func;
                }
                if (!func.___hb) {
                  var client_1 = this;
                  func.___hb = function() {
                    if (util_12.preferCatch) {
                      try {
                        return func.apply(this, arguments);
                      } catch (err) {
                        if (client_1.__lastWrapErr === err) {
                          throw err;
                        }
                        client_1.__lastWrapErr = err;
                        (0, onerror_1.ignoreNextOnError)();
                        client_1.addBreadcrumb(opts.component ? "".concat(opts.component, ": ").concat(err.name) : err.name, {
                          category: "error",
                          metadata: {
                            message: err.message,
                            name: err.name,
                            stack: err.stack
                          }
                        });
                        if (client_1.config.enableUncaught) {
                          client_1.notify(err);
                        }
                        throw err;
                      }
                    } else {
                      return func.apply(this, arguments);
                    }
                  };
                }
                func.___hb.___hb = func.___hb;
                return func.___hb;
              } catch (_e2) {
                return func;
              }
            };
            Honeybadger3.prototype.__incrementErrorsCount = function() {
              return this.__errorsSent++;
            };
            Honeybadger3.prototype.__exceedsMaxErrors = function() {
              return this.config.maxErrors && this.__errorsSent >= this.config.maxErrors;
            };
            return Honeybadger3;
          }(core_12.Client);
          var NOTIFIER = {
            name: "@honeybadger-io/js",
            url: "https://github.com/honeybadger-io/honeybadger-js/tree/master/packages/js",
            version: "6.8.3"
          };
          var userAgent = function() {
            if (typeof navigator !== "undefined") {
              return "Honeybadger JS Browser Client ".concat(NOTIFIER.version, "; ").concat(navigator.userAgent);
            }
            return "Honeybadger JS Browser Client ".concat(NOTIFIER.version, "; n/a; n/a");
          };
          var singleton = new Honeybadger2({
            __plugins: [
              (0, onerror_1.onError)(),
              (0, onunhandledrejection_1.default)(),
              (0, timers_1.default)(),
              (0, event_listeners_1.default)(),
              (0, breadcrumbs_1.default)(),
              (0, events_1.default)()
            ]
          });
          singleton.setNotifier(NOTIFIER);
          var core_2 = src;
          Object.defineProperty(exports2, "Types", { enumerable: true, get: function() {
            return core_2.Types;
          } });
          exports2.default = singleton;
        })(browser$1);
        var browser = /* @__PURE__ */ getDefaultExportFromCjs(browser$1);
        return browser;
      });
    }
  });

  // ../../node_modules/jquery/dist/jquery.js
  var require_jquery = __commonJS({
    "../../node_modules/jquery/dist/jquery.js"(exports, module) {
      (function(global2, factory) {
        "use strict";
        if (typeof module === "object" && typeof module.exports === "object") {
          module.exports = global2.document ? factory(global2, true) : function(w2) {
            if (!w2.document) {
              throw new Error("jQuery requires a window with a document");
            }
            return factory(w2);
          };
        } else {
          factory(global2);
        }
      })(typeof window !== "undefined" ? window : exports, function(window2, noGlobal) {
        "use strict";
        var arr = [];
        var getProto = Object.getPrototypeOf;
        var slice = arr.slice;
        var flat = arr.flat ? function(array) {
          return arr.flat.call(array);
        } : function(array) {
          return arr.concat.apply([], array);
        };
        var push = arr.push;
        var indexOf2 = arr.indexOf;
        var class2type = {};
        var toString = class2type.toString;
        var hasOwn = class2type.hasOwnProperty;
        var fnToString = hasOwn.toString;
        var ObjectFunctionString = fnToString.call(Object);
        var support = {};
        var isFunction2 = function isFunction3(obj) {
          return typeof obj === "function" && typeof obj.nodeType !== "number" && typeof obj.item !== "function";
        };
        var isWindow = function isWindow2(obj) {
          return obj != null && obj === obj.window;
        };
        var document2 = window2.document;
        var preservedScriptAttributes = {
          type: true,
          src: true,
          nonce: true,
          noModule: true
        };
        function DOMEval(code, node, doc) {
          doc = doc || document2;
          var i2, val, script = doc.createElement("script");
          script.text = code;
          if (node) {
            for (i2 in preservedScriptAttributes) {
              val = node[i2] || node.getAttribute && node.getAttribute(i2);
              if (val) {
                script.setAttribute(i2, val);
              }
            }
          }
          doc.head.appendChild(script).parentNode.removeChild(script);
        }
        function toType2(obj) {
          if (obj == null) {
            return obj + "";
          }
          return typeof obj === "object" || typeof obj === "function" ? class2type[toString.call(obj)] || "object" : typeof obj;
        }
        var version2 = "3.6.0", jQuery2 = function(selector, context) {
          return new jQuery2.fn.init(selector, context);
        };
        jQuery2.fn = jQuery2.prototype = {
          jquery: version2,
          constructor: jQuery2,
          length: 0,
          toArray: function() {
            return slice.call(this);
          },
          get: function(num) {
            if (num == null) {
              return slice.call(this);
            }
            return num < 0 ? this[num + this.length] : this[num];
          },
          pushStack: function(elems) {
            var ret = jQuery2.merge(this.constructor(), elems);
            ret.prevObject = this;
            return ret;
          },
          each: function(callback2) {
            return jQuery2.each(this, callback2);
          },
          map: function(callback2) {
            return this.pushStack(jQuery2.map(this, function(elem, i2) {
              return callback2.call(elem, i2, elem);
            }));
          },
          slice: function() {
            return this.pushStack(slice.apply(this, arguments));
          },
          first: function() {
            return this.eq(0);
          },
          last: function() {
            return this.eq(-1);
          },
          even: function() {
            return this.pushStack(jQuery2.grep(this, function(_elem, i2) {
              return (i2 + 1) % 2;
            }));
          },
          odd: function() {
            return this.pushStack(jQuery2.grep(this, function(_elem, i2) {
              return i2 % 2;
            }));
          },
          eq: function(i2) {
            var len = this.length, j2 = +i2 + (i2 < 0 ? len : 0);
            return this.pushStack(j2 >= 0 && j2 < len ? [this[j2]] : []);
          },
          end: function() {
            return this.prevObject || this.constructor();
          },
          push,
          sort: arr.sort,
          splice: arr.splice
        };
        jQuery2.extend = jQuery2.fn.extend = function() {
          var options, name, src, copy, copyIsArray, clone2, target = arguments[0] || {}, i2 = 1, length = arguments.length, deep = false;
          if (typeof target === "boolean") {
            deep = target;
            target = arguments[i2] || {};
            i2++;
          }
          if (typeof target !== "object" && !isFunction2(target)) {
            target = {};
          }
          if (i2 === length) {
            target = this;
            i2--;
          }
          for (; i2 < length; i2++) {
            if ((options = arguments[i2]) != null) {
              for (name in options) {
                copy = options[name];
                if (name === "__proto__" || target === copy) {
                  continue;
                }
                if (deep && copy && (jQuery2.isPlainObject(copy) || (copyIsArray = Array.isArray(copy)))) {
                  src = target[name];
                  if (copyIsArray && !Array.isArray(src)) {
                    clone2 = [];
                  } else if (!copyIsArray && !jQuery2.isPlainObject(src)) {
                    clone2 = {};
                  } else {
                    clone2 = src;
                  }
                  copyIsArray = false;
                  target[name] = jQuery2.extend(deep, clone2, copy);
                } else if (copy !== void 0) {
                  target[name] = copy;
                }
              }
            }
          }
          return target;
        };
        jQuery2.extend({
          expando: "jQuery" + (version2 + Math.random()).replace(/\D/g, ""),
          isReady: true,
          error: function(msg) {
            throw new Error(msg);
          },
          noop: function() {
          },
          isPlainObject: function(obj) {
            var proto, Ctor;
            if (!obj || toString.call(obj) !== "[object Object]") {
              return false;
            }
            proto = getProto(obj);
            if (!proto) {
              return true;
            }
            Ctor = hasOwn.call(proto, "constructor") && proto.constructor;
            return typeof Ctor === "function" && fnToString.call(Ctor) === ObjectFunctionString;
          },
          isEmptyObject: function(obj) {
            var name;
            for (name in obj) {
              return false;
            }
            return true;
          },
          globalEval: function(code, options, doc) {
            DOMEval(code, { nonce: options && options.nonce }, doc);
          },
          each: function(obj, callback2) {
            var length, i2 = 0;
            if (isArrayLike(obj)) {
              length = obj.length;
              for (; i2 < length; i2++) {
                if (callback2.call(obj[i2], i2, obj[i2]) === false) {
                  break;
                }
              }
            } else {
              for (i2 in obj) {
                if (callback2.call(obj[i2], i2, obj[i2]) === false) {
                  break;
                }
              }
            }
            return obj;
          },
          makeArray: function(arr2, results) {
            var ret = results || [];
            if (arr2 != null) {
              if (isArrayLike(Object(arr2))) {
                jQuery2.merge(ret, typeof arr2 === "string" ? [arr2] : arr2);
              } else {
                push.call(ret, arr2);
              }
            }
            return ret;
          },
          inArray: function(elem, arr2, i2) {
            return arr2 == null ? -1 : indexOf2.call(arr2, elem, i2);
          },
          merge: function(first, second) {
            var len = +second.length, j2 = 0, i2 = first.length;
            for (; j2 < len; j2++) {
              first[i2++] = second[j2];
            }
            first.length = i2;
            return first;
          },
          grep: function(elems, callback2, invert) {
            var callbackInverse, matches = [], i2 = 0, length = elems.length, callbackExpect = !invert;
            for (; i2 < length; i2++) {
              callbackInverse = !callback2(elems[i2], i2);
              if (callbackInverse !== callbackExpect) {
                matches.push(elems[i2]);
              }
            }
            return matches;
          },
          map: function(elems, callback2, arg) {
            var length, value, i2 = 0, ret = [];
            if (isArrayLike(elems)) {
              length = elems.length;
              for (; i2 < length; i2++) {
                value = callback2(elems[i2], i2, arg);
                if (value != null) {
                  ret.push(value);
                }
              }
            } else {
              for (i2 in elems) {
                value = callback2(elems[i2], i2, arg);
                if (value != null) {
                  ret.push(value);
                }
              }
            }
            return flat(ret);
          },
          guid: 1,
          support
        });
        if (typeof Symbol === "function") {
          jQuery2.fn[Symbol.iterator] = arr[Symbol.iterator];
        }
        jQuery2.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "), function(_i2, name) {
          class2type["[object " + name + "]"] = name.toLowerCase();
        });
        function isArrayLike(obj) {
          var length = !!obj && "length" in obj && obj.length, type = toType2(obj);
          if (isFunction2(obj) || isWindow(obj)) {
            return false;
          }
          return type === "array" || length === 0 || typeof length === "number" && length > 0 && length - 1 in obj;
        }
        var Sizzle = function(window3) {
          var i2, support2, Expr, getText, isXML, tokenize2, compile, select, outermostContext, sortInput, hasDuplicate, setDocument, document3, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains2, expando = "sizzle" + 1 * new Date(), preferredDoc = window3.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), nonnativeSelectorCache = createCache(), sortOrder = function(a2, b2) {
            if (a2 === b2) {
              hasDuplicate = true;
            }
            return 0;
          }, hasOwn2 = {}.hasOwnProperty, arr2 = [], pop = arr2.pop, pushNative = arr2.push, push2 = arr2.push, slice2 = arr2.slice, indexOf3 = function(list, elem) {
            var i3 = 0, len = list.length;
            for (; i3 < len; i3++) {
              if (list[i3] === elem) {
                return i3;
              }
            }
            return -1;
          }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", whitespace = "[\\x20\\t\\r\\n\\f]", identifier = "(?:\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+", attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + "*([*^$|!~]?=)" + whitespace + `*(?:'((?:\\\\.|[^\\\\'])*)'|"((?:\\\\.|[^\\\\"])*)"|(` + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + identifier + `)(?:\\((('((?:\\\\.|[^\\\\'])*)'|"((?:\\\\.|[^\\\\"])*)")|((?:\\\\.|[^\\\\()[\\]]|` + attributes + ")*)|.*)\\)|)", rwhitespace = new RegExp(whitespace + "+", "g"), rtrim2 = new RegExp("^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g"), rcomma = new RegExp("^" + whitespace + "*," + whitespace + "*"), rcombinators = new RegExp("^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*"), rdescend = new RegExp(whitespace + "|>"), rpseudo = new RegExp(pseudos), ridentifier = new RegExp("^" + identifier + "$"), matchExpr = {
            "ID": new RegExp("^#(" + identifier + ")"),
            "CLASS": new RegExp("^\\.(" + identifier + ")"),
            "TAG": new RegExp("^(" + identifier + "|[*])"),
            "ATTR": new RegExp("^" + attributes),
            "PSEUDO": new RegExp("^" + pseudos),
            "CHILD": new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i"),
            "bool": new RegExp("^(?:" + booleans + ")$", "i"),
            "needsContext": new RegExp("^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i")
          }, rhtml2 = /HTML$/i, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, rquickExpr2 = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, runescape = new RegExp("\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\([^\\r\\n\\f])", "g"), funescape = function(escape2, nonHex) {
            var high = "0x" + escape2.slice(1) - 65536;
            return nonHex ? nonHex : high < 0 ? String.fromCharCode(high + 65536) : String.fromCharCode(high >> 10 | 55296, high & 1023 | 56320);
          }, rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g, fcssescape = function(ch, asCodePoint) {
            if (asCodePoint) {
              if (ch === "\0") {
                return "\uFFFD";
              }
              return ch.slice(0, -1) + "\\" + ch.charCodeAt(ch.length - 1).toString(16) + " ";
            }
            return "\\" + ch;
          }, unloadHandler = function() {
            setDocument();
          }, inDisabledFieldset = addCombinator(function(elem) {
            return elem.disabled === true && elem.nodeName.toLowerCase() === "fieldset";
          }, { dir: "parentNode", next: "legend" });
          try {
            push2.apply(arr2 = slice2.call(preferredDoc.childNodes), preferredDoc.childNodes);
            arr2[preferredDoc.childNodes.length].nodeType;
          } catch (e2) {
            push2 = {
              apply: arr2.length ? function(target, els) {
                pushNative.apply(target, slice2.call(els));
              } : function(target, els) {
                var j2 = target.length, i3 = 0;
                while (target[j2++] = els[i3++]) {
                }
                target.length = j2 - 1;
              }
            };
          }
          function Sizzle2(selector, context, results, seed) {
            var m2, i3, elem, nid, match2, groups, newSelector, newContext = context && context.ownerDocument, nodeType = context ? context.nodeType : 9;
            results = results || [];
            if (typeof selector !== "string" || !selector || nodeType !== 1 && nodeType !== 9 && nodeType !== 11) {
              return results;
            }
            if (!seed) {
              setDocument(context);
              context = context || document3;
              if (documentIsHTML) {
                if (nodeType !== 11 && (match2 = rquickExpr2.exec(selector))) {
                  if (m2 = match2[1]) {
                    if (nodeType === 9) {
                      if (elem = context.getElementById(m2)) {
                        if (elem.id === m2) {
                          results.push(elem);
                          return results;
                        }
                      } else {
                        return results;
                      }
                    } else {
                      if (newContext && (elem = newContext.getElementById(m2)) && contains2(context, elem) && elem.id === m2) {
                        results.push(elem);
                        return results;
                      }
                    }
                  } else if (match2[2]) {
                    push2.apply(results, context.getElementsByTagName(selector));
                    return results;
                  } else if ((m2 = match2[3]) && support2.getElementsByClassName && context.getElementsByClassName) {
                    push2.apply(results, context.getElementsByClassName(m2));
                    return results;
                  }
                }
                if (support2.qsa && !nonnativeSelectorCache[selector + " "] && (!rbuggyQSA || !rbuggyQSA.test(selector)) && (nodeType !== 1 || context.nodeName.toLowerCase() !== "object")) {
                  newSelector = selector;
                  newContext = context;
                  if (nodeType === 1 && (rdescend.test(selector) || rcombinators.test(selector))) {
                    newContext = rsibling.test(selector) && testContext(context.parentNode) || context;
                    if (newContext !== context || !support2.scope) {
                      if (nid = context.getAttribute("id")) {
                        nid = nid.replace(rcssescape, fcssescape);
                      } else {
                        context.setAttribute("id", nid = expando);
                      }
                    }
                    groups = tokenize2(selector);
                    i3 = groups.length;
                    while (i3--) {
                      groups[i3] = (nid ? "#" + nid : ":scope") + " " + toSelector(groups[i3]);
                    }
                    newSelector = groups.join(",");
                  }
                  try {
                    push2.apply(results, newContext.querySelectorAll(newSelector));
                    return results;
                  } catch (qsaError) {
                    nonnativeSelectorCache(selector, true);
                  } finally {
                    if (nid === expando) {
                      context.removeAttribute("id");
                    }
                  }
                }
              }
            }
            return select(selector.replace(rtrim2, "$1"), context, results, seed);
          }
          function createCache() {
            var keys = [];
            function cache2(key, value) {
              if (keys.push(key + " ") > Expr.cacheLength) {
                delete cache2[keys.shift()];
              }
              return cache2[key + " "] = value;
            }
            return cache2;
          }
          function markFunction(fn3) {
            fn3[expando] = true;
            return fn3;
          }
          function assert(fn3) {
            var el = document3.createElement("fieldset");
            try {
              return !!fn3(el);
            } catch (e2) {
              return false;
            } finally {
              if (el.parentNode) {
                el.parentNode.removeChild(el);
              }
              el = null;
            }
          }
          function addHandle(attrs, handler) {
            var arr3 = attrs.split("|"), i3 = arr3.length;
            while (i3--) {
              Expr.attrHandle[arr3[i3]] = handler;
            }
          }
          function siblingCheck(a2, b2) {
            var cur = b2 && a2, diff = cur && a2.nodeType === 1 && b2.nodeType === 1 && a2.sourceIndex - b2.sourceIndex;
            if (diff) {
              return diff;
            }
            if (cur) {
              while (cur = cur.nextSibling) {
                if (cur === b2) {
                  return -1;
                }
              }
            }
            return a2 ? 1 : -1;
          }
          function createInputPseudo(type) {
            return function(elem) {
              var name = elem.nodeName.toLowerCase();
              return name === "input" && elem.type === type;
            };
          }
          function createButtonPseudo(type) {
            return function(elem) {
              var name = elem.nodeName.toLowerCase();
              return (name === "input" || name === "button") && elem.type === type;
            };
          }
          function createDisabledPseudo(disabled) {
            return function(elem) {
              if ("form" in elem) {
                if (elem.parentNode && elem.disabled === false) {
                  if ("label" in elem) {
                    if ("label" in elem.parentNode) {
                      return elem.parentNode.disabled === disabled;
                    } else {
                      return elem.disabled === disabled;
                    }
                  }
                  return elem.isDisabled === disabled || elem.isDisabled !== !disabled && inDisabledFieldset(elem) === disabled;
                }
                return elem.disabled === disabled;
              } else if ("label" in elem) {
                return elem.disabled === disabled;
              }
              return false;
            };
          }
          function createPositionalPseudo(fn3) {
            return markFunction(function(argument) {
              argument = +argument;
              return markFunction(function(seed, matches2) {
                var j2, matchIndexes = fn3([], seed.length, argument), i3 = matchIndexes.length;
                while (i3--) {
                  if (seed[j2 = matchIndexes[i3]]) {
                    seed[j2] = !(matches2[j2] = seed[j2]);
                  }
                }
              });
            });
          }
          function testContext(context) {
            return context && typeof context.getElementsByTagName !== "undefined" && context;
          }
          support2 = Sizzle2.support = {};
          isXML = Sizzle2.isXML = function(elem) {
            var namespace = elem && elem.namespaceURI, docElem2 = elem && (elem.ownerDocument || elem).documentElement;
            return !rhtml2.test(namespace || docElem2 && docElem2.nodeName || "HTML");
          };
          setDocument = Sizzle2.setDocument = function(node) {
            var hasCompare, subWindow, doc = node ? node.ownerDocument || node : preferredDoc;
            if (doc == document3 || doc.nodeType !== 9 || !doc.documentElement) {
              return document3;
            }
            document3 = doc;
            docElem = document3.documentElement;
            documentIsHTML = !isXML(document3);
            if (preferredDoc != document3 && (subWindow = document3.defaultView) && subWindow.top !== subWindow) {
              if (subWindow.addEventListener) {
                subWindow.addEventListener("unload", unloadHandler, false);
              } else if (subWindow.attachEvent) {
                subWindow.attachEvent("onunload", unloadHandler);
              }
            }
            support2.scope = assert(function(el) {
              docElem.appendChild(el).appendChild(document3.createElement("div"));
              return typeof el.querySelectorAll !== "undefined" && !el.querySelectorAll(":scope fieldset div").length;
            });
            support2.attributes = assert(function(el) {
              el.className = "i";
              return !el.getAttribute("className");
            });
            support2.getElementsByTagName = assert(function(el) {
              el.appendChild(document3.createComment(""));
              return !el.getElementsByTagName("*").length;
            });
            support2.getElementsByClassName = rnative.test(document3.getElementsByClassName);
            support2.getById = assert(function(el) {
              docElem.appendChild(el).id = expando;
              return !document3.getElementsByName || !document3.getElementsByName(expando).length;
            });
            if (support2.getById) {
              Expr.filter["ID"] = function(id2) {
                var attrId = id2.replace(runescape, funescape);
                return function(elem) {
                  return elem.getAttribute("id") === attrId;
                };
              };
              Expr.find["ID"] = function(id2, context) {
                if (typeof context.getElementById !== "undefined" && documentIsHTML) {
                  var elem = context.getElementById(id2);
                  return elem ? [elem] : [];
                }
              };
            } else {
              Expr.filter["ID"] = function(id2) {
                var attrId = id2.replace(runescape, funescape);
                return function(elem) {
                  var node2 = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
                  return node2 && node2.value === attrId;
                };
              };
              Expr.find["ID"] = function(id2, context) {
                if (typeof context.getElementById !== "undefined" && documentIsHTML) {
                  var node2, i3, elems, elem = context.getElementById(id2);
                  if (elem) {
                    node2 = elem.getAttributeNode("id");
                    if (node2 && node2.value === id2) {
                      return [elem];
                    }
                    elems = context.getElementsByName(id2);
                    i3 = 0;
                    while (elem = elems[i3++]) {
                      node2 = elem.getAttributeNode("id");
                      if (node2 && node2.value === id2) {
                        return [elem];
                      }
                    }
                  }
                  return [];
                }
              };
            }
            Expr.find["TAG"] = support2.getElementsByTagName ? function(tag, context) {
              if (typeof context.getElementsByTagName !== "undefined") {
                return context.getElementsByTagName(tag);
              } else if (support2.qsa) {
                return context.querySelectorAll(tag);
              }
            } : function(tag, context) {
              var elem, tmp = [], i3 = 0, results = context.getElementsByTagName(tag);
              if (tag === "*") {
                while (elem = results[i3++]) {
                  if (elem.nodeType === 1) {
                    tmp.push(elem);
                  }
                }
                return tmp;
              }
              return results;
            };
            Expr.find["CLASS"] = support2.getElementsByClassName && function(className, context) {
              if (typeof context.getElementsByClassName !== "undefined" && documentIsHTML) {
                return context.getElementsByClassName(className);
              }
            };
            rbuggyMatches = [];
            rbuggyQSA = [];
            if (support2.qsa = rnative.test(document3.querySelectorAll)) {
              assert(function(el) {
                var input;
                docElem.appendChild(el).innerHTML = "<a id='" + expando + "'></a><select id='" + expando + "-\r\\' msallowcapture=''><option selected=''></option></select>";
                if (el.querySelectorAll("[msallowcapture^='']").length) {
                  rbuggyQSA.push("[*^$]=" + whitespace + `*(?:''|"")`);
                }
                if (!el.querySelectorAll("[selected]").length) {
                  rbuggyQSA.push("\\[" + whitespace + "*(?:value|" + booleans + ")");
                }
                if (!el.querySelectorAll("[id~=" + expando + "-]").length) {
                  rbuggyQSA.push("~=");
                }
                input = document3.createElement("input");
                input.setAttribute("name", "");
                el.appendChild(input);
                if (!el.querySelectorAll("[name='']").length) {
                  rbuggyQSA.push("\\[" + whitespace + "*name" + whitespace + "*=" + whitespace + `*(?:''|"")`);
                }
                if (!el.querySelectorAll(":checked").length) {
                  rbuggyQSA.push(":checked");
                }
                if (!el.querySelectorAll("a#" + expando + "+*").length) {
                  rbuggyQSA.push(".#.+[+~]");
                }
                el.querySelectorAll("\\\f");
                rbuggyQSA.push("[\\r\\n\\f]");
              });
              assert(function(el) {
                el.innerHTML = "<a href='' disabled='disabled'></a><select disabled='disabled'><option/></select>";
                var input = document3.createElement("input");
                input.setAttribute("type", "hidden");
                el.appendChild(input).setAttribute("name", "D");
                if (el.querySelectorAll("[name=d]").length) {
                  rbuggyQSA.push("name" + whitespace + "*[*^$|!~]?=");
                }
                if (el.querySelectorAll(":enabled").length !== 2) {
                  rbuggyQSA.push(":enabled", ":disabled");
                }
                docElem.appendChild(el).disabled = true;
                if (el.querySelectorAll(":disabled").length !== 2) {
                  rbuggyQSA.push(":enabled", ":disabled");
                }
                el.querySelectorAll("*,:x");
                rbuggyQSA.push(",.*:");
              });
            }
            if (support2.matchesSelector = rnative.test(matches = docElem.matches || docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector)) {
              assert(function(el) {
                support2.disconnectedMatch = matches.call(el, "*");
                matches.call(el, "[s!='']:x");
                rbuggyMatches.push("!=", pseudos);
              });
            }
            rbuggyQSA = rbuggyQSA.length && new RegExp(rbuggyQSA.join("|"));
            rbuggyMatches = rbuggyMatches.length && new RegExp(rbuggyMatches.join("|"));
            hasCompare = rnative.test(docElem.compareDocumentPosition);
            contains2 = hasCompare || rnative.test(docElem.contains) ? function(a2, b2) {
              var adown = a2.nodeType === 9 ? a2.documentElement : a2, bup = b2 && b2.parentNode;
              return a2 === bup || !!(bup && bup.nodeType === 1 && (adown.contains ? adown.contains(bup) : a2.compareDocumentPosition && a2.compareDocumentPosition(bup) & 16));
            } : function(a2, b2) {
              if (b2) {
                while (b2 = b2.parentNode) {
                  if (b2 === a2) {
                    return true;
                  }
                }
              }
              return false;
            };
            sortOrder = hasCompare ? function(a2, b2) {
              if (a2 === b2) {
                hasDuplicate = true;
                return 0;
              }
              var compare = !a2.compareDocumentPosition - !b2.compareDocumentPosition;
              if (compare) {
                return compare;
              }
              compare = (a2.ownerDocument || a2) == (b2.ownerDocument || b2) ? a2.compareDocumentPosition(b2) : 1;
              if (compare & 1 || !support2.sortDetached && b2.compareDocumentPosition(a2) === compare) {
                if (a2 == document3 || a2.ownerDocument == preferredDoc && contains2(preferredDoc, a2)) {
                  return -1;
                }
                if (b2 == document3 || b2.ownerDocument == preferredDoc && contains2(preferredDoc, b2)) {
                  return 1;
                }
                return sortInput ? indexOf3(sortInput, a2) - indexOf3(sortInput, b2) : 0;
              }
              return compare & 4 ? -1 : 1;
            } : function(a2, b2) {
              if (a2 === b2) {
                hasDuplicate = true;
                return 0;
              }
              var cur, i3 = 0, aup = a2.parentNode, bup = b2.parentNode, ap = [a2], bp = [b2];
              if (!aup || !bup) {
                return a2 == document3 ? -1 : b2 == document3 ? 1 : aup ? -1 : bup ? 1 : sortInput ? indexOf3(sortInput, a2) - indexOf3(sortInput, b2) : 0;
              } else if (aup === bup) {
                return siblingCheck(a2, b2);
              }
              cur = a2;
              while (cur = cur.parentNode) {
                ap.unshift(cur);
              }
              cur = b2;
              while (cur = cur.parentNode) {
                bp.unshift(cur);
              }
              while (ap[i3] === bp[i3]) {
                i3++;
              }
              return i3 ? siblingCheck(ap[i3], bp[i3]) : ap[i3] == preferredDoc ? -1 : bp[i3] == preferredDoc ? 1 : 0;
            };
            return document3;
          };
          Sizzle2.matches = function(expr, elements2) {
            return Sizzle2(expr, null, null, elements2);
          };
          Sizzle2.matchesSelector = function(elem, expr) {
            setDocument(elem);
            if (support2.matchesSelector && documentIsHTML && !nonnativeSelectorCache[expr + " "] && (!rbuggyMatches || !rbuggyMatches.test(expr)) && (!rbuggyQSA || !rbuggyQSA.test(expr))) {
              try {
                var ret = matches.call(elem, expr);
                if (ret || support2.disconnectedMatch || elem.document && elem.document.nodeType !== 11) {
                  return ret;
                }
              } catch (e2) {
                nonnativeSelectorCache(expr, true);
              }
            }
            return Sizzle2(expr, document3, null, [elem]).length > 0;
          };
          Sizzle2.contains = function(context, elem) {
            if ((context.ownerDocument || context) != document3) {
              setDocument(context);
            }
            return contains2(context, elem);
          };
          Sizzle2.attr = function(elem, name) {
            if ((elem.ownerDocument || elem) != document3) {
              setDocument(elem);
            }
            var fn3 = Expr.attrHandle[name.toLowerCase()], val = fn3 && hasOwn2.call(Expr.attrHandle, name.toLowerCase()) ? fn3(elem, name, !documentIsHTML) : void 0;
            return val !== void 0 ? val : support2.attributes || !documentIsHTML ? elem.getAttribute(name) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null;
          };
          Sizzle2.escape = function(sel) {
            return (sel + "").replace(rcssescape, fcssescape);
          };
          Sizzle2.error = function(msg) {
            throw new Error("Syntax error, unrecognized expression: " + msg);
          };
          Sizzle2.uniqueSort = function(results) {
            var elem, duplicates = [], j2 = 0, i3 = 0;
            hasDuplicate = !support2.detectDuplicates;
            sortInput = !support2.sortStable && results.slice(0);
            results.sort(sortOrder);
            if (hasDuplicate) {
              while (elem = results[i3++]) {
                if (elem === results[i3]) {
                  j2 = duplicates.push(i3);
                }
              }
              while (j2--) {
                results.splice(duplicates[j2], 1);
              }
            }
            sortInput = null;
            return results;
          };
          getText = Sizzle2.getText = function(elem) {
            var node, ret = "", i3 = 0, nodeType = elem.nodeType;
            if (!nodeType) {
              while (node = elem[i3++]) {
                ret += getText(node);
              }
            } else if (nodeType === 1 || nodeType === 9 || nodeType === 11) {
              if (typeof elem.textContent === "string") {
                return elem.textContent;
              } else {
                for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
                  ret += getText(elem);
                }
              }
            } else if (nodeType === 3 || nodeType === 4) {
              return elem.nodeValue;
            }
            return ret;
          };
          Expr = Sizzle2.selectors = {
            cacheLength: 50,
            createPseudo: markFunction,
            match: matchExpr,
            attrHandle: {},
            find: {},
            relative: {
              ">": { dir: "parentNode", first: true },
              " ": { dir: "parentNode" },
              "+": { dir: "previousSibling", first: true },
              "~": { dir: "previousSibling" }
            },
            preFilter: {
              "ATTR": function(match2) {
                match2[1] = match2[1].replace(runescape, funescape);
                match2[3] = (match2[3] || match2[4] || match2[5] || "").replace(runescape, funescape);
                if (match2[2] === "~=") {
                  match2[3] = " " + match2[3] + " ";
                }
                return match2.slice(0, 4);
              },
              "CHILD": function(match2) {
                match2[1] = match2[1].toLowerCase();
                if (match2[1].slice(0, 3) === "nth") {
                  if (!match2[3]) {
                    Sizzle2.error(match2[0]);
                  }
                  match2[4] = +(match2[4] ? match2[5] + (match2[6] || 1) : 2 * (match2[3] === "even" || match2[3] === "odd"));
                  match2[5] = +(match2[7] + match2[8] || match2[3] === "odd");
                } else if (match2[3]) {
                  Sizzle2.error(match2[0]);
                }
                return match2;
              },
              "PSEUDO": function(match2) {
                var excess, unquoted = !match2[6] && match2[2];
                if (matchExpr["CHILD"].test(match2[0])) {
                  return null;
                }
                if (match2[3]) {
                  match2[2] = match2[4] || match2[5] || "";
                } else if (unquoted && rpseudo.test(unquoted) && (excess = tokenize2(unquoted, true)) && (excess = unquoted.indexOf(")", unquoted.length - excess) - unquoted.length)) {
                  match2[0] = match2[0].slice(0, excess);
                  match2[2] = unquoted.slice(0, excess);
                }
                return match2.slice(0, 3);
              }
            },
            filter: {
              "TAG": function(nodeNameSelector) {
                var nodeName2 = nodeNameSelector.replace(runescape, funescape).toLowerCase();
                return nodeNameSelector === "*" ? function() {
                  return true;
                } : function(elem) {
                  return elem.nodeName && elem.nodeName.toLowerCase() === nodeName2;
                };
              },
              "CLASS": function(className) {
                var pattern = classCache[className + " "];
                return pattern || (pattern = new RegExp("(^|" + whitespace + ")" + className + "(" + whitespace + "|$)")) && classCache(className, function(elem) {
                  return pattern.test(typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "");
                });
              },
              "ATTR": function(name, operator, check) {
                return function(elem) {
                  var result = Sizzle2.attr(elem, name);
                  if (result == null) {
                    return operator === "!=";
                  }
                  if (!operator) {
                    return true;
                  }
                  result += "";
                  return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf(check) === 0 : operator === "*=" ? check && result.indexOf(check) > -1 : operator === "$=" ? check && result.slice(-check.length) === check : operator === "~=" ? (" " + result.replace(rwhitespace, " ") + " ").indexOf(check) > -1 : operator === "|=" ? result === check || result.slice(0, check.length + 1) === check + "-" : false;
                };
              },
              "CHILD": function(type, what, _argument, first, last) {
                var simple = type.slice(0, 3) !== "nth", forward = type.slice(-4) !== "last", ofType = what === "of-type";
                return first === 1 && last === 0 ? function(elem) {
                  return !!elem.parentNode;
                } : function(elem, _context, xml) {
                  var cache2, uniqueCache, outerCache, node, nodeIndex, start4, dir2 = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType, diff = false;
                  if (parent) {
                    if (simple) {
                      while (dir2) {
                        node = elem;
                        while (node = node[dir2]) {
                          if (ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1) {
                            return false;
                          }
                        }
                        start4 = dir2 = type === "only" && !start4 && "nextSibling";
                      }
                      return true;
                    }
                    start4 = [forward ? parent.firstChild : parent.lastChild];
                    if (forward && useCache) {
                      node = parent;
                      outerCache = node[expando] || (node[expando] = {});
                      uniqueCache = outerCache[node.uniqueID] || (outerCache[node.uniqueID] = {});
                      cache2 = uniqueCache[type] || [];
                      nodeIndex = cache2[0] === dirruns && cache2[1];
                      diff = nodeIndex && cache2[2];
                      node = nodeIndex && parent.childNodes[nodeIndex];
                      while (node = ++nodeIndex && node && node[dir2] || (diff = nodeIndex = 0) || start4.pop()) {
                        if (node.nodeType === 1 && ++diff && node === elem) {
                          uniqueCache[type] = [dirruns, nodeIndex, diff];
                          break;
                        }
                      }
                    } else {
                      if (useCache) {
                        node = elem;
                        outerCache = node[expando] || (node[expando] = {});
                        uniqueCache = outerCache[node.uniqueID] || (outerCache[node.uniqueID] = {});
                        cache2 = uniqueCache[type] || [];
                        nodeIndex = cache2[0] === dirruns && cache2[1];
                        diff = nodeIndex;
                      }
                      if (diff === false) {
                        while (node = ++nodeIndex && node && node[dir2] || (diff = nodeIndex = 0) || start4.pop()) {
                          if ((ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1) && ++diff) {
                            if (useCache) {
                              outerCache = node[expando] || (node[expando] = {});
                              uniqueCache = outerCache[node.uniqueID] || (outerCache[node.uniqueID] = {});
                              uniqueCache[type] = [dirruns, diff];
                            }
                            if (node === elem) {
                              break;
                            }
                          }
                        }
                      }
                    }
                    diff -= last;
                    return diff === first || diff % first === 0 && diff / first >= 0;
                  }
                };
              },
              "PSEUDO": function(pseudo, argument) {
                var args, fn3 = Expr.pseudos[pseudo] || Expr.setFilters[pseudo.toLowerCase()] || Sizzle2.error("unsupported pseudo: " + pseudo);
                if (fn3[expando]) {
                  return fn3(argument);
                }
                if (fn3.length > 1) {
                  args = [pseudo, pseudo, "", argument];
                  return Expr.setFilters.hasOwnProperty(pseudo.toLowerCase()) ? markFunction(function(seed, matches2) {
                    var idx, matched = fn3(seed, argument), i3 = matched.length;
                    while (i3--) {
                      idx = indexOf3(seed, matched[i3]);
                      seed[idx] = !(matches2[idx] = matched[i3]);
                    }
                  }) : function(elem) {
                    return fn3(elem, 0, args);
                  };
                }
                return fn3;
              }
            },
            pseudos: {
              "not": markFunction(function(selector) {
                var input = [], results = [], matcher = compile(selector.replace(rtrim2, "$1"));
                return matcher[expando] ? markFunction(function(seed, matches2, _context, xml) {
                  var elem, unmatched = matcher(seed, null, xml, []), i3 = seed.length;
                  while (i3--) {
                    if (elem = unmatched[i3]) {
                      seed[i3] = !(matches2[i3] = elem);
                    }
                  }
                }) : function(elem, _context, xml) {
                  input[0] = elem;
                  matcher(input, null, xml, results);
                  input[0] = null;
                  return !results.pop();
                };
              }),
              "has": markFunction(function(selector) {
                return function(elem) {
                  return Sizzle2(selector, elem).length > 0;
                };
              }),
              "contains": markFunction(function(text) {
                text = text.replace(runescape, funescape);
                return function(elem) {
                  return (elem.textContent || getText(elem)).indexOf(text) > -1;
                };
              }),
              "lang": markFunction(function(lang) {
                if (!ridentifier.test(lang || "")) {
                  Sizzle2.error("unsupported lang: " + lang);
                }
                lang = lang.replace(runescape, funescape).toLowerCase();
                return function(elem) {
                  var elemLang;
                  do {
                    if (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) {
                      elemLang = elemLang.toLowerCase();
                      return elemLang === lang || elemLang.indexOf(lang + "-") === 0;
                    }
                  } while ((elem = elem.parentNode) && elem.nodeType === 1);
                  return false;
                };
              }),
              "target": function(elem) {
                var hash3 = window3.location && window3.location.hash;
                return hash3 && hash3.slice(1) === elem.id;
              },
              "root": function(elem) {
                return elem === docElem;
              },
              "focus": function(elem) {
                return elem === document3.activeElement && (!document3.hasFocus || document3.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
              },
              "enabled": createDisabledPseudo(false),
              "disabled": createDisabledPseudo(true),
              "checked": function(elem) {
                var nodeName2 = elem.nodeName.toLowerCase();
                return nodeName2 === "input" && !!elem.checked || nodeName2 === "option" && !!elem.selected;
              },
              "selected": function(elem) {
                if (elem.parentNode) {
                  elem.parentNode.selectedIndex;
                }
                return elem.selected === true;
              },
              "empty": function(elem) {
                for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
                  if (elem.nodeType < 6) {
                    return false;
                  }
                }
                return true;
              },
              "parent": function(elem) {
                return !Expr.pseudos["empty"](elem);
              },
              "header": function(elem) {
                return rheader.test(elem.nodeName);
              },
              "input": function(elem) {
                return rinputs.test(elem.nodeName);
              },
              "button": function(elem) {
                var name = elem.nodeName.toLowerCase();
                return name === "input" && elem.type === "button" || name === "button";
              },
              "text": function(elem) {
                var attr;
                return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && ((attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text");
              },
              "first": createPositionalPseudo(function() {
                return [0];
              }),
              "last": createPositionalPseudo(function(_matchIndexes, length) {
                return [length - 1];
              }),
              "eq": createPositionalPseudo(function(_matchIndexes, length, argument) {
                return [argument < 0 ? argument + length : argument];
              }),
              "even": createPositionalPseudo(function(matchIndexes, length) {
                var i3 = 0;
                for (; i3 < length; i3 += 2) {
                  matchIndexes.push(i3);
                }
                return matchIndexes;
              }),
              "odd": createPositionalPseudo(function(matchIndexes, length) {
                var i3 = 1;
                for (; i3 < length; i3 += 2) {
                  matchIndexes.push(i3);
                }
                return matchIndexes;
              }),
              "lt": createPositionalPseudo(function(matchIndexes, length, argument) {
                var i3 = argument < 0 ? argument + length : argument > length ? length : argument;
                for (; --i3 >= 0; ) {
                  matchIndexes.push(i3);
                }
                return matchIndexes;
              }),
              "gt": createPositionalPseudo(function(matchIndexes, length, argument) {
                var i3 = argument < 0 ? argument + length : argument;
                for (; ++i3 < length; ) {
                  matchIndexes.push(i3);
                }
                return matchIndexes;
              })
            }
          };
          Expr.pseudos["nth"] = Expr.pseudos["eq"];
          for (i2 in { radio: true, checkbox: true, file: true, password: true, image: true }) {
            Expr.pseudos[i2] = createInputPseudo(i2);
          }
          for (i2 in { submit: true, reset: true }) {
            Expr.pseudos[i2] = createButtonPseudo(i2);
          }
          function setFilters() {
          }
          setFilters.prototype = Expr.filters = Expr.pseudos;
          Expr.setFilters = new setFilters();
          tokenize2 = Sizzle2.tokenize = function(selector, parseOnly) {
            var matched, match2, tokens, type, soFar, groups, preFilters, cached = tokenCache[selector + " "];
            if (cached) {
              return parseOnly ? 0 : cached.slice(0);
            }
            soFar = selector;
            groups = [];
            preFilters = Expr.preFilter;
            while (soFar) {
              if (!matched || (match2 = rcomma.exec(soFar))) {
                if (match2) {
                  soFar = soFar.slice(match2[0].length) || soFar;
                }
                groups.push(tokens = []);
              }
              matched = false;
              if (match2 = rcombinators.exec(soFar)) {
                matched = match2.shift();
                tokens.push({
                  value: matched,
                  type: match2[0].replace(rtrim2, " ")
                });
                soFar = soFar.slice(matched.length);
              }
              for (type in Expr.filter) {
                if ((match2 = matchExpr[type].exec(soFar)) && (!preFilters[type] || (match2 = preFilters[type](match2)))) {
                  matched = match2.shift();
                  tokens.push({
                    value: matched,
                    type,
                    matches: match2
                  });
                  soFar = soFar.slice(matched.length);
                }
              }
              if (!matched) {
                break;
              }
            }
            return parseOnly ? soFar.length : soFar ? Sizzle2.error(selector) : tokenCache(selector, groups).slice(0);
          };
          function toSelector(tokens) {
            var i3 = 0, len = tokens.length, selector = "";
            for (; i3 < len; i3++) {
              selector += tokens[i3].value;
            }
            return selector;
          }
          function addCombinator(matcher, combinator, base) {
            var dir2 = combinator.dir, skip2 = combinator.next, key = skip2 || dir2, checkNonElements = base && key === "parentNode", doneName = done++;
            return combinator.first ? function(elem, context, xml) {
              while (elem = elem[dir2]) {
                if (elem.nodeType === 1 || checkNonElements) {
                  return matcher(elem, context, xml);
                }
              }
              return false;
            } : function(elem, context, xml) {
              var oldCache, uniqueCache, outerCache, newCache = [dirruns, doneName];
              if (xml) {
                while (elem = elem[dir2]) {
                  if (elem.nodeType === 1 || checkNonElements) {
                    if (matcher(elem, context, xml)) {
                      return true;
                    }
                  }
                }
              } else {
                while (elem = elem[dir2]) {
                  if (elem.nodeType === 1 || checkNonElements) {
                    outerCache = elem[expando] || (elem[expando] = {});
                    uniqueCache = outerCache[elem.uniqueID] || (outerCache[elem.uniqueID] = {});
                    if (skip2 && skip2 === elem.nodeName.toLowerCase()) {
                      elem = elem[dir2] || elem;
                    } else if ((oldCache = uniqueCache[key]) && oldCache[0] === dirruns && oldCache[1] === doneName) {
                      return newCache[2] = oldCache[2];
                    } else {
                      uniqueCache[key] = newCache;
                      if (newCache[2] = matcher(elem, context, xml)) {
                        return true;
                      }
                    }
                  }
                }
              }
              return false;
            };
          }
          function elementMatcher(matchers) {
            return matchers.length > 1 ? function(elem, context, xml) {
              var i3 = matchers.length;
              while (i3--) {
                if (!matchers[i3](elem, context, xml)) {
                  return false;
                }
              }
              return true;
            } : matchers[0];
          }
          function multipleContexts(selector, contexts, results) {
            var i3 = 0, len = contexts.length;
            for (; i3 < len; i3++) {
              Sizzle2(selector, contexts[i3], results);
            }
            return results;
          }
          function condense(unmatched, map3, filter, context, xml) {
            var elem, newUnmatched = [], i3 = 0, len = unmatched.length, mapped = map3 != null;
            for (; i3 < len; i3++) {
              if (elem = unmatched[i3]) {
                if (!filter || filter(elem, context, xml)) {
                  newUnmatched.push(elem);
                  if (mapped) {
                    map3.push(i3);
                  }
                }
              }
            }
            return newUnmatched;
          }
          function setMatcher(preFilter, selector, matcher, postFilter, postFinder, postSelector) {
            if (postFilter && !postFilter[expando]) {
              postFilter = setMatcher(postFilter);
            }
            if (postFinder && !postFinder[expando]) {
              postFinder = setMatcher(postFinder, postSelector);
            }
            return markFunction(function(seed, results, context, xml) {
              var temp, i3, elem, preMap = [], postMap = [], preexisting = results.length, elems = seed || multipleContexts(selector || "*", context.nodeType ? [context] : context, []), matcherIn = preFilter && (seed || !selector) ? condense(elems, preMap, preFilter, context, xml) : elems, matcherOut = matcher ? postFinder || (seed ? preFilter : preexisting || postFilter) ? [] : results : matcherIn;
              if (matcher) {
                matcher(matcherIn, matcherOut, context, xml);
              }
              if (postFilter) {
                temp = condense(matcherOut, postMap);
                postFilter(temp, [], context, xml);
                i3 = temp.length;
                while (i3--) {
                  if (elem = temp[i3]) {
                    matcherOut[postMap[i3]] = !(matcherIn[postMap[i3]] = elem);
                  }
                }
              }
              if (seed) {
                if (postFinder || preFilter) {
                  if (postFinder) {
                    temp = [];
                    i3 = matcherOut.length;
                    while (i3--) {
                      if (elem = matcherOut[i3]) {
                        temp.push(matcherIn[i3] = elem);
                      }
                    }
                    postFinder(null, matcherOut = [], temp, xml);
                  }
                  i3 = matcherOut.length;
                  while (i3--) {
                    if ((elem = matcherOut[i3]) && (temp = postFinder ? indexOf3(seed, elem) : preMap[i3]) > -1) {
                      seed[temp] = !(results[temp] = elem);
                    }
                  }
                }
              } else {
                matcherOut = condense(matcherOut === results ? matcherOut.splice(preexisting, matcherOut.length) : matcherOut);
                if (postFinder) {
                  postFinder(null, results, matcherOut, xml);
                } else {
                  push2.apply(results, matcherOut);
                }
              }
            });
          }
          function matcherFromTokens(tokens) {
            var checkContext, matcher, j2, len = tokens.length, leadingRelative = Expr.relative[tokens[0].type], implicitRelative = leadingRelative || Expr.relative[" "], i3 = leadingRelative ? 1 : 0, matchContext = addCombinator(function(elem) {
              return elem === checkContext;
            }, implicitRelative, true), matchAnyContext = addCombinator(function(elem) {
              return indexOf3(checkContext, elem) > -1;
            }, implicitRelative, true), matchers = [function(elem, context, xml) {
              var ret = !leadingRelative && (xml || context !== outermostContext) || ((checkContext = context).nodeType ? matchContext(elem, context, xml) : matchAnyContext(elem, context, xml));
              checkContext = null;
              return ret;
            }];
            for (; i3 < len; i3++) {
              if (matcher = Expr.relative[tokens[i3].type]) {
                matchers = [addCombinator(elementMatcher(matchers), matcher)];
              } else {
                matcher = Expr.filter[tokens[i3].type].apply(null, tokens[i3].matches);
                if (matcher[expando]) {
                  j2 = ++i3;
                  for (; j2 < len; j2++) {
                    if (Expr.relative[tokens[j2].type]) {
                      break;
                    }
                  }
                  return setMatcher(i3 > 1 && elementMatcher(matchers), i3 > 1 && toSelector(tokens.slice(0, i3 - 1).concat({ value: tokens[i3 - 2].type === " " ? "*" : "" })).replace(rtrim2, "$1"), matcher, i3 < j2 && matcherFromTokens(tokens.slice(i3, j2)), j2 < len && matcherFromTokens(tokens = tokens.slice(j2)), j2 < len && toSelector(tokens));
                }
                matchers.push(matcher);
              }
            }
            return elementMatcher(matchers);
          }
          function matcherFromGroupMatchers(elementMatchers, setMatchers) {
            var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function(seed, context, xml, results, outermost) {
              var elem, j2, matcher, matchedCount = 0, i3 = "0", unmatched = seed && [], setMatched = [], contextBackup = outermostContext, elems = seed || byElement && Expr.find["TAG"]("*", outermost), dirrunsUnique = dirruns += contextBackup == null ? 1 : Math.random() || 0.1, len = elems.length;
              if (outermost) {
                outermostContext = context == document3 || context || outermost;
              }
              for (; i3 !== len && (elem = elems[i3]) != null; i3++) {
                if (byElement && elem) {
                  j2 = 0;
                  if (!context && elem.ownerDocument != document3) {
                    setDocument(elem);
                    xml = !documentIsHTML;
                  }
                  while (matcher = elementMatchers[j2++]) {
                    if (matcher(elem, context || document3, xml)) {
                      results.push(elem);
                      break;
                    }
                  }
                  if (outermost) {
                    dirruns = dirrunsUnique;
                  }
                }
                if (bySet) {
                  if (elem = !matcher && elem) {
                    matchedCount--;
                  }
                  if (seed) {
                    unmatched.push(elem);
                  }
                }
              }
              matchedCount += i3;
              if (bySet && i3 !== matchedCount) {
                j2 = 0;
                while (matcher = setMatchers[j2++]) {
                  matcher(unmatched, setMatched, context, xml);
                }
                if (seed) {
                  if (matchedCount > 0) {
                    while (i3--) {
                      if (!(unmatched[i3] || setMatched[i3])) {
                        setMatched[i3] = pop.call(results);
                      }
                    }
                  }
                  setMatched = condense(setMatched);
                }
                push2.apply(results, setMatched);
                if (outermost && !seed && setMatched.length > 0 && matchedCount + setMatchers.length > 1) {
                  Sizzle2.uniqueSort(results);
                }
              }
              if (outermost) {
                dirruns = dirrunsUnique;
                outermostContext = contextBackup;
              }
              return unmatched;
            };
            return bySet ? markFunction(superMatcher) : superMatcher;
          }
          compile = Sizzle2.compile = function(selector, match2) {
            var i3, setMatchers = [], elementMatchers = [], cached = compilerCache[selector + " "];
            if (!cached) {
              if (!match2) {
                match2 = tokenize2(selector);
              }
              i3 = match2.length;
              while (i3--) {
                cached = matcherFromTokens(match2[i3]);
                if (cached[expando]) {
                  setMatchers.push(cached);
                } else {
                  elementMatchers.push(cached);
                }
              }
              cached = compilerCache(selector, matcherFromGroupMatchers(elementMatchers, setMatchers));
              cached.selector = selector;
            }
            return cached;
          };
          select = Sizzle2.select = function(selector, context, results, seed) {
            var i3, tokens, token, type, find, compiled = typeof selector === "function" && selector, match2 = !seed && tokenize2(selector = compiled.selector || selector);
            results = results || [];
            if (match2.length === 1) {
              tokens = match2[0] = match2[0].slice(0);
              if (tokens.length > 2 && (token = tokens[0]).type === "ID" && context.nodeType === 9 && documentIsHTML && Expr.relative[tokens[1].type]) {
                context = (Expr.find["ID"](token.matches[0].replace(runescape, funescape), context) || [])[0];
                if (!context) {
                  return results;
                } else if (compiled) {
                  context = context.parentNode;
                }
                selector = selector.slice(tokens.shift().value.length);
              }
              i3 = matchExpr["needsContext"].test(selector) ? 0 : tokens.length;
              while (i3--) {
                token = tokens[i3];
                if (Expr.relative[type = token.type]) {
                  break;
                }
                if (find = Expr.find[type]) {
                  if (seed = find(token.matches[0].replace(runescape, funescape), rsibling.test(tokens[0].type) && testContext(context.parentNode) || context)) {
                    tokens.splice(i3, 1);
                    selector = seed.length && toSelector(tokens);
                    if (!selector) {
                      push2.apply(results, seed);
                      return results;
                    }
                    break;
                  }
                }
              }
            }
            (compiled || compile(selector, match2))(seed, context, !documentIsHTML, results, !context || rsibling.test(selector) && testContext(context.parentNode) || context);
            return results;
          };
          support2.sortStable = expando.split("").sort(sortOrder).join("") === expando;
          support2.detectDuplicates = !!hasDuplicate;
          setDocument();
          support2.sortDetached = assert(function(el) {
            return el.compareDocumentPosition(document3.createElement("fieldset")) & 1;
          });
          if (!assert(function(el) {
            el.innerHTML = "<a href='#'></a>";
            return el.firstChild.getAttribute("href") === "#";
          })) {
            addHandle("type|href|height|width", function(elem, name, isXML2) {
              if (!isXML2) {
                return elem.getAttribute(name, name.toLowerCase() === "type" ? 1 : 2);
              }
            });
          }
          if (!support2.attributes || !assert(function(el) {
            el.innerHTML = "<input/>";
            el.firstChild.setAttribute("value", "");
            return el.firstChild.getAttribute("value") === "";
          })) {
            addHandle("value", function(elem, _name, isXML2) {
              if (!isXML2 && elem.nodeName.toLowerCase() === "input") {
                return elem.defaultValue;
              }
            });
          }
          if (!assert(function(el) {
            return el.getAttribute("disabled") == null;
          })) {
            addHandle(booleans, function(elem, name, isXML2) {
              var val;
              if (!isXML2) {
                return elem[name] === true ? name.toLowerCase() : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null;
              }
            });
          }
          return Sizzle2;
        }(window2);
        jQuery2.find = Sizzle;
        jQuery2.expr = Sizzle.selectors;
        jQuery2.expr[":"] = jQuery2.expr.pseudos;
        jQuery2.uniqueSort = jQuery2.unique = Sizzle.uniqueSort;
        jQuery2.text = Sizzle.getText;
        jQuery2.isXMLDoc = Sizzle.isXML;
        jQuery2.contains = Sizzle.contains;
        jQuery2.escapeSelector = Sizzle.escape;
        var dir = function(elem, dir2, until) {
          var matched = [], truncate = until !== void 0;
          while ((elem = elem[dir2]) && elem.nodeType !== 9) {
            if (elem.nodeType === 1) {
              if (truncate && jQuery2(elem).is(until)) {
                break;
              }
              matched.push(elem);
            }
          }
          return matched;
        };
        var siblings = function(n2, elem) {
          var matched = [];
          for (; n2; n2 = n2.nextSibling) {
            if (n2.nodeType === 1 && n2 !== elem) {
              matched.push(n2);
            }
          }
          return matched;
        };
        var rneedsContext = jQuery2.expr.match.needsContext;
        function nodeName(elem, name) {
          return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
        }
        var rsingleTag = /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;
        function winnow(elements2, qualifier, not) {
          if (isFunction2(qualifier)) {
            return jQuery2.grep(elements2, function(elem, i2) {
              return !!qualifier.call(elem, i2, elem) !== not;
            });
          }
          if (qualifier.nodeType) {
            return jQuery2.grep(elements2, function(elem) {
              return elem === qualifier !== not;
            });
          }
          if (typeof qualifier !== "string") {
            return jQuery2.grep(elements2, function(elem) {
              return indexOf2.call(qualifier, elem) > -1 !== not;
            });
          }
          return jQuery2.filter(qualifier, elements2, not);
        }
        jQuery2.filter = function(expr, elems, not) {
          var elem = elems[0];
          if (not) {
            expr = ":not(" + expr + ")";
          }
          if (elems.length === 1 && elem.nodeType === 1) {
            return jQuery2.find.matchesSelector(elem, expr) ? [elem] : [];
          }
          return jQuery2.find.matches(expr, jQuery2.grep(elems, function(elem2) {
            return elem2.nodeType === 1;
          }));
        };
        jQuery2.fn.extend({
          find: function(selector) {
            var i2, ret, len = this.length, self2 = this;
            if (typeof selector !== "string") {
              return this.pushStack(jQuery2(selector).filter(function() {
                for (i2 = 0; i2 < len; i2++) {
                  if (jQuery2.contains(self2[i2], this)) {
                    return true;
                  }
                }
              }));
            }
            ret = this.pushStack([]);
            for (i2 = 0; i2 < len; i2++) {
              jQuery2.find(selector, self2[i2], ret);
            }
            return len > 1 ? jQuery2.uniqueSort(ret) : ret;
          },
          filter: function(selector) {
            return this.pushStack(winnow(this, selector || [], false));
          },
          not: function(selector) {
            return this.pushStack(winnow(this, selector || [], true));
          },
          is: function(selector) {
            return !!winnow(this, typeof selector === "string" && rneedsContext.test(selector) ? jQuery2(selector) : selector || [], false).length;
          }
        });
        var rootjQuery, rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/, init = jQuery2.fn.init = function(selector, context, root) {
          var match2, elem;
          if (!selector) {
            return this;
          }
          root = root || rootjQuery;
          if (typeof selector === "string") {
            if (selector[0] === "<" && selector[selector.length - 1] === ">" && selector.length >= 3) {
              match2 = [null, selector, null];
            } else {
              match2 = rquickExpr.exec(selector);
            }
            if (match2 && (match2[1] || !context)) {
              if (match2[1]) {
                context = context instanceof jQuery2 ? context[0] : context;
                jQuery2.merge(this, jQuery2.parseHTML(match2[1], context && context.nodeType ? context.ownerDocument || context : document2, true));
                if (rsingleTag.test(match2[1]) && jQuery2.isPlainObject(context)) {
                  for (match2 in context) {
                    if (isFunction2(this[match2])) {
                      this[match2](context[match2]);
                    } else {
                      this.attr(match2, context[match2]);
                    }
                  }
                }
                return this;
              } else {
                elem = document2.getElementById(match2[2]);
                if (elem) {
                  this[0] = elem;
                  this.length = 1;
                }
                return this;
              }
            } else if (!context || context.jquery) {
              return (context || root).find(selector);
            } else {
              return this.constructor(context).find(selector);
            }
          } else if (selector.nodeType) {
            this[0] = selector;
            this.length = 1;
            return this;
          } else if (isFunction2(selector)) {
            return root.ready !== void 0 ? root.ready(selector) : selector(jQuery2);
          }
          return jQuery2.makeArray(selector, this);
        };
        init.prototype = jQuery2.fn;
        rootjQuery = jQuery2(document2);
        var rparentsprev = /^(?:parents|prev(?:Until|All))/, guaranteedUnique = {
          children: true,
          contents: true,
          next: true,
          prev: true
        };
        jQuery2.fn.extend({
          has: function(target) {
            var targets = jQuery2(target, this), l2 = targets.length;
            return this.filter(function() {
              var i2 = 0;
              for (; i2 < l2; i2++) {
                if (jQuery2.contains(this, targets[i2])) {
                  return true;
                }
              }
            });
          },
          closest: function(selectors, context) {
            var cur, i2 = 0, l2 = this.length, matched = [], targets = typeof selectors !== "string" && jQuery2(selectors);
            if (!rneedsContext.test(selectors)) {
              for (; i2 < l2; i2++) {
                for (cur = this[i2]; cur && cur !== context; cur = cur.parentNode) {
                  if (cur.nodeType < 11 && (targets ? targets.index(cur) > -1 : cur.nodeType === 1 && jQuery2.find.matchesSelector(cur, selectors))) {
                    matched.push(cur);
                    break;
                  }
                }
              }
            }
            return this.pushStack(matched.length > 1 ? jQuery2.uniqueSort(matched) : matched);
          },
          index: function(elem) {
            if (!elem) {
              return this[0] && this[0].parentNode ? this.first().prevAll().length : -1;
            }
            if (typeof elem === "string") {
              return indexOf2.call(jQuery2(elem), this[0]);
            }
            return indexOf2.call(this, elem.jquery ? elem[0] : elem);
          },
          add: function(selector, context) {
            return this.pushStack(jQuery2.uniqueSort(jQuery2.merge(this.get(), jQuery2(selector, context))));
          },
          addBack: function(selector) {
            return this.add(selector == null ? this.prevObject : this.prevObject.filter(selector));
          }
        });
        function sibling(cur, dir2) {
          while ((cur = cur[dir2]) && cur.nodeType !== 1) {
          }
          return cur;
        }
        jQuery2.each({
          parent: function(elem) {
            var parent = elem.parentNode;
            return parent && parent.nodeType !== 11 ? parent : null;
          },
          parents: function(elem) {
            return dir(elem, "parentNode");
          },
          parentsUntil: function(elem, _i2, until) {
            return dir(elem, "parentNode", until);
          },
          next: function(elem) {
            return sibling(elem, "nextSibling");
          },
          prev: function(elem) {
            return sibling(elem, "previousSibling");
          },
          nextAll: function(elem) {
            return dir(elem, "nextSibling");
          },
          prevAll: function(elem) {
            return dir(elem, "previousSibling");
          },
          nextUntil: function(elem, _i2, until) {
            return dir(elem, "nextSibling", until);
          },
          prevUntil: function(elem, _i2, until) {
            return dir(elem, "previousSibling", until);
          },
          siblings: function(elem) {
            return siblings((elem.parentNode || {}).firstChild, elem);
          },
          children: function(elem) {
            return siblings(elem.firstChild);
          },
          contents: function(elem) {
            if (elem.contentDocument != null && getProto(elem.contentDocument)) {
              return elem.contentDocument;
            }
            if (nodeName(elem, "template")) {
              elem = elem.content || elem;
            }
            return jQuery2.merge([], elem.childNodes);
          }
        }, function(name, fn3) {
          jQuery2.fn[name] = function(until, selector) {
            var matched = jQuery2.map(this, fn3, until);
            if (name.slice(-5) !== "Until") {
              selector = until;
            }
            if (selector && typeof selector === "string") {
              matched = jQuery2.filter(selector, matched);
            }
            if (this.length > 1) {
              if (!guaranteedUnique[name]) {
                jQuery2.uniqueSort(matched);
              }
              if (rparentsprev.test(name)) {
                matched.reverse();
              }
            }
            return this.pushStack(matched);
          };
        });
        var rnothtmlwhite = /[^\x20\t\r\n\f]+/g;
        function createOptions(options) {
          var object = {};
          jQuery2.each(options.match(rnothtmlwhite) || [], function(_2, flag) {
            object[flag] = true;
          });
          return object;
        }
        jQuery2.Callbacks = function(options) {
          options = typeof options === "string" ? createOptions(options) : jQuery2.extend({}, options);
          var firing, memory, fired, locked, list = [], queue = [], firingIndex = -1, fire = function() {
            locked = locked || options.once;
            fired = firing = true;
            for (; queue.length; firingIndex = -1) {
              memory = queue.shift();
              while (++firingIndex < list.length) {
                if (list[firingIndex].apply(memory[0], memory[1]) === false && options.stopOnFalse) {
                  firingIndex = list.length;
                  memory = false;
                }
              }
            }
            if (!options.memory) {
              memory = false;
            }
            firing = false;
            if (locked) {
              if (memory) {
                list = [];
              } else {
                list = "";
              }
            }
          }, self2 = {
            add: function() {
              if (list) {
                if (memory && !firing) {
                  firingIndex = list.length - 1;
                  queue.push(memory);
                }
                (function add3(args) {
                  jQuery2.each(args, function(_2, arg) {
                    if (isFunction2(arg)) {
                      if (!options.unique || !self2.has(arg)) {
                        list.push(arg);
                      }
                    } else if (arg && arg.length && toType2(arg) !== "string") {
                      add3(arg);
                    }
                  });
                })(arguments);
                if (memory && !firing) {
                  fire();
                }
              }
              return this;
            },
            remove: function() {
              jQuery2.each(arguments, function(_2, arg) {
                var index;
                while ((index = jQuery2.inArray(arg, list, index)) > -1) {
                  list.splice(index, 1);
                  if (index <= firingIndex) {
                    firingIndex--;
                  }
                }
              });
              return this;
            },
            has: function(fn3) {
              return fn3 ? jQuery2.inArray(fn3, list) > -1 : list.length > 0;
            },
            empty: function() {
              if (list) {
                list = [];
              }
              return this;
            },
            disable: function() {
              locked = queue = [];
              list = memory = "";
              return this;
            },
            disabled: function() {
              return !list;
            },
            lock: function() {
              locked = queue = [];
              if (!memory && !firing) {
                list = memory = "";
              }
              return this;
            },
            locked: function() {
              return !!locked;
            },
            fireWith: function(context, args) {
              if (!locked) {
                args = args || [];
                args = [context, args.slice ? args.slice() : args];
                queue.push(args);
                if (!firing) {
                  fire();
                }
              }
              return this;
            },
            fire: function() {
              self2.fireWith(this, arguments);
              return this;
            },
            fired: function() {
              return !!fired;
            }
          };
          return self2;
        };
        function Identity(v2) {
          return v2;
        }
        function Thrower(ex) {
          throw ex;
        }
        function adoptValue(value, resolve2, reject, noValue) {
          var method;
          try {
            if (value && isFunction2(method = value.promise)) {
              method.call(value).done(resolve2).fail(reject);
            } else if (value && isFunction2(method = value.then)) {
              method.call(value, resolve2, reject);
            } else {
              resolve2.apply(void 0, [value].slice(noValue));
            }
          } catch (value2) {
            reject.apply(void 0, [value2]);
          }
        }
        jQuery2.extend({
          Deferred: function(func) {
            var tuples = [
              [
                "notify",
                "progress",
                jQuery2.Callbacks("memory"),
                jQuery2.Callbacks("memory"),
                2
              ],
              [
                "resolve",
                "done",
                jQuery2.Callbacks("once memory"),
                jQuery2.Callbacks("once memory"),
                0,
                "resolved"
              ],
              [
                "reject",
                "fail",
                jQuery2.Callbacks("once memory"),
                jQuery2.Callbacks("once memory"),
                1,
                "rejected"
              ]
            ], state = "pending", promise = {
              state: function() {
                return state;
              },
              always: function() {
                deferred.done(arguments).fail(arguments);
                return this;
              },
              "catch": function(fn3) {
                return promise.then(null, fn3);
              },
              pipe: function() {
                var fns = arguments;
                return jQuery2.Deferred(function(newDefer) {
                  jQuery2.each(tuples, function(_i2, tuple) {
                    var fn3 = isFunction2(fns[tuple[4]]) && fns[tuple[4]];
                    deferred[tuple[1]](function() {
                      var returned = fn3 && fn3.apply(this, arguments);
                      if (returned && isFunction2(returned.promise)) {
                        returned.promise().progress(newDefer.notify).done(newDefer.resolve).fail(newDefer.reject);
                      } else {
                        newDefer[tuple[0] + "With"](this, fn3 ? [returned] : arguments);
                      }
                    });
                  });
                  fns = null;
                }).promise();
              },
              then: function(onFulfilled, onRejected, onProgress) {
                var maxDepth = 0;
                function resolve2(depth, deferred2, handler, special) {
                  return function() {
                    var that = this, args = arguments, mightThrow = function() {
                      var returned, then;
                      if (depth < maxDepth) {
                        return;
                      }
                      returned = handler.apply(that, args);
                      if (returned === deferred2.promise()) {
                        throw new TypeError("Thenable self-resolution");
                      }
                      then = returned && (typeof returned === "object" || typeof returned === "function") && returned.then;
                      if (isFunction2(then)) {
                        if (special) {
                          then.call(returned, resolve2(maxDepth, deferred2, Identity, special), resolve2(maxDepth, deferred2, Thrower, special));
                        } else {
                          maxDepth++;
                          then.call(returned, resolve2(maxDepth, deferred2, Identity, special), resolve2(maxDepth, deferred2, Thrower, special), resolve2(maxDepth, deferred2, Identity, deferred2.notifyWith));
                        }
                      } else {
                        if (handler !== Identity) {
                          that = void 0;
                          args = [returned];
                        }
                        (special || deferred2.resolveWith)(that, args);
                      }
                    }, process2 = special ? mightThrow : function() {
                      try {
                        mightThrow();
                      } catch (e2) {
                        if (jQuery2.Deferred.exceptionHook) {
                          jQuery2.Deferred.exceptionHook(e2, process2.stackTrace);
                        }
                        if (depth + 1 >= maxDepth) {
                          if (handler !== Thrower) {
                            that = void 0;
                            args = [e2];
                          }
                          deferred2.rejectWith(that, args);
                        }
                      }
                    };
                    if (depth) {
                      process2();
                    } else {
                      if (jQuery2.Deferred.getStackHook) {
                        process2.stackTrace = jQuery2.Deferred.getStackHook();
                      }
                      window2.setTimeout(process2);
                    }
                  };
                }
                return jQuery2.Deferred(function(newDefer) {
                  tuples[0][3].add(resolve2(0, newDefer, isFunction2(onProgress) ? onProgress : Identity, newDefer.notifyWith));
                  tuples[1][3].add(resolve2(0, newDefer, isFunction2(onFulfilled) ? onFulfilled : Identity));
                  tuples[2][3].add(resolve2(0, newDefer, isFunction2(onRejected) ? onRejected : Thrower));
                }).promise();
              },
              promise: function(obj) {
                return obj != null ? jQuery2.extend(obj, promise) : promise;
              }
            }, deferred = {};
            jQuery2.each(tuples, function(i2, tuple) {
              var list = tuple[2], stateString = tuple[5];
              promise[tuple[1]] = list.add;
              if (stateString) {
                list.add(function() {
                  state = stateString;
                }, tuples[3 - i2][2].disable, tuples[3 - i2][3].disable, tuples[0][2].lock, tuples[0][3].lock);
              }
              list.add(tuple[3].fire);
              deferred[tuple[0]] = function() {
                deferred[tuple[0] + "With"](this === deferred ? void 0 : this, arguments);
                return this;
              };
              deferred[tuple[0] + "With"] = list.fireWith;
            });
            promise.promise(deferred);
            if (func) {
              func.call(deferred, deferred);
            }
            return deferred;
          },
          when: function(singleValue) {
            var remaining = arguments.length, i2 = remaining, resolveContexts = Array(i2), resolveValues = slice.call(arguments), primary = jQuery2.Deferred(), updateFunc = function(i3) {
              return function(value) {
                resolveContexts[i3] = this;
                resolveValues[i3] = arguments.length > 1 ? slice.call(arguments) : value;
                if (!--remaining) {
                  primary.resolveWith(resolveContexts, resolveValues);
                }
              };
            };
            if (remaining <= 1) {
              adoptValue(singleValue, primary.done(updateFunc(i2)).resolve, primary.reject, !remaining);
              if (primary.state() === "pending" || isFunction2(resolveValues[i2] && resolveValues[i2].then)) {
                return primary.then();
              }
            }
            while (i2--) {
              adoptValue(resolveValues[i2], updateFunc(i2), primary.reject);
            }
            return primary.promise();
          }
        });
        var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;
        jQuery2.Deferred.exceptionHook = function(error3, stack) {
          if (window2.console && window2.console.warn && error3 && rerrorNames.test(error3.name)) {
            window2.console.warn("jQuery.Deferred exception: " + error3.message, error3.stack, stack);
          }
        };
        jQuery2.readyException = function(error3) {
          window2.setTimeout(function() {
            throw error3;
          });
        };
        var readyList = jQuery2.Deferred();
        jQuery2.fn.ready = function(fn3) {
          readyList.then(fn3).catch(function(error3) {
            jQuery2.readyException(error3);
          });
          return this;
        };
        jQuery2.extend({
          isReady: false,
          readyWait: 1,
          ready: function(wait) {
            if (wait === true ? --jQuery2.readyWait : jQuery2.isReady) {
              return;
            }
            jQuery2.isReady = true;
            if (wait !== true && --jQuery2.readyWait > 0) {
              return;
            }
            readyList.resolveWith(document2, [jQuery2]);
          }
        });
        jQuery2.ready.then = readyList.then;
        function completed() {
          document2.removeEventListener("DOMContentLoaded", completed);
          window2.removeEventListener("load", completed);
          jQuery2.ready();
        }
        if (document2.readyState === "complete" || document2.readyState !== "loading" && !document2.documentElement.doScroll) {
          window2.setTimeout(jQuery2.ready);
        } else {
          document2.addEventListener("DOMContentLoaded", completed);
          window2.addEventListener("load", completed);
        }
        var access = function(elems, fn3, key, value, chainable, emptyGet, raw) {
          var i2 = 0, len = elems.length, bulk = key == null;
          if (toType2(key) === "object") {
            chainable = true;
            for (i2 in key) {
              access(elems, fn3, i2, key[i2], true, emptyGet, raw);
            }
          } else if (value !== void 0) {
            chainable = true;
            if (!isFunction2(value)) {
              raw = true;
            }
            if (bulk) {
              if (raw) {
                fn3.call(elems, value);
                fn3 = null;
              } else {
                bulk = fn3;
                fn3 = function(elem, _key, value2) {
                  return bulk.call(jQuery2(elem), value2);
                };
              }
            }
            if (fn3) {
              for (; i2 < len; i2++) {
                fn3(elems[i2], key, raw ? value : value.call(elems[i2], i2, fn3(elems[i2], key)));
              }
            }
          }
          if (chainable) {
            return elems;
          }
          if (bulk) {
            return fn3.call(elems);
          }
          return len ? fn3(elems[0], key) : emptyGet;
        };
        var rmsPrefix = /^-ms-/, rdashAlpha = /-([a-z])/g;
        function fcamelCase(_all, letter) {
          return letter.toUpperCase();
        }
        function camelCase(string) {
          return string.replace(rmsPrefix, "ms-").replace(rdashAlpha, fcamelCase);
        }
        var acceptData = function(owner) {
          return owner.nodeType === 1 || owner.nodeType === 9 || !+owner.nodeType;
        };
        function Data2() {
          this.expando = jQuery2.expando + Data2.uid++;
        }
        Data2.uid = 1;
        Data2.prototype = {
          cache: function(owner) {
            var value = owner[this.expando];
            if (!value) {
              value = {};
              if (acceptData(owner)) {
                if (owner.nodeType) {
                  owner[this.expando] = value;
                } else {
                  Object.defineProperty(owner, this.expando, {
                    value,
                    configurable: true
                  });
                }
              }
            }
            return value;
          },
          set: function(owner, data, value) {
            var prop, cache2 = this.cache(owner);
            if (typeof data === "string") {
              cache2[camelCase(data)] = value;
            } else {
              for (prop in data) {
                cache2[camelCase(prop)] = data[prop];
              }
            }
            return cache2;
          },
          get: function(owner, key) {
            return key === void 0 ? this.cache(owner) : owner[this.expando] && owner[this.expando][camelCase(key)];
          },
          access: function(owner, key, value) {
            if (key === void 0 || key && typeof key === "string" && value === void 0) {
              return this.get(owner, key);
            }
            this.set(owner, key, value);
            return value !== void 0 ? value : key;
          },
          remove: function(owner, key) {
            var i2, cache2 = owner[this.expando];
            if (cache2 === void 0) {
              return;
            }
            if (key !== void 0) {
              if (Array.isArray(key)) {
                key = key.map(camelCase);
              } else {
                key = camelCase(key);
                key = key in cache2 ? [key] : key.match(rnothtmlwhite) || [];
              }
              i2 = key.length;
              while (i2--) {
                delete cache2[key[i2]];
              }
            }
            if (key === void 0 || jQuery2.isEmptyObject(cache2)) {
              if (owner.nodeType) {
                owner[this.expando] = void 0;
              } else {
                delete owner[this.expando];
              }
            }
          },
          hasData: function(owner) {
            var cache2 = owner[this.expando];
            return cache2 !== void 0 && !jQuery2.isEmptyObject(cache2);
          }
        };
        var dataPriv = new Data2();
        var dataUser = new Data2();
        var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, rmultiDash = /[A-Z]/g;
        function getData(data) {
          if (data === "true") {
            return true;
          }
          if (data === "false") {
            return false;
          }
          if (data === "null") {
            return null;
          }
          if (data === +data + "") {
            return +data;
          }
          if (rbrace.test(data)) {
            return JSON.parse(data);
          }
          return data;
        }
        function dataAttr(elem, key, data) {
          var name;
          if (data === void 0 && elem.nodeType === 1) {
            name = "data-" + key.replace(rmultiDash, "-$&").toLowerCase();
            data = elem.getAttribute(name);
            if (typeof data === "string") {
              try {
                data = getData(data);
              } catch (e2) {
              }
              dataUser.set(elem, key, data);
            } else {
              data = void 0;
            }
          }
          return data;
        }
        jQuery2.extend({
          hasData: function(elem) {
            return dataUser.hasData(elem) || dataPriv.hasData(elem);
          },
          data: function(elem, name, data) {
            return dataUser.access(elem, name, data);
          },
          removeData: function(elem, name) {
            dataUser.remove(elem, name);
          },
          _data: function(elem, name, data) {
            return dataPriv.access(elem, name, data);
          },
          _removeData: function(elem, name) {
            dataPriv.remove(elem, name);
          }
        });
        jQuery2.fn.extend({
          data: function(key, value) {
            var i2, name, data, elem = this[0], attrs = elem && elem.attributes;
            if (key === void 0) {
              if (this.length) {
                data = dataUser.get(elem);
                if (elem.nodeType === 1 && !dataPriv.get(elem, "hasDataAttrs")) {
                  i2 = attrs.length;
                  while (i2--) {
                    if (attrs[i2]) {
                      name = attrs[i2].name;
                      if (name.indexOf("data-") === 0) {
                        name = camelCase(name.slice(5));
                        dataAttr(elem, name, data[name]);
                      }
                    }
                  }
                  dataPriv.set(elem, "hasDataAttrs", true);
                }
              }
              return data;
            }
            if (typeof key === "object") {
              return this.each(function() {
                dataUser.set(this, key);
              });
            }
            return access(this, function(value2) {
              var data2;
              if (elem && value2 === void 0) {
                data2 = dataUser.get(elem, key);
                if (data2 !== void 0) {
                  return data2;
                }
                data2 = dataAttr(elem, key);
                if (data2 !== void 0) {
                  return data2;
                }
                return;
              }
              this.each(function() {
                dataUser.set(this, key, value2);
              });
            }, null, value, arguments.length > 1, null, true);
          },
          removeData: function(key) {
            return this.each(function() {
              dataUser.remove(this, key);
            });
          }
        });
        jQuery2.extend({
          queue: function(elem, type, data) {
            var queue;
            if (elem) {
              type = (type || "fx") + "queue";
              queue = dataPriv.get(elem, type);
              if (data) {
                if (!queue || Array.isArray(data)) {
                  queue = dataPriv.access(elem, type, jQuery2.makeArray(data));
                } else {
                  queue.push(data);
                }
              }
              return queue || [];
            }
          },
          dequeue: function(elem, type) {
            type = type || "fx";
            var queue = jQuery2.queue(elem, type), startLength = queue.length, fn3 = queue.shift(), hooks = jQuery2._queueHooks(elem, type), next = function() {
              jQuery2.dequeue(elem, type);
            };
            if (fn3 === "inprogress") {
              fn3 = queue.shift();
              startLength--;
            }
            if (fn3) {
              if (type === "fx") {
                queue.unshift("inprogress");
              }
              delete hooks.stop;
              fn3.call(elem, next, hooks);
            }
            if (!startLength && hooks) {
              hooks.empty.fire();
            }
          },
          _queueHooks: function(elem, type) {
            var key = type + "queueHooks";
            return dataPriv.get(elem, key) || dataPriv.access(elem, key, {
              empty: jQuery2.Callbacks("once memory").add(function() {
                dataPriv.remove(elem, [type + "queue", key]);
              })
            });
          }
        });
        jQuery2.fn.extend({
          queue: function(type, data) {
            var setter = 2;
            if (typeof type !== "string") {
              data = type;
              type = "fx";
              setter--;
            }
            if (arguments.length < setter) {
              return jQuery2.queue(this[0], type);
            }
            return data === void 0 ? this : this.each(function() {
              var queue = jQuery2.queue(this, type, data);
              jQuery2._queueHooks(this, type);
              if (type === "fx" && queue[0] !== "inprogress") {
                jQuery2.dequeue(this, type);
              }
            });
          },
          dequeue: function(type) {
            return this.each(function() {
              jQuery2.dequeue(this, type);
            });
          },
          clearQueue: function(type) {
            return this.queue(type || "fx", []);
          },
          promise: function(type, obj) {
            var tmp, count = 1, defer = jQuery2.Deferred(), elements2 = this, i2 = this.length, resolve2 = function() {
              if (!--count) {
                defer.resolveWith(elements2, [elements2]);
              }
            };
            if (typeof type !== "string") {
              obj = type;
              type = void 0;
            }
            type = type || "fx";
            while (i2--) {
              tmp = dataPriv.get(elements2[i2], type + "queueHooks");
              if (tmp && tmp.empty) {
                count++;
                tmp.empty.add(resolve2);
              }
            }
            resolve2();
            return defer.promise(obj);
          }
        });
        var pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source;
        var rcssNum = new RegExp("^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i");
        var cssExpand = ["Top", "Right", "Bottom", "Left"];
        var documentElement = document2.documentElement;
        var isAttached = function(elem) {
          return jQuery2.contains(elem.ownerDocument, elem);
        }, composed = { composed: true };
        if (documentElement.getRootNode) {
          isAttached = function(elem) {
            return jQuery2.contains(elem.ownerDocument, elem) || elem.getRootNode(composed) === elem.ownerDocument;
          };
        }
        var isHiddenWithinTree = function(elem, el) {
          elem = el || elem;
          return elem.style.display === "none" || elem.style.display === "" && isAttached(elem) && jQuery2.css(elem, "display") === "none";
        };
        function adjustCSS(elem, prop, valueParts, tween) {
          var adjusted, scale, maxIterations = 20, currentValue = tween ? function() {
            return tween.cur();
          } : function() {
            return jQuery2.css(elem, prop, "");
          }, initial = currentValue(), unit = valueParts && valueParts[3] || (jQuery2.cssNumber[prop] ? "" : "px"), initialInUnit = elem.nodeType && (jQuery2.cssNumber[prop] || unit !== "px" && +initial) && rcssNum.exec(jQuery2.css(elem, prop));
          if (initialInUnit && initialInUnit[3] !== unit) {
            initial = initial / 2;
            unit = unit || initialInUnit[3];
            initialInUnit = +initial || 1;
            while (maxIterations--) {
              jQuery2.style(elem, prop, initialInUnit + unit);
              if ((1 - scale) * (1 - (scale = currentValue() / initial || 0.5)) <= 0) {
                maxIterations = 0;
              }
              initialInUnit = initialInUnit / scale;
            }
            initialInUnit = initialInUnit * 2;
            jQuery2.style(elem, prop, initialInUnit + unit);
            valueParts = valueParts || [];
          }
          if (valueParts) {
            initialInUnit = +initialInUnit || +initial || 0;
            adjusted = valueParts[1] ? initialInUnit + (valueParts[1] + 1) * valueParts[2] : +valueParts[2];
            if (tween) {
              tween.unit = unit;
              tween.start = initialInUnit;
              tween.end = adjusted;
            }
          }
          return adjusted;
        }
        var defaultDisplayMap = {};
        function getDefaultDisplay(elem) {
          var temp, doc = elem.ownerDocument, nodeName2 = elem.nodeName, display = defaultDisplayMap[nodeName2];
          if (display) {
            return display;
          }
          temp = doc.body.appendChild(doc.createElement(nodeName2));
          display = jQuery2.css(temp, "display");
          temp.parentNode.removeChild(temp);
          if (display === "none") {
            display = "block";
          }
          defaultDisplayMap[nodeName2] = display;
          return display;
        }
        function showHide(elements2, show) {
          var display, elem, values = [], index = 0, length = elements2.length;
          for (; index < length; index++) {
            elem = elements2[index];
            if (!elem.style) {
              continue;
            }
            display = elem.style.display;
            if (show) {
              if (display === "none") {
                values[index] = dataPriv.get(elem, "display") || null;
                if (!values[index]) {
                  elem.style.display = "";
                }
              }
              if (elem.style.display === "" && isHiddenWithinTree(elem)) {
                values[index] = getDefaultDisplay(elem);
              }
            } else {
              if (display !== "none") {
                values[index] = "none";
                dataPriv.set(elem, "display", display);
              }
            }
          }
          for (index = 0; index < length; index++) {
            if (values[index] != null) {
              elements2[index].style.display = values[index];
            }
          }
          return elements2;
        }
        jQuery2.fn.extend({
          show: function() {
            return showHide(this, true);
          },
          hide: function() {
            return showHide(this);
          },
          toggle: function(state) {
            if (typeof state === "boolean") {
              return state ? this.show() : this.hide();
            }
            return this.each(function() {
              if (isHiddenWithinTree(this)) {
                jQuery2(this).show();
              } else {
                jQuery2(this).hide();
              }
            });
          }
        });
        var rcheckableType = /^(?:checkbox|radio)$/i;
        var rtagName = /<([a-z][^\/\0>\x20\t\r\n\f]*)/i;
        var rscriptType = /^$|^module$|\/(?:java|ecma)script/i;
        (function() {
          var fragment = document2.createDocumentFragment(), div = fragment.appendChild(document2.createElement("div")), input = document2.createElement("input");
          input.setAttribute("type", "radio");
          input.setAttribute("checked", "checked");
          input.setAttribute("name", "t");
          div.appendChild(input);
          support.checkClone = div.cloneNode(true).cloneNode(true).lastChild.checked;
          div.innerHTML = "<textarea>x</textarea>";
          support.noCloneChecked = !!div.cloneNode(true).lastChild.defaultValue;
          div.innerHTML = "<option></option>";
          support.option = !!div.lastChild;
        })();
        var wrapMap = {
          thead: [1, "<table>", "</table>"],
          col: [2, "<table><colgroup>", "</colgroup></table>"],
          tr: [2, "<table><tbody>", "</tbody></table>"],
          td: [3, "<table><tbody><tr>", "</tr></tbody></table>"],
          _default: [0, "", ""]
        };
        wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
        wrapMap.th = wrapMap.td;
        if (!support.option) {
          wrapMap.optgroup = wrapMap.option = [1, "<select multiple='multiple'>", "</select>"];
        }
        function getAll(context, tag) {
          var ret;
          if (typeof context.getElementsByTagName !== "undefined") {
            ret = context.getElementsByTagName(tag || "*");
          } else if (typeof context.querySelectorAll !== "undefined") {
            ret = context.querySelectorAll(tag || "*");
          } else {
            ret = [];
          }
          if (tag === void 0 || tag && nodeName(context, tag)) {
            return jQuery2.merge([context], ret);
          }
          return ret;
        }
        function setGlobalEval(elems, refElements) {
          var i2 = 0, l2 = elems.length;
          for (; i2 < l2; i2++) {
            dataPriv.set(elems[i2], "globalEval", !refElements || dataPriv.get(refElements[i2], "globalEval"));
          }
        }
        var rhtml = /<|&#?\w+;/;
        function buildFragment(elems, context, scripts, selection, ignored) {
          var elem, tmp, tag, wrap, attached, j2, fragment = context.createDocumentFragment(), nodes = [], i2 = 0, l2 = elems.length;
          for (; i2 < l2; i2++) {
            elem = elems[i2];
            if (elem || elem === 0) {
              if (toType2(elem) === "object") {
                jQuery2.merge(nodes, elem.nodeType ? [elem] : elem);
              } else if (!rhtml.test(elem)) {
                nodes.push(context.createTextNode(elem));
              } else {
                tmp = tmp || fragment.appendChild(context.createElement("div"));
                tag = (rtagName.exec(elem) || ["", ""])[1].toLowerCase();
                wrap = wrapMap[tag] || wrapMap._default;
                tmp.innerHTML = wrap[1] + jQuery2.htmlPrefilter(elem) + wrap[2];
                j2 = wrap[0];
                while (j2--) {
                  tmp = tmp.lastChild;
                }
                jQuery2.merge(nodes, tmp.childNodes);
                tmp = fragment.firstChild;
                tmp.textContent = "";
              }
            }
          }
          fragment.textContent = "";
          i2 = 0;
          while (elem = nodes[i2++]) {
            if (selection && jQuery2.inArray(elem, selection) > -1) {
              if (ignored) {
                ignored.push(elem);
              }
              continue;
            }
            attached = isAttached(elem);
            tmp = getAll(fragment.appendChild(elem), "script");
            if (attached) {
              setGlobalEval(tmp);
            }
            if (scripts) {
              j2 = 0;
              while (elem = tmp[j2++]) {
                if (rscriptType.test(elem.type || "")) {
                  scripts.push(elem);
                }
              }
            }
          }
          return fragment;
        }
        var rtypenamespace = /^([^.]*)(?:\.(.+)|)/;
        function returnTrue() {
          return true;
        }
        function returnFalse() {
          return false;
        }
        function expectSync(elem, type) {
          return elem === safeActiveElement() === (type === "focus");
        }
        function safeActiveElement() {
          try {
            return document2.activeElement;
          } catch (err) {
          }
        }
        function on2(elem, types, selector, data, fn3, one) {
          var origFn, type;
          if (typeof types === "object") {
            if (typeof selector !== "string") {
              data = data || selector;
              selector = void 0;
            }
            for (type in types) {
              on2(elem, type, selector, data, types[type], one);
            }
            return elem;
          }
          if (data == null && fn3 == null) {
            fn3 = selector;
            data = selector = void 0;
          } else if (fn3 == null) {
            if (typeof selector === "string") {
              fn3 = data;
              data = void 0;
            } else {
              fn3 = data;
              data = selector;
              selector = void 0;
            }
          }
          if (fn3 === false) {
            fn3 = returnFalse;
          } else if (!fn3) {
            return elem;
          }
          if (one === 1) {
            origFn = fn3;
            fn3 = function(event) {
              jQuery2().off(event);
              return origFn.apply(this, arguments);
            };
            fn3.guid = origFn.guid || (origFn.guid = jQuery2.guid++);
          }
          return elem.each(function() {
            jQuery2.event.add(this, types, fn3, data, selector);
          });
        }
        jQuery2.event = {
          global: {},
          add: function(elem, types, handler, data, selector) {
            var handleObjIn, eventHandle, tmp, events, t2, handleObj, special, handlers, type, namespaces, origType, elemData = dataPriv.get(elem);
            if (!acceptData(elem)) {
              return;
            }
            if (handler.handler) {
              handleObjIn = handler;
              handler = handleObjIn.handler;
              selector = handleObjIn.selector;
            }
            if (selector) {
              jQuery2.find.matchesSelector(documentElement, selector);
            }
            if (!handler.guid) {
              handler.guid = jQuery2.guid++;
            }
            if (!(events = elemData.events)) {
              events = elemData.events = /* @__PURE__ */ Object.create(null);
            }
            if (!(eventHandle = elemData.handle)) {
              eventHandle = elemData.handle = function(e2) {
                return typeof jQuery2 !== "undefined" && jQuery2.event.triggered !== e2.type ? jQuery2.event.dispatch.apply(elem, arguments) : void 0;
              };
            }
            types = (types || "").match(rnothtmlwhite) || [""];
            t2 = types.length;
            while (t2--) {
              tmp = rtypenamespace.exec(types[t2]) || [];
              type = origType = tmp[1];
              namespaces = (tmp[2] || "").split(".").sort();
              if (!type) {
                continue;
              }
              special = jQuery2.event.special[type] || {};
              type = (selector ? special.delegateType : special.bindType) || type;
              special = jQuery2.event.special[type] || {};
              handleObj = jQuery2.extend({
                type,
                origType,
                data,
                handler,
                guid: handler.guid,
                selector,
                needsContext: selector && jQuery2.expr.match.needsContext.test(selector),
                namespace: namespaces.join(".")
              }, handleObjIn);
              if (!(handlers = events[type])) {
                handlers = events[type] = [];
                handlers.delegateCount = 0;
                if (!special.setup || special.setup.call(elem, data, namespaces, eventHandle) === false) {
                  if (elem.addEventListener) {
                    elem.addEventListener(type, eventHandle);
                  }
                }
              }
              if (special.add) {
                special.add.call(elem, handleObj);
                if (!handleObj.handler.guid) {
                  handleObj.handler.guid = handler.guid;
                }
              }
              if (selector) {
                handlers.splice(handlers.delegateCount++, 0, handleObj);
              } else {
                handlers.push(handleObj);
              }
              jQuery2.event.global[type] = true;
            }
          },
          remove: function(elem, types, handler, selector, mappedTypes) {
            var j2, origCount, tmp, events, t2, handleObj, special, handlers, type, namespaces, origType, elemData = dataPriv.hasData(elem) && dataPriv.get(elem);
            if (!elemData || !(events = elemData.events)) {
              return;
            }
            types = (types || "").match(rnothtmlwhite) || [""];
            t2 = types.length;
            while (t2--) {
              tmp = rtypenamespace.exec(types[t2]) || [];
              type = origType = tmp[1];
              namespaces = (tmp[2] || "").split(".").sort();
              if (!type) {
                for (type in events) {
                  jQuery2.event.remove(elem, type + types[t2], handler, selector, true);
                }
                continue;
              }
              special = jQuery2.event.special[type] || {};
              type = (selector ? special.delegateType : special.bindType) || type;
              handlers = events[type] || [];
              tmp = tmp[2] && new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)");
              origCount = j2 = handlers.length;
              while (j2--) {
                handleObj = handlers[j2];
                if ((mappedTypes || origType === handleObj.origType) && (!handler || handler.guid === handleObj.guid) && (!tmp || tmp.test(handleObj.namespace)) && (!selector || selector === handleObj.selector || selector === "**" && handleObj.selector)) {
                  handlers.splice(j2, 1);
                  if (handleObj.selector) {
                    handlers.delegateCount--;
                  }
                  if (special.remove) {
                    special.remove.call(elem, handleObj);
                  }
                }
              }
              if (origCount && !handlers.length) {
                if (!special.teardown || special.teardown.call(elem, namespaces, elemData.handle) === false) {
                  jQuery2.removeEvent(elem, type, elemData.handle);
                }
                delete events[type];
              }
            }
            if (jQuery2.isEmptyObject(events)) {
              dataPriv.remove(elem, "handle events");
            }
          },
          dispatch: function(nativeEvent) {
            var i2, j2, ret, matched, handleObj, handlerQueue, args = new Array(arguments.length), event = jQuery2.event.fix(nativeEvent), handlers = (dataPriv.get(this, "events") || /* @__PURE__ */ Object.create(null))[event.type] || [], special = jQuery2.event.special[event.type] || {};
            args[0] = event;
            for (i2 = 1; i2 < arguments.length; i2++) {
              args[i2] = arguments[i2];
            }
            event.delegateTarget = this;
            if (special.preDispatch && special.preDispatch.call(this, event) === false) {
              return;
            }
            handlerQueue = jQuery2.event.handlers.call(this, event, handlers);
            i2 = 0;
            while ((matched = handlerQueue[i2++]) && !event.isPropagationStopped()) {
              event.currentTarget = matched.elem;
              j2 = 0;
              while ((handleObj = matched.handlers[j2++]) && !event.isImmediatePropagationStopped()) {
                if (!event.rnamespace || handleObj.namespace === false || event.rnamespace.test(handleObj.namespace)) {
                  event.handleObj = handleObj;
                  event.data = handleObj.data;
                  ret = ((jQuery2.event.special[handleObj.origType] || {}).handle || handleObj.handler).apply(matched.elem, args);
                  if (ret !== void 0) {
                    if ((event.result = ret) === false) {
                      event.preventDefault();
                      event.stopPropagation();
                    }
                  }
                }
              }
            }
            if (special.postDispatch) {
              special.postDispatch.call(this, event);
            }
            return event.result;
          },
          handlers: function(event, handlers) {
            var i2, handleObj, sel, matchedHandlers, matchedSelectors, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target;
            if (delegateCount && cur.nodeType && !(event.type === "click" && event.button >= 1)) {
              for (; cur !== this; cur = cur.parentNode || this) {
                if (cur.nodeType === 1 && !(event.type === "click" && cur.disabled === true)) {
                  matchedHandlers = [];
                  matchedSelectors = {};
                  for (i2 = 0; i2 < delegateCount; i2++) {
                    handleObj = handlers[i2];
                    sel = handleObj.selector + " ";
                    if (matchedSelectors[sel] === void 0) {
                      matchedSelectors[sel] = handleObj.needsContext ? jQuery2(sel, this).index(cur) > -1 : jQuery2.find(sel, this, null, [cur]).length;
                    }
                    if (matchedSelectors[sel]) {
                      matchedHandlers.push(handleObj);
                    }
                  }
                  if (matchedHandlers.length) {
                    handlerQueue.push({ elem: cur, handlers: matchedHandlers });
                  }
                }
              }
            }
            cur = this;
            if (delegateCount < handlers.length) {
              handlerQueue.push({ elem: cur, handlers: handlers.slice(delegateCount) });
            }
            return handlerQueue;
          },
          addProp: function(name, hook) {
            Object.defineProperty(jQuery2.Event.prototype, name, {
              enumerable: true,
              configurable: true,
              get: isFunction2(hook) ? function() {
                if (this.originalEvent) {
                  return hook(this.originalEvent);
                }
              } : function() {
                if (this.originalEvent) {
                  return this.originalEvent[name];
                }
              },
              set: function(value) {
                Object.defineProperty(this, name, {
                  enumerable: true,
                  configurable: true,
                  writable: true,
                  value
                });
              }
            });
          },
          fix: function(originalEvent) {
            return originalEvent[jQuery2.expando] ? originalEvent : new jQuery2.Event(originalEvent);
          },
          special: {
            load: {
              noBubble: true
            },
            click: {
              setup: function(data) {
                var el = this || data;
                if (rcheckableType.test(el.type) && el.click && nodeName(el, "input")) {
                  leverageNative(el, "click", returnTrue);
                }
                return false;
              },
              trigger: function(data) {
                var el = this || data;
                if (rcheckableType.test(el.type) && el.click && nodeName(el, "input")) {
                  leverageNative(el, "click");
                }
                return true;
              },
              _default: function(event) {
                var target = event.target;
                return rcheckableType.test(target.type) && target.click && nodeName(target, "input") && dataPriv.get(target, "click") || nodeName(target, "a");
              }
            },
            beforeunload: {
              postDispatch: function(event) {
                if (event.result !== void 0 && event.originalEvent) {
                  event.originalEvent.returnValue = event.result;
                }
              }
            }
          }
        };
        function leverageNative(el, type, expectSync2) {
          if (!expectSync2) {
            if (dataPriv.get(el, type) === void 0) {
              jQuery2.event.add(el, type, returnTrue);
            }
            return;
          }
          dataPriv.set(el, type, false);
          jQuery2.event.add(el, type, {
            namespace: false,
            handler: function(event) {
              var notAsync, result, saved = dataPriv.get(this, type);
              if (event.isTrigger & 1 && this[type]) {
                if (!saved.length) {
                  saved = slice.call(arguments);
                  dataPriv.set(this, type, saved);
                  notAsync = expectSync2(this, type);
                  this[type]();
                  result = dataPriv.get(this, type);
                  if (saved !== result || notAsync) {
                    dataPriv.set(this, type, false);
                  } else {
                    result = {};
                  }
                  if (saved !== result) {
                    event.stopImmediatePropagation();
                    event.preventDefault();
                    return result && result.value;
                  }
                } else if ((jQuery2.event.special[type] || {}).delegateType) {
                  event.stopPropagation();
                }
              } else if (saved.length) {
                dataPriv.set(this, type, {
                  value: jQuery2.event.trigger(jQuery2.extend(saved[0], jQuery2.Event.prototype), saved.slice(1), this)
                });
                event.stopImmediatePropagation();
              }
            }
          });
        }
        jQuery2.removeEvent = function(elem, type, handle) {
          if (elem.removeEventListener) {
            elem.removeEventListener(type, handle);
          }
        };
        jQuery2.Event = function(src, props) {
          if (!(this instanceof jQuery2.Event)) {
            return new jQuery2.Event(src, props);
          }
          if (src && src.type) {
            this.originalEvent = src;
            this.type = src.type;
            this.isDefaultPrevented = src.defaultPrevented || src.defaultPrevented === void 0 && src.returnValue === false ? returnTrue : returnFalse;
            this.target = src.target && src.target.nodeType === 3 ? src.target.parentNode : src.target;
            this.currentTarget = src.currentTarget;
            this.relatedTarget = src.relatedTarget;
          } else {
            this.type = src;
          }
          if (props) {
            jQuery2.extend(this, props);
          }
          this.timeStamp = src && src.timeStamp || Date.now();
          this[jQuery2.expando] = true;
        };
        jQuery2.Event.prototype = {
          constructor: jQuery2.Event,
          isDefaultPrevented: returnFalse,
          isPropagationStopped: returnFalse,
          isImmediatePropagationStopped: returnFalse,
          isSimulated: false,
          preventDefault: function() {
            var e2 = this.originalEvent;
            this.isDefaultPrevented = returnTrue;
            if (e2 && !this.isSimulated) {
              e2.preventDefault();
            }
          },
          stopPropagation: function() {
            var e2 = this.originalEvent;
            this.isPropagationStopped = returnTrue;
            if (e2 && !this.isSimulated) {
              e2.stopPropagation();
            }
          },
          stopImmediatePropagation: function() {
            var e2 = this.originalEvent;
            this.isImmediatePropagationStopped = returnTrue;
            if (e2 && !this.isSimulated) {
              e2.stopImmediatePropagation();
            }
            this.stopPropagation();
          }
        };
        jQuery2.each({
          altKey: true,
          bubbles: true,
          cancelable: true,
          changedTouches: true,
          ctrlKey: true,
          detail: true,
          eventPhase: true,
          metaKey: true,
          pageX: true,
          pageY: true,
          shiftKey: true,
          view: true,
          "char": true,
          code: true,
          charCode: true,
          key: true,
          keyCode: true,
          button: true,
          buttons: true,
          clientX: true,
          clientY: true,
          offsetX: true,
          offsetY: true,
          pointerId: true,
          pointerType: true,
          screenX: true,
          screenY: true,
          targetTouches: true,
          toElement: true,
          touches: true,
          which: true
        }, jQuery2.event.addProp);
        jQuery2.each({ focus: "focusin", blur: "focusout" }, function(type, delegateType) {
          jQuery2.event.special[type] = {
            setup: function() {
              leverageNative(this, type, expectSync);
              return false;
            },
            trigger: function() {
              leverageNative(this, type);
              return true;
            },
            _default: function() {
              return true;
            },
            delegateType
          };
        });
        jQuery2.each({
          mouseenter: "mouseover",
          mouseleave: "mouseout",
          pointerenter: "pointerover",
          pointerleave: "pointerout"
        }, function(orig, fix) {
          jQuery2.event.special[orig] = {
            delegateType: fix,
            bindType: fix,
            handle: function(event) {
              var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj;
              if (!related || related !== target && !jQuery2.contains(target, related)) {
                event.type = handleObj.origType;
                ret = handleObj.handler.apply(this, arguments);
                event.type = fix;
              }
              return ret;
            }
          };
        });
        jQuery2.fn.extend({
          on: function(types, selector, data, fn3) {
            return on2(this, types, selector, data, fn3);
          },
          one: function(types, selector, data, fn3) {
            return on2(this, types, selector, data, fn3, 1);
          },
          off: function(types, selector, fn3) {
            var handleObj, type;
            if (types && types.preventDefault && types.handleObj) {
              handleObj = types.handleObj;
              jQuery2(types.delegateTarget).off(handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler);
              return this;
            }
            if (typeof types === "object") {
              for (type in types) {
                this.off(type, selector, types[type]);
              }
              return this;
            }
            if (selector === false || typeof selector === "function") {
              fn3 = selector;
              selector = void 0;
            }
            if (fn3 === false) {
              fn3 = returnFalse;
            }
            return this.each(function() {
              jQuery2.event.remove(this, types, fn3, selector);
            });
          }
        });
        var rnoInnerhtml = /<script|<style|<link/i, rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;
        function manipulationTarget(elem, content) {
          if (nodeName(elem, "table") && nodeName(content.nodeType !== 11 ? content : content.firstChild, "tr")) {
            return jQuery2(elem).children("tbody")[0] || elem;
          }
          return elem;
        }
        function disableScript(elem) {
          elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type;
          return elem;
        }
        function restoreScript(elem) {
          if ((elem.type || "").slice(0, 5) === "true/") {
            elem.type = elem.type.slice(5);
          } else {
            elem.removeAttribute("type");
          }
          return elem;
        }
        function cloneCopyEvent(src, dest) {
          var i2, l2, type, pdataOld, udataOld, udataCur, events;
          if (dest.nodeType !== 1) {
            return;
          }
          if (dataPriv.hasData(src)) {
            pdataOld = dataPriv.get(src);
            events = pdataOld.events;
            if (events) {
              dataPriv.remove(dest, "handle events");
              for (type in events) {
                for (i2 = 0, l2 = events[type].length; i2 < l2; i2++) {
                  jQuery2.event.add(dest, type, events[type][i2]);
                }
              }
            }
          }
          if (dataUser.hasData(src)) {
            udataOld = dataUser.access(src);
            udataCur = jQuery2.extend({}, udataOld);
            dataUser.set(dest, udataCur);
          }
        }
        function fixInput(src, dest) {
          var nodeName2 = dest.nodeName.toLowerCase();
          if (nodeName2 === "input" && rcheckableType.test(src.type)) {
            dest.checked = src.checked;
          } else if (nodeName2 === "input" || nodeName2 === "textarea") {
            dest.defaultValue = src.defaultValue;
          }
        }
        function domManip(collection, args, callback2, ignored) {
          args = flat(args);
          var fragment, first, scripts, hasScripts, node, doc, i2 = 0, l2 = collection.length, iNoClone = l2 - 1, value = args[0], valueIsFunction = isFunction2(value);
          if (valueIsFunction || l2 > 1 && typeof value === "string" && !support.checkClone && rchecked.test(value)) {
            return collection.each(function(index) {
              var self2 = collection.eq(index);
              if (valueIsFunction) {
                args[0] = value.call(this, index, self2.html());
              }
              domManip(self2, args, callback2, ignored);
            });
          }
          if (l2) {
            fragment = buildFragment(args, collection[0].ownerDocument, false, collection, ignored);
            first = fragment.firstChild;
            if (fragment.childNodes.length === 1) {
              fragment = first;
            }
            if (first || ignored) {
              scripts = jQuery2.map(getAll(fragment, "script"), disableScript);
              hasScripts = scripts.length;
              for (; i2 < l2; i2++) {
                node = fragment;
                if (i2 !== iNoClone) {
                  node = jQuery2.clone(node, true, true);
                  if (hasScripts) {
                    jQuery2.merge(scripts, getAll(node, "script"));
                  }
                }
                callback2.call(collection[i2], node, i2);
              }
              if (hasScripts) {
                doc = scripts[scripts.length - 1].ownerDocument;
                jQuery2.map(scripts, restoreScript);
                for (i2 = 0; i2 < hasScripts; i2++) {
                  node = scripts[i2];
                  if (rscriptType.test(node.type || "") && !dataPriv.access(node, "globalEval") && jQuery2.contains(doc, node)) {
                    if (node.src && (node.type || "").toLowerCase() !== "module") {
                      if (jQuery2._evalUrl && !node.noModule) {
                        jQuery2._evalUrl(node.src, {
                          nonce: node.nonce || node.getAttribute("nonce")
                        }, doc);
                      }
                    } else {
                      DOMEval(node.textContent.replace(rcleanScript, ""), node, doc);
                    }
                  }
                }
              }
            }
          }
          return collection;
        }
        function remove(elem, selector, keepData) {
          var node, nodes = selector ? jQuery2.filter(selector, elem) : elem, i2 = 0;
          for (; (node = nodes[i2]) != null; i2++) {
            if (!keepData && node.nodeType === 1) {
              jQuery2.cleanData(getAll(node));
            }
            if (node.parentNode) {
              if (keepData && isAttached(node)) {
                setGlobalEval(getAll(node, "script"));
              }
              node.parentNode.removeChild(node);
            }
          }
          return elem;
        }
        jQuery2.extend({
          htmlPrefilter: function(html) {
            return html;
          },
          clone: function(elem, dataAndEvents, deepDataAndEvents) {
            var i2, l2, srcElements, destElements, clone2 = elem.cloneNode(true), inPage = isAttached(elem);
            if (!support.noCloneChecked && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery2.isXMLDoc(elem)) {
              destElements = getAll(clone2);
              srcElements = getAll(elem);
              for (i2 = 0, l2 = srcElements.length; i2 < l2; i2++) {
                fixInput(srcElements[i2], destElements[i2]);
              }
            }
            if (dataAndEvents) {
              if (deepDataAndEvents) {
                srcElements = srcElements || getAll(elem);
                destElements = destElements || getAll(clone2);
                for (i2 = 0, l2 = srcElements.length; i2 < l2; i2++) {
                  cloneCopyEvent(srcElements[i2], destElements[i2]);
                }
              } else {
                cloneCopyEvent(elem, clone2);
              }
            }
            destElements = getAll(clone2, "script");
            if (destElements.length > 0) {
              setGlobalEval(destElements, !inPage && getAll(elem, "script"));
            }
            return clone2;
          },
          cleanData: function(elems) {
            var data, elem, type, special = jQuery2.event.special, i2 = 0;
            for (; (elem = elems[i2]) !== void 0; i2++) {
              if (acceptData(elem)) {
                if (data = elem[dataPriv.expando]) {
                  if (data.events) {
                    for (type in data.events) {
                      if (special[type]) {
                        jQuery2.event.remove(elem, type);
                      } else {
                        jQuery2.removeEvent(elem, type, data.handle);
                      }
                    }
                  }
                  elem[dataPriv.expando] = void 0;
                }
                if (elem[dataUser.expando]) {
                  elem[dataUser.expando] = void 0;
                }
              }
            }
          }
        });
        jQuery2.fn.extend({
          detach: function(selector) {
            return remove(this, selector, true);
          },
          remove: function(selector) {
            return remove(this, selector);
          },
          text: function(value) {
            return access(this, function(value2) {
              return value2 === void 0 ? jQuery2.text(this) : this.empty().each(function() {
                if (this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9) {
                  this.textContent = value2;
                }
              });
            }, null, value, arguments.length);
          },
          append: function() {
            return domManip(this, arguments, function(elem) {
              if (this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9) {
                var target = manipulationTarget(this, elem);
                target.appendChild(elem);
              }
            });
          },
          prepend: function() {
            return domManip(this, arguments, function(elem) {
              if (this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9) {
                var target = manipulationTarget(this, elem);
                target.insertBefore(elem, target.firstChild);
              }
            });
          },
          before: function() {
            return domManip(this, arguments, function(elem) {
              if (this.parentNode) {
                this.parentNode.insertBefore(elem, this);
              }
            });
          },
          after: function() {
            return domManip(this, arguments, function(elem) {
              if (this.parentNode) {
                this.parentNode.insertBefore(elem, this.nextSibling);
              }
            });
          },
          empty: function() {
            var elem, i2 = 0;
            for (; (elem = this[i2]) != null; i2++) {
              if (elem.nodeType === 1) {
                jQuery2.cleanData(getAll(elem, false));
                elem.textContent = "";
              }
            }
            return this;
          },
          clone: function(dataAndEvents, deepDataAndEvents) {
            dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
            deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
            return this.map(function() {
              return jQuery2.clone(this, dataAndEvents, deepDataAndEvents);
            });
          },
          html: function(value) {
            return access(this, function(value2) {
              var elem = this[0] || {}, i2 = 0, l2 = this.length;
              if (value2 === void 0 && elem.nodeType === 1) {
                return elem.innerHTML;
              }
              if (typeof value2 === "string" && !rnoInnerhtml.test(value2) && !wrapMap[(rtagName.exec(value2) || ["", ""])[1].toLowerCase()]) {
                value2 = jQuery2.htmlPrefilter(value2);
                try {
                  for (; i2 < l2; i2++) {
                    elem = this[i2] || {};
                    if (elem.nodeType === 1) {
                      jQuery2.cleanData(getAll(elem, false));
                      elem.innerHTML = value2;
                    }
                  }
                  elem = 0;
                } catch (e2) {
                }
              }
              if (elem) {
                this.empty().append(value2);
              }
            }, null, value, arguments.length);
          },
          replaceWith: function() {
            var ignored = [];
            return domManip(this, arguments, function(elem) {
              var parent = this.parentNode;
              if (jQuery2.inArray(this, ignored) < 0) {
                jQuery2.cleanData(getAll(this));
                if (parent) {
                  parent.replaceChild(elem, this);
                }
              }
            }, ignored);
          }
        });
        jQuery2.each({
          appendTo: "append",
          prependTo: "prepend",
          insertBefore: "before",
          insertAfter: "after",
          replaceAll: "replaceWith"
        }, function(name, original) {
          jQuery2.fn[name] = function(selector) {
            var elems, ret = [], insert = jQuery2(selector), last = insert.length - 1, i2 = 0;
            for (; i2 <= last; i2++) {
              elems = i2 === last ? this : this.clone(true);
              jQuery2(insert[i2])[original](elems);
              push.apply(ret, elems.get());
            }
            return this.pushStack(ret);
          };
        });
        var rnumnonpx = new RegExp("^(" + pnum + ")(?!px)[a-z%]+$", "i");
        var getStyles = function(elem) {
          var view = elem.ownerDocument.defaultView;
          if (!view || !view.opener) {
            view = window2;
          }
          return view.getComputedStyle(elem);
        };
        var swap2 = function(elem, options, callback2) {
          var ret, name, old = {};
          for (name in options) {
            old[name] = elem.style[name];
            elem.style[name] = options[name];
          }
          ret = callback2.call(elem);
          for (name in options) {
            elem.style[name] = old[name];
          }
          return ret;
        };
        var rboxStyle = new RegExp(cssExpand.join("|"), "i");
        (function() {
          function computeStyleTests() {
            if (!div) {
              return;
            }
            container.style.cssText = "position:absolute;left:-11111px;width:60px;margin-top:1px;padding:0;border:0";
            div.style.cssText = "position:relative;display:block;box-sizing:border-box;overflow:scroll;margin:auto;border:1px;padding:1px;width:60%;top:1%";
            documentElement.appendChild(container).appendChild(div);
            var divStyle = window2.getComputedStyle(div);
            pixelPositionVal = divStyle.top !== "1%";
            reliableMarginLeftVal = roundPixelMeasures(divStyle.marginLeft) === 12;
            div.style.right = "60%";
            pixelBoxStylesVal = roundPixelMeasures(divStyle.right) === 36;
            boxSizingReliableVal = roundPixelMeasures(divStyle.width) === 36;
            div.style.position = "absolute";
            scrollboxSizeVal = roundPixelMeasures(div.offsetWidth / 3) === 12;
            documentElement.removeChild(container);
            div = null;
          }
          function roundPixelMeasures(measure) {
            return Math.round(parseFloat(measure));
          }
          var pixelPositionVal, boxSizingReliableVal, scrollboxSizeVal, pixelBoxStylesVal, reliableTrDimensionsVal, reliableMarginLeftVal, container = document2.createElement("div"), div = document2.createElement("div");
          if (!div.style) {
            return;
          }
          div.style.backgroundClip = "content-box";
          div.cloneNode(true).style.backgroundClip = "";
          support.clearCloneStyle = div.style.backgroundClip === "content-box";
          jQuery2.extend(support, {
            boxSizingReliable: function() {
              computeStyleTests();
              return boxSizingReliableVal;
            },
            pixelBoxStyles: function() {
              computeStyleTests();
              return pixelBoxStylesVal;
            },
            pixelPosition: function() {
              computeStyleTests();
              return pixelPositionVal;
            },
            reliableMarginLeft: function() {
              computeStyleTests();
              return reliableMarginLeftVal;
            },
            scrollboxSize: function() {
              computeStyleTests();
              return scrollboxSizeVal;
            },
            reliableTrDimensions: function() {
              var table, tr, trChild, trStyle;
              if (reliableTrDimensionsVal == null) {
                table = document2.createElement("table");
                tr = document2.createElement("tr");
                trChild = document2.createElement("div");
                table.style.cssText = "position:absolute;left:-11111px;border-collapse:separate";
                tr.style.cssText = "border:1px solid";
                tr.style.height = "1px";
                trChild.style.height = "9px";
                trChild.style.display = "block";
                documentElement.appendChild(table).appendChild(tr).appendChild(trChild);
                trStyle = window2.getComputedStyle(tr);
                reliableTrDimensionsVal = parseInt(trStyle.height, 10) + parseInt(trStyle.borderTopWidth, 10) + parseInt(trStyle.borderBottomWidth, 10) === tr.offsetHeight;
                documentElement.removeChild(table);
              }
              return reliableTrDimensionsVal;
            }
          });
        })();
        function curCSS(elem, name, computed) {
          var width, minWidth, maxWidth, ret, style = elem.style;
          computed = computed || getStyles(elem);
          if (computed) {
            ret = computed.getPropertyValue(name) || computed[name];
            if (ret === "" && !isAttached(elem)) {
              ret = jQuery2.style(elem, name);
            }
            if (!support.pixelBoxStyles() && rnumnonpx.test(ret) && rboxStyle.test(name)) {
              width = style.width;
              minWidth = style.minWidth;
              maxWidth = style.maxWidth;
              style.minWidth = style.maxWidth = style.width = ret;
              ret = computed.width;
              style.width = width;
              style.minWidth = minWidth;
              style.maxWidth = maxWidth;
            }
          }
          return ret !== void 0 ? ret + "" : ret;
        }
        function addGetHookIf(conditionFn, hookFn) {
          return {
            get: function() {
              if (conditionFn()) {
                delete this.get;
                return;
              }
              return (this.get = hookFn).apply(this, arguments);
            }
          };
        }
        var cssPrefixes = ["Webkit", "Moz", "ms"], emptyStyle = document2.createElement("div").style, vendorProps = {};
        function vendorPropName(name) {
          var capName = name[0].toUpperCase() + name.slice(1), i2 = cssPrefixes.length;
          while (i2--) {
            name = cssPrefixes[i2] + capName;
            if (name in emptyStyle) {
              return name;
            }
          }
        }
        function finalPropName(name) {
          var final = jQuery2.cssProps[name] || vendorProps[name];
          if (final) {
            return final;
          }
          if (name in emptyStyle) {
            return name;
          }
          return vendorProps[name] = vendorPropName(name) || name;
        }
        var rdisplayswap = /^(none|table(?!-c[ea]).+)/, rcustomProp = /^--/, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = {
          letterSpacing: "0",
          fontWeight: "400"
        };
        function setPositiveNumber(_elem, value, subtract) {
          var matches = rcssNum.exec(value);
          return matches ? Math.max(0, matches[2] - (subtract || 0)) + (matches[3] || "px") : value;
        }
        function boxModelAdjustment(elem, dimension, box, isBorderBox, styles, computedVal) {
          var i2 = dimension === "width" ? 1 : 0, extra = 0, delta = 0;
          if (box === (isBorderBox ? "border" : "content")) {
            return 0;
          }
          for (; i2 < 4; i2 += 2) {
            if (box === "margin") {
              delta += jQuery2.css(elem, box + cssExpand[i2], true, styles);
            }
            if (!isBorderBox) {
              delta += jQuery2.css(elem, "padding" + cssExpand[i2], true, styles);
              if (box !== "padding") {
                delta += jQuery2.css(elem, "border" + cssExpand[i2] + "Width", true, styles);
              } else {
                extra += jQuery2.css(elem, "border" + cssExpand[i2] + "Width", true, styles);
              }
            } else {
              if (box === "content") {
                delta -= jQuery2.css(elem, "padding" + cssExpand[i2], true, styles);
              }
              if (box !== "margin") {
                delta -= jQuery2.css(elem, "border" + cssExpand[i2] + "Width", true, styles);
              }
            }
          }
          if (!isBorderBox && computedVal >= 0) {
            delta += Math.max(0, Math.ceil(elem["offset" + dimension[0].toUpperCase() + dimension.slice(1)] - computedVal - delta - extra - 0.5)) || 0;
          }
          return delta;
        }
        function getWidthOrHeight(elem, dimension, extra) {
          var styles = getStyles(elem), boxSizingNeeded = !support.boxSizingReliable() || extra, isBorderBox = boxSizingNeeded && jQuery2.css(elem, "boxSizing", false, styles) === "border-box", valueIsBorderBox = isBorderBox, val = curCSS(elem, dimension, styles), offsetProp = "offset" + dimension[0].toUpperCase() + dimension.slice(1);
          if (rnumnonpx.test(val)) {
            if (!extra) {
              return val;
            }
            val = "auto";
          }
          if ((!support.boxSizingReliable() && isBorderBox || !support.reliableTrDimensions() && nodeName(elem, "tr") || val === "auto" || !parseFloat(val) && jQuery2.css(elem, "display", false, styles) === "inline") && elem.getClientRects().length) {
            isBorderBox = jQuery2.css(elem, "boxSizing", false, styles) === "border-box";
            valueIsBorderBox = offsetProp in elem;
            if (valueIsBorderBox) {
              val = elem[offsetProp];
            }
          }
          val = parseFloat(val) || 0;
          return val + boxModelAdjustment(elem, dimension, extra || (isBorderBox ? "border" : "content"), valueIsBorderBox, styles, val) + "px";
        }
        jQuery2.extend({
          cssHooks: {
            opacity: {
              get: function(elem, computed) {
                if (computed) {
                  var ret = curCSS(elem, "opacity");
                  return ret === "" ? "1" : ret;
                }
              }
            }
          },
          cssNumber: {
            "animationIterationCount": true,
            "columnCount": true,
            "fillOpacity": true,
            "flexGrow": true,
            "flexShrink": true,
            "fontWeight": true,
            "gridArea": true,
            "gridColumn": true,
            "gridColumnEnd": true,
            "gridColumnStart": true,
            "gridRow": true,
            "gridRowEnd": true,
            "gridRowStart": true,
            "lineHeight": true,
            "opacity": true,
            "order": true,
            "orphans": true,
            "widows": true,
            "zIndex": true,
            "zoom": true
          },
          cssProps: {},
          style: function(elem, name, value, extra) {
            if (!elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style) {
              return;
            }
            var ret, type, hooks, origName = camelCase(name), isCustomProp = rcustomProp.test(name), style = elem.style;
            if (!isCustomProp) {
              name = finalPropName(origName);
            }
            hooks = jQuery2.cssHooks[name] || jQuery2.cssHooks[origName];
            if (value !== void 0) {
              type = typeof value;
              if (type === "string" && (ret = rcssNum.exec(value)) && ret[1]) {
                value = adjustCSS(elem, name, ret);
                type = "number";
              }
              if (value == null || value !== value) {
                return;
              }
              if (type === "number" && !isCustomProp) {
                value += ret && ret[3] || (jQuery2.cssNumber[origName] ? "" : "px");
              }
              if (!support.clearCloneStyle && value === "" && name.indexOf("background") === 0) {
                style[name] = "inherit";
              }
              if (!hooks || !("set" in hooks) || (value = hooks.set(elem, value, extra)) !== void 0) {
                if (isCustomProp) {
                  style.setProperty(name, value);
                } else {
                  style[name] = value;
                }
              }
            } else {
              if (hooks && "get" in hooks && (ret = hooks.get(elem, false, extra)) !== void 0) {
                return ret;
              }
              return style[name];
            }
          },
          css: function(elem, name, extra, styles) {
            var val, num, hooks, origName = camelCase(name), isCustomProp = rcustomProp.test(name);
            if (!isCustomProp) {
              name = finalPropName(origName);
            }
            hooks = jQuery2.cssHooks[name] || jQuery2.cssHooks[origName];
            if (hooks && "get" in hooks) {
              val = hooks.get(elem, true, extra);
            }
            if (val === void 0) {
              val = curCSS(elem, name, styles);
            }
            if (val === "normal" && name in cssNormalTransform) {
              val = cssNormalTransform[name];
            }
            if (extra === "" || extra) {
              num = parseFloat(val);
              return extra === true || isFinite(num) ? num || 0 : val;
            }
            return val;
          }
        });
        jQuery2.each(["height", "width"], function(_i2, dimension) {
          jQuery2.cssHooks[dimension] = {
            get: function(elem, computed, extra) {
              if (computed) {
                return rdisplayswap.test(jQuery2.css(elem, "display")) && (!elem.getClientRects().length || !elem.getBoundingClientRect().width) ? swap2(elem, cssShow, function() {
                  return getWidthOrHeight(elem, dimension, extra);
                }) : getWidthOrHeight(elem, dimension, extra);
              }
            },
            set: function(elem, value, extra) {
              var matches, styles = getStyles(elem), scrollboxSizeBuggy = !support.scrollboxSize() && styles.position === "absolute", boxSizingNeeded = scrollboxSizeBuggy || extra, isBorderBox = boxSizingNeeded && jQuery2.css(elem, "boxSizing", false, styles) === "border-box", subtract = extra ? boxModelAdjustment(elem, dimension, extra, isBorderBox, styles) : 0;
              if (isBorderBox && scrollboxSizeBuggy) {
                subtract -= Math.ceil(elem["offset" + dimension[0].toUpperCase() + dimension.slice(1)] - parseFloat(styles[dimension]) - boxModelAdjustment(elem, dimension, "border", false, styles) - 0.5);
              }
              if (subtract && (matches = rcssNum.exec(value)) && (matches[3] || "px") !== "px") {
                elem.style[dimension] = value;
                value = jQuery2.css(elem, dimension);
              }
              return setPositiveNumber(elem, value, subtract);
            }
          };
        });
        jQuery2.cssHooks.marginLeft = addGetHookIf(support.reliableMarginLeft, function(elem, computed) {
          if (computed) {
            return (parseFloat(curCSS(elem, "marginLeft")) || elem.getBoundingClientRect().left - swap2(elem, { marginLeft: 0 }, function() {
              return elem.getBoundingClientRect().left;
            })) + "px";
          }
        });
        jQuery2.each({
          margin: "",
          padding: "",
          border: "Width"
        }, function(prefix, suffix) {
          jQuery2.cssHooks[prefix + suffix] = {
            expand: function(value) {
              var i2 = 0, expanded = {}, parts = typeof value === "string" ? value.split(" ") : [value];
              for (; i2 < 4; i2++) {
                expanded[prefix + cssExpand[i2] + suffix] = parts[i2] || parts[i2 - 2] || parts[0];
              }
              return expanded;
            }
          };
          if (prefix !== "margin") {
            jQuery2.cssHooks[prefix + suffix].set = setPositiveNumber;
          }
        });
        jQuery2.fn.extend({
          css: function(name, value) {
            return access(this, function(elem, name2, value2) {
              var styles, len, map3 = {}, i2 = 0;
              if (Array.isArray(name2)) {
                styles = getStyles(elem);
                len = name2.length;
                for (; i2 < len; i2++) {
                  map3[name2[i2]] = jQuery2.css(elem, name2[i2], false, styles);
                }
                return map3;
              }
              return value2 !== void 0 ? jQuery2.style(elem, name2, value2) : jQuery2.css(elem, name2);
            }, name, value, arguments.length > 1);
          }
        });
        function Tween(elem, options, prop, end2, easing) {
          return new Tween.prototype.init(elem, options, prop, end2, easing);
        }
        jQuery2.Tween = Tween;
        Tween.prototype = {
          constructor: Tween,
          init: function(elem, options, prop, end2, easing, unit) {
            this.elem = elem;
            this.prop = prop;
            this.easing = easing || jQuery2.easing._default;
            this.options = options;
            this.start = this.now = this.cur();
            this.end = end2;
            this.unit = unit || (jQuery2.cssNumber[prop] ? "" : "px");
          },
          cur: function() {
            var hooks = Tween.propHooks[this.prop];
            return hooks && hooks.get ? hooks.get(this) : Tween.propHooks._default.get(this);
          },
          run: function(percent) {
            var eased, hooks = Tween.propHooks[this.prop];
            if (this.options.duration) {
              this.pos = eased = jQuery2.easing[this.easing](percent, this.options.duration * percent, 0, 1, this.options.duration);
            } else {
              this.pos = eased = percent;
            }
            this.now = (this.end - this.start) * eased + this.start;
            if (this.options.step) {
              this.options.step.call(this.elem, this.now, this);
            }
            if (hooks && hooks.set) {
              hooks.set(this);
            } else {
              Tween.propHooks._default.set(this);
            }
            return this;
          }
        };
        Tween.prototype.init.prototype = Tween.prototype;
        Tween.propHooks = {
          _default: {
            get: function(tween) {
              var result;
              if (tween.elem.nodeType !== 1 || tween.elem[tween.prop] != null && tween.elem.style[tween.prop] == null) {
                return tween.elem[tween.prop];
              }
              result = jQuery2.css(tween.elem, tween.prop, "");
              return !result || result === "auto" ? 0 : result;
            },
            set: function(tween) {
              if (jQuery2.fx.step[tween.prop]) {
                jQuery2.fx.step[tween.prop](tween);
              } else if (tween.elem.nodeType === 1 && (jQuery2.cssHooks[tween.prop] || tween.elem.style[finalPropName(tween.prop)] != null)) {
                jQuery2.style(tween.elem, tween.prop, tween.now + tween.unit);
              } else {
                tween.elem[tween.prop] = tween.now;
              }
            }
          }
        };
        Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
          set: function(tween) {
            if (tween.elem.nodeType && tween.elem.parentNode) {
              tween.elem[tween.prop] = tween.now;
            }
          }
        };
        jQuery2.easing = {
          linear: function(p2) {
            return p2;
          },
          swing: function(p2) {
            return 0.5 - Math.cos(p2 * Math.PI) / 2;
          },
          _default: "swing"
        };
        jQuery2.fx = Tween.prototype.init;
        jQuery2.fx.step = {};
        var fxNow, inProgress, rfxtypes = /^(?:toggle|show|hide)$/, rrun = /queueHooks$/;
        function schedule() {
          if (inProgress) {
            if (document2.hidden === false && window2.requestAnimationFrame) {
              window2.requestAnimationFrame(schedule);
            } else {
              window2.setTimeout(schedule, jQuery2.fx.interval);
            }
            jQuery2.fx.tick();
          }
        }
        function createFxNow() {
          window2.setTimeout(function() {
            fxNow = void 0;
          });
          return fxNow = Date.now();
        }
        function genFx(type, includeWidth) {
          var which, i2 = 0, attrs = { height: type };
          includeWidth = includeWidth ? 1 : 0;
          for (; i2 < 4; i2 += 2 - includeWidth) {
            which = cssExpand[i2];
            attrs["margin" + which] = attrs["padding" + which] = type;
          }
          if (includeWidth) {
            attrs.opacity = attrs.width = type;
          }
          return attrs;
        }
        function createTween(value, prop, animation) {
          var tween, collection = (Animation2.tweeners[prop] || []).concat(Animation2.tweeners["*"]), index = 0, length = collection.length;
          for (; index < length; index++) {
            if (tween = collection[index].call(animation, prop, value)) {
              return tween;
            }
          }
        }
        function defaultPrefilter(elem, props, opts) {
          var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display, isBox = "width" in props || "height" in props, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHiddenWithinTree(elem), dataShow = dataPriv.get(elem, "fxshow");
          if (!opts.queue) {
            hooks = jQuery2._queueHooks(elem, "fx");
            if (hooks.unqueued == null) {
              hooks.unqueued = 0;
              oldfire = hooks.empty.fire;
              hooks.empty.fire = function() {
                if (!hooks.unqueued) {
                  oldfire();
                }
              };
            }
            hooks.unqueued++;
            anim.always(function() {
              anim.always(function() {
                hooks.unqueued--;
                if (!jQuery2.queue(elem, "fx").length) {
                  hooks.empty.fire();
                }
              });
            });
          }
          for (prop in props) {
            value = props[prop];
            if (rfxtypes.test(value)) {
              delete props[prop];
              toggle = toggle || value === "toggle";
              if (value === (hidden ? "hide" : "show")) {
                if (value === "show" && dataShow && dataShow[prop] !== void 0) {
                  hidden = true;
                } else {
                  continue;
                }
              }
              orig[prop] = dataShow && dataShow[prop] || jQuery2.style(elem, prop);
            }
          }
          propTween = !jQuery2.isEmptyObject(props);
          if (!propTween && jQuery2.isEmptyObject(orig)) {
            return;
          }
          if (isBox && elem.nodeType === 1) {
            opts.overflow = [style.overflow, style.overflowX, style.overflowY];
            restoreDisplay = dataShow && dataShow.display;
            if (restoreDisplay == null) {
              restoreDisplay = dataPriv.get(elem, "display");
            }
            display = jQuery2.css(elem, "display");
            if (display === "none") {
              if (restoreDisplay) {
                display = restoreDisplay;
              } else {
                showHide([elem], true);
                restoreDisplay = elem.style.display || restoreDisplay;
                display = jQuery2.css(elem, "display");
                showHide([elem]);
              }
            }
            if (display === "inline" || display === "inline-block" && restoreDisplay != null) {
              if (jQuery2.css(elem, "float") === "none") {
                if (!propTween) {
                  anim.done(function() {
                    style.display = restoreDisplay;
                  });
                  if (restoreDisplay == null) {
                    display = style.display;
                    restoreDisplay = display === "none" ? "" : display;
                  }
                }
                style.display = "inline-block";
              }
            }
          }
          if (opts.overflow) {
            style.overflow = "hidden";
            anim.always(function() {
              style.overflow = opts.overflow[0];
              style.overflowX = opts.overflow[1];
              style.overflowY = opts.overflow[2];
            });
          }
          propTween = false;
          for (prop in orig) {
            if (!propTween) {
              if (dataShow) {
                if ("hidden" in dataShow) {
                  hidden = dataShow.hidden;
                }
              } else {
                dataShow = dataPriv.access(elem, "fxshow", { display: restoreDisplay });
              }
              if (toggle) {
                dataShow.hidden = !hidden;
              }
              if (hidden) {
                showHide([elem], true);
              }
              anim.done(function() {
                if (!hidden) {
                  showHide([elem]);
                }
                dataPriv.remove(elem, "fxshow");
                for (prop in orig) {
                  jQuery2.style(elem, prop, orig[prop]);
                }
              });
            }
            propTween = createTween(hidden ? dataShow[prop] : 0, prop, anim);
            if (!(prop in dataShow)) {
              dataShow[prop] = propTween.start;
              if (hidden) {
                propTween.end = propTween.start;
                propTween.start = 0;
              }
            }
          }
        }
        function propFilter(props, specialEasing) {
          var index, name, easing, value, hooks;
          for (index in props) {
            name = camelCase(index);
            easing = specialEasing[name];
            value = props[index];
            if (Array.isArray(value)) {
              easing = value[1];
              value = props[index] = value[0];
            }
            if (index !== name) {
              props[name] = value;
              delete props[index];
            }
            hooks = jQuery2.cssHooks[name];
            if (hooks && "expand" in hooks) {
              value = hooks.expand(value);
              delete props[name];
              for (index in value) {
                if (!(index in props)) {
                  props[index] = value[index];
                  specialEasing[index] = easing;
                }
              }
            } else {
              specialEasing[name] = easing;
            }
          }
        }
        function Animation2(elem, properties, options) {
          var result, stopped, index = 0, length = Animation2.prefilters.length, deferred = jQuery2.Deferred().always(function() {
            delete tick.elem;
          }), tick = function() {
            if (stopped) {
              return false;
            }
            var currentTime = fxNow || createFxNow(), remaining = Math.max(0, animation.startTime + animation.duration - currentTime), temp = remaining / animation.duration || 0, percent = 1 - temp, index2 = 0, length2 = animation.tweens.length;
            for (; index2 < length2; index2++) {
              animation.tweens[index2].run(percent);
            }
            deferred.notifyWith(elem, [animation, percent, remaining]);
            if (percent < 1 && length2) {
              return remaining;
            }
            if (!length2) {
              deferred.notifyWith(elem, [animation, 1, 0]);
            }
            deferred.resolveWith(elem, [animation]);
            return false;
          }, animation = deferred.promise({
            elem,
            props: jQuery2.extend({}, properties),
            opts: jQuery2.extend(true, {
              specialEasing: {},
              easing: jQuery2.easing._default
            }, options),
            originalProperties: properties,
            originalOptions: options,
            startTime: fxNow || createFxNow(),
            duration: options.duration,
            tweens: [],
            createTween: function(prop, end2) {
              var tween = jQuery2.Tween(elem, animation.opts, prop, end2, animation.opts.specialEasing[prop] || animation.opts.easing);
              animation.tweens.push(tween);
              return tween;
            },
            stop: function(gotoEnd) {
              var index2 = 0, length2 = gotoEnd ? animation.tweens.length : 0;
              if (stopped) {
                return this;
              }
              stopped = true;
              for (; index2 < length2; index2++) {
                animation.tweens[index2].run(1);
              }
              if (gotoEnd) {
                deferred.notifyWith(elem, [animation, 1, 0]);
                deferred.resolveWith(elem, [animation, gotoEnd]);
              } else {
                deferred.rejectWith(elem, [animation, gotoEnd]);
              }
              return this;
            }
          }), props = animation.props;
          propFilter(props, animation.opts.specialEasing);
          for (; index < length; index++) {
            result = Animation2.prefilters[index].call(animation, elem, props, animation.opts);
            if (result) {
              if (isFunction2(result.stop)) {
                jQuery2._queueHooks(animation.elem, animation.opts.queue).stop = result.stop.bind(result);
              }
              return result;
            }
          }
          jQuery2.map(props, createTween, animation);
          if (isFunction2(animation.opts.start)) {
            animation.opts.start.call(elem, animation);
          }
          animation.progress(animation.opts.progress).done(animation.opts.done, animation.opts.complete).fail(animation.opts.fail).always(animation.opts.always);
          jQuery2.fx.timer(jQuery2.extend(tick, {
            elem,
            anim: animation,
            queue: animation.opts.queue
          }));
          return animation;
        }
        jQuery2.Animation = jQuery2.extend(Animation2, {
          tweeners: {
            "*": [function(prop, value) {
              var tween = this.createTween(prop, value);
              adjustCSS(tween.elem, prop, rcssNum.exec(value), tween);
              return tween;
            }]
          },
          tweener: function(props, callback2) {
            if (isFunction2(props)) {
              callback2 = props;
              props = ["*"];
            } else {
              props = props.match(rnothtmlwhite);
            }
            var prop, index = 0, length = props.length;
            for (; index < length; index++) {
              prop = props[index];
              Animation2.tweeners[prop] = Animation2.tweeners[prop] || [];
              Animation2.tweeners[prop].unshift(callback2);
            }
          },
          prefilters: [defaultPrefilter],
          prefilter: function(callback2, prepend) {
            if (prepend) {
              Animation2.prefilters.unshift(callback2);
            } else {
              Animation2.prefilters.push(callback2);
            }
          }
        });
        jQuery2.speed = function(speed, easing, fn3) {
          var opt = speed && typeof speed === "object" ? jQuery2.extend({}, speed) : {
            complete: fn3 || !fn3 && easing || isFunction2(speed) && speed,
            duration: speed,
            easing: fn3 && easing || easing && !isFunction2(easing) && easing
          };
          if (jQuery2.fx.off) {
            opt.duration = 0;
          } else {
            if (typeof opt.duration !== "number") {
              if (opt.duration in jQuery2.fx.speeds) {
                opt.duration = jQuery2.fx.speeds[opt.duration];
              } else {
                opt.duration = jQuery2.fx.speeds._default;
              }
            }
          }
          if (opt.queue == null || opt.queue === true) {
            opt.queue = "fx";
          }
          opt.old = opt.complete;
          opt.complete = function() {
            if (isFunction2(opt.old)) {
              opt.old.call(this);
            }
            if (opt.queue) {
              jQuery2.dequeue(this, opt.queue);
            }
          };
          return opt;
        };
        jQuery2.fn.extend({
          fadeTo: function(speed, to, easing, callback2) {
            return this.filter(isHiddenWithinTree).css("opacity", 0).show().end().animate({ opacity: to }, speed, easing, callback2);
          },
          animate: function(prop, speed, easing, callback2) {
            var empty = jQuery2.isEmptyObject(prop), optall = jQuery2.speed(speed, easing, callback2), doAnimation = function() {
              var anim = Animation2(this, jQuery2.extend({}, prop), optall);
              if (empty || dataPriv.get(this, "finish")) {
                anim.stop(true);
              }
            };
            doAnimation.finish = doAnimation;
            return empty || optall.queue === false ? this.each(doAnimation) : this.queue(optall.queue, doAnimation);
          },
          stop: function(type, clearQueue, gotoEnd) {
            var stopQueue = function(hooks) {
              var stop = hooks.stop;
              delete hooks.stop;
              stop(gotoEnd);
            };
            if (typeof type !== "string") {
              gotoEnd = clearQueue;
              clearQueue = type;
              type = void 0;
            }
            if (clearQueue) {
              this.queue(type || "fx", []);
            }
            return this.each(function() {
              var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery2.timers, data = dataPriv.get(this);
              if (index) {
                if (data[index] && data[index].stop) {
                  stopQueue(data[index]);
                }
              } else {
                for (index in data) {
                  if (data[index] && data[index].stop && rrun.test(index)) {
                    stopQueue(data[index]);
                  }
                }
              }
              for (index = timers.length; index--; ) {
                if (timers[index].elem === this && (type == null || timers[index].queue === type)) {
                  timers[index].anim.stop(gotoEnd);
                  dequeue = false;
                  timers.splice(index, 1);
                }
              }
              if (dequeue || !gotoEnd) {
                jQuery2.dequeue(this, type);
              }
            });
          },
          finish: function(type) {
            if (type !== false) {
              type = type || "fx";
            }
            return this.each(function() {
              var index, data = dataPriv.get(this), queue = data[type + "queue"], hooks = data[type + "queueHooks"], timers = jQuery2.timers, length = queue ? queue.length : 0;
              data.finish = true;
              jQuery2.queue(this, type, []);
              if (hooks && hooks.stop) {
                hooks.stop.call(this, true);
              }
              for (index = timers.length; index--; ) {
                if (timers[index].elem === this && timers[index].queue === type) {
                  timers[index].anim.stop(true);
                  timers.splice(index, 1);
                }
              }
              for (index = 0; index < length; index++) {
                if (queue[index] && queue[index].finish) {
                  queue[index].finish.call(this);
                }
              }
              delete data.finish;
            });
          }
        });
        jQuery2.each(["toggle", "show", "hide"], function(_i2, name) {
          var cssFn = jQuery2.fn[name];
          jQuery2.fn[name] = function(speed, easing, callback2) {
            return speed == null || typeof speed === "boolean" ? cssFn.apply(this, arguments) : this.animate(genFx(name, true), speed, easing, callback2);
          };
        });
        jQuery2.each({
          slideDown: genFx("show"),
          slideUp: genFx("hide"),
          slideToggle: genFx("toggle"),
          fadeIn: { opacity: "show" },
          fadeOut: { opacity: "hide" },
          fadeToggle: { opacity: "toggle" }
        }, function(name, props) {
          jQuery2.fn[name] = function(speed, easing, callback2) {
            return this.animate(props, speed, easing, callback2);
          };
        });
        jQuery2.timers = [];
        jQuery2.fx.tick = function() {
          var timer, i2 = 0, timers = jQuery2.timers;
          fxNow = Date.now();
          for (; i2 < timers.length; i2++) {
            timer = timers[i2];
            if (!timer() && timers[i2] === timer) {
              timers.splice(i2--, 1);
            }
          }
          if (!timers.length) {
            jQuery2.fx.stop();
          }
          fxNow = void 0;
        };
        jQuery2.fx.timer = function(timer) {
          jQuery2.timers.push(timer);
          jQuery2.fx.start();
        };
        jQuery2.fx.interval = 13;
        jQuery2.fx.start = function() {
          if (inProgress) {
            return;
          }
          inProgress = true;
          schedule();
        };
        jQuery2.fx.stop = function() {
          inProgress = null;
        };
        jQuery2.fx.speeds = {
          slow: 600,
          fast: 200,
          _default: 400
        };
        jQuery2.fn.delay = function(time, type) {
          time = jQuery2.fx ? jQuery2.fx.speeds[time] || time : time;
          type = type || "fx";
          return this.queue(type, function(next, hooks) {
            var timeout = window2.setTimeout(next, time);
            hooks.stop = function() {
              window2.clearTimeout(timeout);
            };
          });
        };
        (function() {
          var input = document2.createElement("input"), select = document2.createElement("select"), opt = select.appendChild(document2.createElement("option"));
          input.type = "checkbox";
          support.checkOn = input.value !== "";
          support.optSelected = opt.selected;
          input = document2.createElement("input");
          input.value = "t";
          input.type = "radio";
          support.radioValue = input.value === "t";
        })();
        var boolHook, attrHandle = jQuery2.expr.attrHandle;
        jQuery2.fn.extend({
          attr: function(name, value) {
            return access(this, jQuery2.attr, name, value, arguments.length > 1);
          },
          removeAttr: function(name) {
            return this.each(function() {
              jQuery2.removeAttr(this, name);
            });
          }
        });
        jQuery2.extend({
          attr: function(elem, name, value) {
            var ret, hooks, nType = elem.nodeType;
            if (nType === 3 || nType === 8 || nType === 2) {
              return;
            }
            if (typeof elem.getAttribute === "undefined") {
              return jQuery2.prop(elem, name, value);
            }
            if (nType !== 1 || !jQuery2.isXMLDoc(elem)) {
              hooks = jQuery2.attrHooks[name.toLowerCase()] || (jQuery2.expr.match.bool.test(name) ? boolHook : void 0);
            }
            if (value !== void 0) {
              if (value === null) {
                jQuery2.removeAttr(elem, name);
                return;
              }
              if (hooks && "set" in hooks && (ret = hooks.set(elem, value, name)) !== void 0) {
                return ret;
              }
              elem.setAttribute(name, value + "");
              return value;
            }
            if (hooks && "get" in hooks && (ret = hooks.get(elem, name)) !== null) {
              return ret;
            }
            ret = jQuery2.find.attr(elem, name);
            return ret == null ? void 0 : ret;
          },
          attrHooks: {
            type: {
              set: function(elem, value) {
                if (!support.radioValue && value === "radio" && nodeName(elem, "input")) {
                  var val = elem.value;
                  elem.setAttribute("type", value);
                  if (val) {
                    elem.value = val;
                  }
                  return value;
                }
              }
            }
          },
          removeAttr: function(elem, value) {
            var name, i2 = 0, attrNames = value && value.match(rnothtmlwhite);
            if (attrNames && elem.nodeType === 1) {
              while (name = attrNames[i2++]) {
                elem.removeAttribute(name);
              }
            }
          }
        });
        boolHook = {
          set: function(elem, value, name) {
            if (value === false) {
              jQuery2.removeAttr(elem, name);
            } else {
              elem.setAttribute(name, name);
            }
            return name;
          }
        };
        jQuery2.each(jQuery2.expr.match.bool.source.match(/\w+/g), function(_i2, name) {
          var getter = attrHandle[name] || jQuery2.find.attr;
          attrHandle[name] = function(elem, name2, isXML) {
            var ret, handle, lowercaseName = name2.toLowerCase();
            if (!isXML) {
              handle = attrHandle[lowercaseName];
              attrHandle[lowercaseName] = ret;
              ret = getter(elem, name2, isXML) != null ? lowercaseName : null;
              attrHandle[lowercaseName] = handle;
            }
            return ret;
          };
        });
        var rfocusable = /^(?:input|select|textarea|button)$/i, rclickable = /^(?:a|area)$/i;
        jQuery2.fn.extend({
          prop: function(name, value) {
            return access(this, jQuery2.prop, name, value, arguments.length > 1);
          },
          removeProp: function(name) {
            return this.each(function() {
              delete this[jQuery2.propFix[name] || name];
            });
          }
        });
        jQuery2.extend({
          prop: function(elem, name, value) {
            var ret, hooks, nType = elem.nodeType;
            if (nType === 3 || nType === 8 || nType === 2) {
              return;
            }
            if (nType !== 1 || !jQuery2.isXMLDoc(elem)) {
              name = jQuery2.propFix[name] || name;
              hooks = jQuery2.propHooks[name];
            }
            if (value !== void 0) {
              if (hooks && "set" in hooks && (ret = hooks.set(elem, value, name)) !== void 0) {
                return ret;
              }
              return elem[name] = value;
            }
            if (hooks && "get" in hooks && (ret = hooks.get(elem, name)) !== null) {
              return ret;
            }
            return elem[name];
          },
          propHooks: {
            tabIndex: {
              get: function(elem) {
                var tabindex = jQuery2.find.attr(elem, "tabindex");
                if (tabindex) {
                  return parseInt(tabindex, 10);
                }
                if (rfocusable.test(elem.nodeName) || rclickable.test(elem.nodeName) && elem.href) {
                  return 0;
                }
                return -1;
              }
            }
          },
          propFix: {
            "for": "htmlFor",
            "class": "className"
          }
        });
        if (!support.optSelected) {
          jQuery2.propHooks.selected = {
            get: function(elem) {
              var parent = elem.parentNode;
              if (parent && parent.parentNode) {
                parent.parentNode.selectedIndex;
              }
              return null;
            },
            set: function(elem) {
              var parent = elem.parentNode;
              if (parent) {
                parent.selectedIndex;
                if (parent.parentNode) {
                  parent.parentNode.selectedIndex;
                }
              }
            }
          };
        }
        jQuery2.each([
          "tabIndex",
          "readOnly",
          "maxLength",
          "cellSpacing",
          "cellPadding",
          "rowSpan",
          "colSpan",
          "useMap",
          "frameBorder",
          "contentEditable"
        ], function() {
          jQuery2.propFix[this.toLowerCase()] = this;
        });
        function stripAndCollapse(value) {
          var tokens = value.match(rnothtmlwhite) || [];
          return tokens.join(" ");
        }
        function getClass(elem) {
          return elem.getAttribute && elem.getAttribute("class") || "";
        }
        function classesToArray(value) {
          if (Array.isArray(value)) {
            return value;
          }
          if (typeof value === "string") {
            return value.match(rnothtmlwhite) || [];
          }
          return [];
        }
        jQuery2.fn.extend({
          addClass: function(value) {
            var classes, elem, cur, curValue, clazz, j2, finalValue, i2 = 0;
            if (isFunction2(value)) {
              return this.each(function(j3) {
                jQuery2(this).addClass(value.call(this, j3, getClass(this)));
              });
            }
            classes = classesToArray(value);
            if (classes.length) {
              while (elem = this[i2++]) {
                curValue = getClass(elem);
                cur = elem.nodeType === 1 && " " + stripAndCollapse(curValue) + " ";
                if (cur) {
                  j2 = 0;
                  while (clazz = classes[j2++]) {
                    if (cur.indexOf(" " + clazz + " ") < 0) {
                      cur += clazz + " ";
                    }
                  }
                  finalValue = stripAndCollapse(cur);
                  if (curValue !== finalValue) {
                    elem.setAttribute("class", finalValue);
                  }
                }
              }
            }
            return this;
          },
          removeClass: function(value) {
            var classes, elem, cur, curValue, clazz, j2, finalValue, i2 = 0;
            if (isFunction2(value)) {
              return this.each(function(j3) {
                jQuery2(this).removeClass(value.call(this, j3, getClass(this)));
              });
            }
            if (!arguments.length) {
              return this.attr("class", "");
            }
            classes = classesToArray(value);
            if (classes.length) {
              while (elem = this[i2++]) {
                curValue = getClass(elem);
                cur = elem.nodeType === 1 && " " + stripAndCollapse(curValue) + " ";
                if (cur) {
                  j2 = 0;
                  while (clazz = classes[j2++]) {
                    while (cur.indexOf(" " + clazz + " ") > -1) {
                      cur = cur.replace(" " + clazz + " ", " ");
                    }
                  }
                  finalValue = stripAndCollapse(cur);
                  if (curValue !== finalValue) {
                    elem.setAttribute("class", finalValue);
                  }
                }
              }
            }
            return this;
          },
          toggleClass: function(value, stateVal) {
            var type = typeof value, isValidValue = type === "string" || Array.isArray(value);
            if (typeof stateVal === "boolean" && isValidValue) {
              return stateVal ? this.addClass(value) : this.removeClass(value);
            }
            if (isFunction2(value)) {
              return this.each(function(i2) {
                jQuery2(this).toggleClass(value.call(this, i2, getClass(this), stateVal), stateVal);
              });
            }
            return this.each(function() {
              var className, i2, self2, classNames;
              if (isValidValue) {
                i2 = 0;
                self2 = jQuery2(this);
                classNames = classesToArray(value);
                while (className = classNames[i2++]) {
                  if (self2.hasClass(className)) {
                    self2.removeClass(className);
                  } else {
                    self2.addClass(className);
                  }
                }
              } else if (value === void 0 || type === "boolean") {
                className = getClass(this);
                if (className) {
                  dataPriv.set(this, "__className__", className);
                }
                if (this.setAttribute) {
                  this.setAttribute("class", className || value === false ? "" : dataPriv.get(this, "__className__") || "");
                }
              }
            });
          },
          hasClass: function(selector) {
            var className, elem, i2 = 0;
            className = " " + selector + " ";
            while (elem = this[i2++]) {
              if (elem.nodeType === 1 && (" " + stripAndCollapse(getClass(elem)) + " ").indexOf(className) > -1) {
                return true;
              }
            }
            return false;
          }
        });
        var rreturn = /\r/g;
        jQuery2.fn.extend({
          val: function(value) {
            var hooks, ret, valueIsFunction, elem = this[0];
            if (!arguments.length) {
              if (elem) {
                hooks = jQuery2.valHooks[elem.type] || jQuery2.valHooks[elem.nodeName.toLowerCase()];
                if (hooks && "get" in hooks && (ret = hooks.get(elem, "value")) !== void 0) {
                  return ret;
                }
                ret = elem.value;
                if (typeof ret === "string") {
                  return ret.replace(rreturn, "");
                }
                return ret == null ? "" : ret;
              }
              return;
            }
            valueIsFunction = isFunction2(value);
            return this.each(function(i2) {
              var val;
              if (this.nodeType !== 1) {
                return;
              }
              if (valueIsFunction) {
                val = value.call(this, i2, jQuery2(this).val());
              } else {
                val = value;
              }
              if (val == null) {
                val = "";
              } else if (typeof val === "number") {
                val += "";
              } else if (Array.isArray(val)) {
                val = jQuery2.map(val, function(value2) {
                  return value2 == null ? "" : value2 + "";
                });
              }
              hooks = jQuery2.valHooks[this.type] || jQuery2.valHooks[this.nodeName.toLowerCase()];
              if (!hooks || !("set" in hooks) || hooks.set(this, val, "value") === void 0) {
                this.value = val;
              }
            });
          }
        });
        jQuery2.extend({
          valHooks: {
            option: {
              get: function(elem) {
                var val = jQuery2.find.attr(elem, "value");
                return val != null ? val : stripAndCollapse(jQuery2.text(elem));
              }
            },
            select: {
              get: function(elem) {
                var value, option, i2, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one", values = one ? null : [], max2 = one ? index + 1 : options.length;
                if (index < 0) {
                  i2 = max2;
                } else {
                  i2 = one ? index : 0;
                }
                for (; i2 < max2; i2++) {
                  option = options[i2];
                  if ((option.selected || i2 === index) && !option.disabled && (!option.parentNode.disabled || !nodeName(option.parentNode, "optgroup"))) {
                    value = jQuery2(option).val();
                    if (one) {
                      return value;
                    }
                    values.push(value);
                  }
                }
                return values;
              },
              set: function(elem, value) {
                var optionSet, option, options = elem.options, values = jQuery2.makeArray(value), i2 = options.length;
                while (i2--) {
                  option = options[i2];
                  if (option.selected = jQuery2.inArray(jQuery2.valHooks.option.get(option), values) > -1) {
                    optionSet = true;
                  }
                }
                if (!optionSet) {
                  elem.selectedIndex = -1;
                }
                return values;
              }
            }
          }
        });
        jQuery2.each(["radio", "checkbox"], function() {
          jQuery2.valHooks[this] = {
            set: function(elem, value) {
              if (Array.isArray(value)) {
                return elem.checked = jQuery2.inArray(jQuery2(elem).val(), value) > -1;
              }
            }
          };
          if (!support.checkOn) {
            jQuery2.valHooks[this].get = function(elem) {
              return elem.getAttribute("value") === null ? "on" : elem.value;
            };
          }
        });
        support.focusin = "onfocusin" in window2;
        var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, stopPropagationCallback = function(e2) {
          e2.stopPropagation();
        };
        jQuery2.extend(jQuery2.event, {
          trigger: function(event, data, elem, onlyHandlers) {
            var i2, cur, tmp, bubbleType, ontype, handle, special, lastElement, eventPath = [elem || document2], type = hasOwn.call(event, "type") ? event.type : event, namespaces = hasOwn.call(event, "namespace") ? event.namespace.split(".") : [];
            cur = lastElement = tmp = elem = elem || document2;
            if (elem.nodeType === 3 || elem.nodeType === 8) {
              return;
            }
            if (rfocusMorph.test(type + jQuery2.event.triggered)) {
              return;
            }
            if (type.indexOf(".") > -1) {
              namespaces = type.split(".");
              type = namespaces.shift();
              namespaces.sort();
            }
            ontype = type.indexOf(":") < 0 && "on" + type;
            event = event[jQuery2.expando] ? event : new jQuery2.Event(type, typeof event === "object" && event);
            event.isTrigger = onlyHandlers ? 2 : 3;
            event.namespace = namespaces.join(".");
            event.rnamespace = event.namespace ? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") : null;
            event.result = void 0;
            if (!event.target) {
              event.target = elem;
            }
            data = data == null ? [event] : jQuery2.makeArray(data, [event]);
            special = jQuery2.event.special[type] || {};
            if (!onlyHandlers && special.trigger && special.trigger.apply(elem, data) === false) {
              return;
            }
            if (!onlyHandlers && !special.noBubble && !isWindow(elem)) {
              bubbleType = special.delegateType || type;
              if (!rfocusMorph.test(bubbleType + type)) {
                cur = cur.parentNode;
              }
              for (; cur; cur = cur.parentNode) {
                eventPath.push(cur);
                tmp = cur;
              }
              if (tmp === (elem.ownerDocument || document2)) {
                eventPath.push(tmp.defaultView || tmp.parentWindow || window2);
              }
            }
            i2 = 0;
            while ((cur = eventPath[i2++]) && !event.isPropagationStopped()) {
              lastElement = cur;
              event.type = i2 > 1 ? bubbleType : special.bindType || type;
              handle = (dataPriv.get(cur, "events") || /* @__PURE__ */ Object.create(null))[event.type] && dataPriv.get(cur, "handle");
              if (handle) {
                handle.apply(cur, data);
              }
              handle = ontype && cur[ontype];
              if (handle && handle.apply && acceptData(cur)) {
                event.result = handle.apply(cur, data);
                if (event.result === false) {
                  event.preventDefault();
                }
              }
            }
            event.type = type;
            if (!onlyHandlers && !event.isDefaultPrevented()) {
              if ((!special._default || special._default.apply(eventPath.pop(), data) === false) && acceptData(elem)) {
                if (ontype && isFunction2(elem[type]) && !isWindow(elem)) {
                  tmp = elem[ontype];
                  if (tmp) {
                    elem[ontype] = null;
                  }
                  jQuery2.event.triggered = type;
                  if (event.isPropagationStopped()) {
                    lastElement.addEventListener(type, stopPropagationCallback);
                  }
                  elem[type]();
                  if (event.isPropagationStopped()) {
                    lastElement.removeEventListener(type, stopPropagationCallback);
                  }
                  jQuery2.event.triggered = void 0;
                  if (tmp) {
                    elem[ontype] = tmp;
                  }
                }
              }
            }
            return event.result;
          },
          simulate: function(type, elem, event) {
            var e2 = jQuery2.extend(new jQuery2.Event(), event, {
              type,
              isSimulated: true
            });
            jQuery2.event.trigger(e2, null, elem);
          }
        });
        jQuery2.fn.extend({
          trigger: function(type, data) {
            return this.each(function() {
              jQuery2.event.trigger(type, data, this);
            });
          },
          triggerHandler: function(type, data) {
            var elem = this[0];
            if (elem) {
              return jQuery2.event.trigger(type, data, elem, true);
            }
          }
        });
        if (!support.focusin) {
          jQuery2.each({ focus: "focusin", blur: "focusout" }, function(orig, fix) {
            var handler = function(event) {
              jQuery2.event.simulate(fix, event.target, jQuery2.event.fix(event));
            };
            jQuery2.event.special[fix] = {
              setup: function() {
                var doc = this.ownerDocument || this.document || this, attaches = dataPriv.access(doc, fix);
                if (!attaches) {
                  doc.addEventListener(orig, handler, true);
                }
                dataPriv.access(doc, fix, (attaches || 0) + 1);
              },
              teardown: function() {
                var doc = this.ownerDocument || this.document || this, attaches = dataPriv.access(doc, fix) - 1;
                if (!attaches) {
                  doc.removeEventListener(orig, handler, true);
                  dataPriv.remove(doc, fix);
                } else {
                  dataPriv.access(doc, fix, attaches);
                }
              }
            };
          });
        }
        var location2 = window2.location;
        var nonce = { guid: Date.now() };
        var rquery = /\?/;
        jQuery2.parseXML = function(data) {
          var xml, parserErrorElem;
          if (!data || typeof data !== "string") {
            return null;
          }
          try {
            xml = new window2.DOMParser().parseFromString(data, "text/xml");
          } catch (e2) {
          }
          parserErrorElem = xml && xml.getElementsByTagName("parsererror")[0];
          if (!xml || parserErrorElem) {
            jQuery2.error("Invalid XML: " + (parserErrorElem ? jQuery2.map(parserErrorElem.childNodes, function(el) {
              return el.textContent;
            }).join("\n") : data));
          }
          return xml;
        };
        var rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i;
        function buildParams(prefix, obj, traditional, add3) {
          var name;
          if (Array.isArray(obj)) {
            jQuery2.each(obj, function(i2, v2) {
              if (traditional || rbracket.test(prefix)) {
                add3(prefix, v2);
              } else {
                buildParams(prefix + "[" + (typeof v2 === "object" && v2 != null ? i2 : "") + "]", v2, traditional, add3);
              }
            });
          } else if (!traditional && toType2(obj) === "object") {
            for (name in obj) {
              buildParams(prefix + "[" + name + "]", obj[name], traditional, add3);
            }
          } else {
            add3(prefix, obj);
          }
        }
        jQuery2.param = function(a2, traditional) {
          var prefix, s2 = [], add3 = function(key, valueOrFunction) {
            var value = isFunction2(valueOrFunction) ? valueOrFunction() : valueOrFunction;
            s2[s2.length] = encodeURIComponent(key) + "=" + encodeURIComponent(value == null ? "" : value);
          };
          if (a2 == null) {
            return "";
          }
          if (Array.isArray(a2) || a2.jquery && !jQuery2.isPlainObject(a2)) {
            jQuery2.each(a2, function() {
              add3(this.name, this.value);
            });
          } else {
            for (prefix in a2) {
              buildParams(prefix, a2[prefix], traditional, add3);
            }
          }
          return s2.join("&");
        };
        jQuery2.fn.extend({
          serialize: function() {
            return jQuery2.param(this.serializeArray());
          },
          serializeArray: function() {
            return this.map(function() {
              var elements2 = jQuery2.prop(this, "elements");
              return elements2 ? jQuery2.makeArray(elements2) : this;
            }).filter(function() {
              var type = this.type;
              return this.name && !jQuery2(this).is(":disabled") && rsubmittable.test(this.nodeName) && !rsubmitterTypes.test(type) && (this.checked || !rcheckableType.test(type));
            }).map(function(_i2, elem) {
              var val = jQuery2(this).val();
              if (val == null) {
                return null;
              }
              if (Array.isArray(val)) {
                return jQuery2.map(val, function(val2) {
                  return { name: elem.name, value: val2.replace(rCRLF, "\r\n") };
                });
              }
              return { name: elem.name, value: val.replace(rCRLF, "\r\n") };
            }).get();
          }
        });
        var r20 = /%20/g, rhash = /#.*$/, rantiCache = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, prefilters = {}, transports = {}, allTypes = "*/".concat("*"), originAnchor = document2.createElement("a");
        originAnchor.href = location2.href;
        function addToPrefiltersOrTransports(structure) {
          return function(dataTypeExpression, func) {
            if (typeof dataTypeExpression !== "string") {
              func = dataTypeExpression;
              dataTypeExpression = "*";
            }
            var dataType, i2 = 0, dataTypes = dataTypeExpression.toLowerCase().match(rnothtmlwhite) || [];
            if (isFunction2(func)) {
              while (dataType = dataTypes[i2++]) {
                if (dataType[0] === "+") {
                  dataType = dataType.slice(1) || "*";
                  (structure[dataType] = structure[dataType] || []).unshift(func);
                } else {
                  (structure[dataType] = structure[dataType] || []).push(func);
                }
              }
            }
          };
        }
        function inspectPrefiltersOrTransports(structure, options, originalOptions, jqXHR) {
          var inspected = {}, seekingTransport = structure === transports;
          function inspect(dataType) {
            var selected;
            inspected[dataType] = true;
            jQuery2.each(structure[dataType] || [], function(_2, prefilterOrFactory) {
              var dataTypeOrTransport = prefilterOrFactory(options, originalOptions, jqXHR);
              if (typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[dataTypeOrTransport]) {
                options.dataTypes.unshift(dataTypeOrTransport);
                inspect(dataTypeOrTransport);
                return false;
              } else if (seekingTransport) {
                return !(selected = dataTypeOrTransport);
              }
            });
            return selected;
          }
          return inspect(options.dataTypes[0]) || !inspected["*"] && inspect("*");
        }
        function ajaxExtend(target, src) {
          var key, deep, flatOptions = jQuery2.ajaxSettings.flatOptions || {};
          for (key in src) {
            if (src[key] !== void 0) {
              (flatOptions[key] ? target : deep || (deep = {}))[key] = src[key];
            }
          }
          if (deep) {
            jQuery2.extend(true, target, deep);
          }
          return target;
        }
        function ajaxHandleResponses(s2, jqXHR, responses) {
          var ct2, type, finalDataType, firstDataType, contents = s2.contents, dataTypes = s2.dataTypes;
          while (dataTypes[0] === "*") {
            dataTypes.shift();
            if (ct2 === void 0) {
              ct2 = s2.mimeType || jqXHR.getResponseHeader("Content-Type");
            }
          }
          if (ct2) {
            for (type in contents) {
              if (contents[type] && contents[type].test(ct2)) {
                dataTypes.unshift(type);
                break;
              }
            }
          }
          if (dataTypes[0] in responses) {
            finalDataType = dataTypes[0];
          } else {
            for (type in responses) {
              if (!dataTypes[0] || s2.converters[type + " " + dataTypes[0]]) {
                finalDataType = type;
                break;
              }
              if (!firstDataType) {
                firstDataType = type;
              }
            }
            finalDataType = finalDataType || firstDataType;
          }
          if (finalDataType) {
            if (finalDataType !== dataTypes[0]) {
              dataTypes.unshift(finalDataType);
            }
            return responses[finalDataType];
          }
        }
        function ajaxConvert(s2, response, jqXHR, isSuccess) {
          var conv2, current, conv, tmp, prev, converters = {}, dataTypes = s2.dataTypes.slice();
          if (dataTypes[1]) {
            for (conv in s2.converters) {
              converters[conv.toLowerCase()] = s2.converters[conv];
            }
          }
          current = dataTypes.shift();
          while (current) {
            if (s2.responseFields[current]) {
              jqXHR[s2.responseFields[current]] = response;
            }
            if (!prev && isSuccess && s2.dataFilter) {
              response = s2.dataFilter(response, s2.dataType);
            }
            prev = current;
            current = dataTypes.shift();
            if (current) {
              if (current === "*") {
                current = prev;
              } else if (prev !== "*" && prev !== current) {
                conv = converters[prev + " " + current] || converters["* " + current];
                if (!conv) {
                  for (conv2 in converters) {
                    tmp = conv2.split(" ");
                    if (tmp[1] === current) {
                      conv = converters[prev + " " + tmp[0]] || converters["* " + tmp[0]];
                      if (conv) {
                        if (conv === true) {
                          conv = converters[conv2];
                        } else if (converters[conv2] !== true) {
                          current = tmp[0];
                          dataTypes.unshift(tmp[1]);
                        }
                        break;
                      }
                    }
                  }
                }
                if (conv !== true) {
                  if (conv && s2.throws) {
                    response = conv(response);
                  } else {
                    try {
                      response = conv(response);
                    } catch (e2) {
                      return {
                        state: "parsererror",
                        error: conv ? e2 : "No conversion from " + prev + " to " + current
                      };
                    }
                  }
                }
              }
            }
          }
          return { state: "success", data: response };
        }
        jQuery2.extend({
          active: 0,
          lastModified: {},
          etag: {},
          ajaxSettings: {
            url: location2.href,
            type: "GET",
            isLocal: rlocalProtocol.test(location2.protocol),
            global: true,
            processData: true,
            async: true,
            contentType: "application/x-www-form-urlencoded; charset=UTF-8",
            accepts: {
              "*": allTypes,
              text: "text/plain",
              html: "text/html",
              xml: "application/xml, text/xml",
              json: "application/json, text/javascript"
            },
            contents: {
              xml: /\bxml\b/,
              html: /\bhtml/,
              json: /\bjson\b/
            },
            responseFields: {
              xml: "responseXML",
              text: "responseText",
              json: "responseJSON"
            },
            converters: {
              "* text": String,
              "text html": true,
              "text json": JSON.parse,
              "text xml": jQuery2.parseXML
            },
            flatOptions: {
              url: true,
              context: true
            }
          },
          ajaxSetup: function(target, settings) {
            return settings ? ajaxExtend(ajaxExtend(target, jQuery2.ajaxSettings), settings) : ajaxExtend(jQuery2.ajaxSettings, target);
          },
          ajaxPrefilter: addToPrefiltersOrTransports(prefilters),
          ajaxTransport: addToPrefiltersOrTransports(transports),
          ajax: function(url, options) {
            if (typeof url === "object") {
              options = url;
              url = void 0;
            }
            options = options || {};
            var transport, cacheURL, responseHeadersString, responseHeaders, timeoutTimer, urlAnchor, completed2, fireGlobals, i2, uncached, s2 = jQuery2.ajaxSetup({}, options), callbackContext = s2.context || s2, globalEventContext = s2.context && (callbackContext.nodeType || callbackContext.jquery) ? jQuery2(callbackContext) : jQuery2.event, deferred = jQuery2.Deferred(), completeDeferred = jQuery2.Callbacks("once memory"), statusCode = s2.statusCode || {}, requestHeaders = {}, requestHeadersNames = {}, strAbort = "canceled", jqXHR = {
              readyState: 0,
              getResponseHeader: function(key) {
                var match2;
                if (completed2) {
                  if (!responseHeaders) {
                    responseHeaders = {};
                    while (match2 = rheaders.exec(responseHeadersString)) {
                      responseHeaders[match2[1].toLowerCase() + " "] = (responseHeaders[match2[1].toLowerCase() + " "] || []).concat(match2[2]);
                    }
                  }
                  match2 = responseHeaders[key.toLowerCase() + " "];
                }
                return match2 == null ? null : match2.join(", ");
              },
              getAllResponseHeaders: function() {
                return completed2 ? responseHeadersString : null;
              },
              setRequestHeader: function(name, value) {
                if (completed2 == null) {
                  name = requestHeadersNames[name.toLowerCase()] = requestHeadersNames[name.toLowerCase()] || name;
                  requestHeaders[name] = value;
                }
                return this;
              },
              overrideMimeType: function(type) {
                if (completed2 == null) {
                  s2.mimeType = type;
                }
                return this;
              },
              statusCode: function(map3) {
                var code;
                if (map3) {
                  if (completed2) {
                    jqXHR.always(map3[jqXHR.status]);
                  } else {
                    for (code in map3) {
                      statusCode[code] = [statusCode[code], map3[code]];
                    }
                  }
                }
                return this;
              },
              abort: function(statusText) {
                var finalText = statusText || strAbort;
                if (transport) {
                  transport.abort(finalText);
                }
                done(0, finalText);
                return this;
              }
            };
            deferred.promise(jqXHR);
            s2.url = ((url || s2.url || location2.href) + "").replace(rprotocol, location2.protocol + "//");
            s2.type = options.method || options.type || s2.method || s2.type;
            s2.dataTypes = (s2.dataType || "*").toLowerCase().match(rnothtmlwhite) || [""];
            if (s2.crossDomain == null) {
              urlAnchor = document2.createElement("a");
              try {
                urlAnchor.href = s2.url;
                urlAnchor.href = urlAnchor.href;
                s2.crossDomain = originAnchor.protocol + "//" + originAnchor.host !== urlAnchor.protocol + "//" + urlAnchor.host;
              } catch (e2) {
                s2.crossDomain = true;
              }
            }
            if (s2.data && s2.processData && typeof s2.data !== "string") {
              s2.data = jQuery2.param(s2.data, s2.traditional);
            }
            inspectPrefiltersOrTransports(prefilters, s2, options, jqXHR);
            if (completed2) {
              return jqXHR;
            }
            fireGlobals = jQuery2.event && s2.global;
            if (fireGlobals && jQuery2.active++ === 0) {
              jQuery2.event.trigger("ajaxStart");
            }
            s2.type = s2.type.toUpperCase();
            s2.hasContent = !rnoContent.test(s2.type);
            cacheURL = s2.url.replace(rhash, "");
            if (!s2.hasContent) {
              uncached = s2.url.slice(cacheURL.length);
              if (s2.data && (s2.processData || typeof s2.data === "string")) {
                cacheURL += (rquery.test(cacheURL) ? "&" : "?") + s2.data;
                delete s2.data;
              }
              if (s2.cache === false) {
                cacheURL = cacheURL.replace(rantiCache, "$1");
                uncached = (rquery.test(cacheURL) ? "&" : "?") + "_=" + nonce.guid++ + uncached;
              }
              s2.url = cacheURL + uncached;
            } else if (s2.data && s2.processData && (s2.contentType || "").indexOf("application/x-www-form-urlencoded") === 0) {
              s2.data = s2.data.replace(r20, "+");
            }
            if (s2.ifModified) {
              if (jQuery2.lastModified[cacheURL]) {
                jqXHR.setRequestHeader("If-Modified-Since", jQuery2.lastModified[cacheURL]);
              }
              if (jQuery2.etag[cacheURL]) {
                jqXHR.setRequestHeader("If-None-Match", jQuery2.etag[cacheURL]);
              }
            }
            if (s2.data && s2.hasContent && s2.contentType !== false || options.contentType) {
              jqXHR.setRequestHeader("Content-Type", s2.contentType);
            }
            jqXHR.setRequestHeader("Accept", s2.dataTypes[0] && s2.accepts[s2.dataTypes[0]] ? s2.accepts[s2.dataTypes[0]] + (s2.dataTypes[0] !== "*" ? ", " + allTypes + "; q=0.01" : "") : s2.accepts["*"]);
            for (i2 in s2.headers) {
              jqXHR.setRequestHeader(i2, s2.headers[i2]);
            }
            if (s2.beforeSend && (s2.beforeSend.call(callbackContext, jqXHR, s2) === false || completed2)) {
              return jqXHR.abort();
            }
            strAbort = "abort";
            completeDeferred.add(s2.complete);
            jqXHR.done(s2.success);
            jqXHR.fail(s2.error);
            transport = inspectPrefiltersOrTransports(transports, s2, options, jqXHR);
            if (!transport) {
              done(-1, "No Transport");
            } else {
              jqXHR.readyState = 1;
              if (fireGlobals) {
                globalEventContext.trigger("ajaxSend", [jqXHR, s2]);
              }
              if (completed2) {
                return jqXHR;
              }
              if (s2.async && s2.timeout > 0) {
                timeoutTimer = window2.setTimeout(function() {
                  jqXHR.abort("timeout");
                }, s2.timeout);
              }
              try {
                completed2 = false;
                transport.send(requestHeaders, done);
              } catch (e2) {
                if (completed2) {
                  throw e2;
                }
                done(-1, e2);
              }
            }
            function done(status, nativeStatusText, responses, headers) {
              var isSuccess, success, error3, response, modified, statusText = nativeStatusText;
              if (completed2) {
                return;
              }
              completed2 = true;
              if (timeoutTimer) {
                window2.clearTimeout(timeoutTimer);
              }
              transport = void 0;
              responseHeadersString = headers || "";
              jqXHR.readyState = status > 0 ? 4 : 0;
              isSuccess = status >= 200 && status < 300 || status === 304;
              if (responses) {
                response = ajaxHandleResponses(s2, jqXHR, responses);
              }
              if (!isSuccess && jQuery2.inArray("script", s2.dataTypes) > -1 && jQuery2.inArray("json", s2.dataTypes) < 0) {
                s2.converters["text script"] = function() {
                };
              }
              response = ajaxConvert(s2, response, jqXHR, isSuccess);
              if (isSuccess) {
                if (s2.ifModified) {
                  modified = jqXHR.getResponseHeader("Last-Modified");
                  if (modified) {
                    jQuery2.lastModified[cacheURL] = modified;
                  }
                  modified = jqXHR.getResponseHeader("etag");
                  if (modified) {
                    jQuery2.etag[cacheURL] = modified;
                  }
                }
                if (status === 204 || s2.type === "HEAD") {
                  statusText = "nocontent";
                } else if (status === 304) {
                  statusText = "notmodified";
                } else {
                  statusText = response.state;
                  success = response.data;
                  error3 = response.error;
                  isSuccess = !error3;
                }
              } else {
                error3 = statusText;
                if (status || !statusText) {
                  statusText = "error";
                  if (status < 0) {
                    status = 0;
                  }
                }
              }
              jqXHR.status = status;
              jqXHR.statusText = (nativeStatusText || statusText) + "";
              if (isSuccess) {
                deferred.resolveWith(callbackContext, [success, statusText, jqXHR]);
              } else {
                deferred.rejectWith(callbackContext, [jqXHR, statusText, error3]);
              }
              jqXHR.statusCode(statusCode);
              statusCode = void 0;
              if (fireGlobals) {
                globalEventContext.trigger(isSuccess ? "ajaxSuccess" : "ajaxError", [jqXHR, s2, isSuccess ? success : error3]);
              }
              completeDeferred.fireWith(callbackContext, [jqXHR, statusText]);
              if (fireGlobals) {
                globalEventContext.trigger("ajaxComplete", [jqXHR, s2]);
                if (!--jQuery2.active) {
                  jQuery2.event.trigger("ajaxStop");
                }
              }
            }
            return jqXHR;
          },
          getJSON: function(url, data, callback2) {
            return jQuery2.get(url, data, callback2, "json");
          },
          getScript: function(url, callback2) {
            return jQuery2.get(url, void 0, callback2, "script");
          }
        });
        jQuery2.each(["get", "post"], function(_i2, method) {
          jQuery2[method] = function(url, data, callback2, type) {
            if (isFunction2(data)) {
              type = type || callback2;
              callback2 = data;
              data = void 0;
            }
            return jQuery2.ajax(jQuery2.extend({
              url,
              type: method,
              dataType: type,
              data,
              success: callback2
            }, jQuery2.isPlainObject(url) && url));
          };
        });
        jQuery2.ajaxPrefilter(function(s2) {
          var i2;
          for (i2 in s2.headers) {
            if (i2.toLowerCase() === "content-type") {
              s2.contentType = s2.headers[i2] || "";
            }
          }
        });
        jQuery2._evalUrl = function(url, options, doc) {
          return jQuery2.ajax({
            url,
            type: "GET",
            dataType: "script",
            cache: true,
            async: false,
            global: false,
            converters: {
              "text script": function() {
              }
            },
            dataFilter: function(response) {
              jQuery2.globalEval(response, options, doc);
            }
          });
        };
        jQuery2.fn.extend({
          wrapAll: function(html) {
            var wrap;
            if (this[0]) {
              if (isFunction2(html)) {
                html = html.call(this[0]);
              }
              wrap = jQuery2(html, this[0].ownerDocument).eq(0).clone(true);
              if (this[0].parentNode) {
                wrap.insertBefore(this[0]);
              }
              wrap.map(function() {
                var elem = this;
                while (elem.firstElementChild) {
                  elem = elem.firstElementChild;
                }
                return elem;
              }).append(this);
            }
            return this;
          },
          wrapInner: function(html) {
            if (isFunction2(html)) {
              return this.each(function(i2) {
                jQuery2(this).wrapInner(html.call(this, i2));
              });
            }
            return this.each(function() {
              var self2 = jQuery2(this), contents = self2.contents();
              if (contents.length) {
                contents.wrapAll(html);
              } else {
                self2.append(html);
              }
            });
          },
          wrap: function(html) {
            var htmlIsFunction = isFunction2(html);
            return this.each(function(i2) {
              jQuery2(this).wrapAll(htmlIsFunction ? html.call(this, i2) : html);
            });
          },
          unwrap: function(selector) {
            this.parent(selector).not("body").each(function() {
              jQuery2(this).replaceWith(this.childNodes);
            });
            return this;
          }
        });
        jQuery2.expr.pseudos.hidden = function(elem) {
          return !jQuery2.expr.pseudos.visible(elem);
        };
        jQuery2.expr.pseudos.visible = function(elem) {
          return !!(elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length);
        };
        jQuery2.ajaxSettings.xhr = function() {
          try {
            return new window2.XMLHttpRequest();
          } catch (e2) {
          }
        };
        var xhrSuccessStatus = {
          0: 200,
          1223: 204
        }, xhrSupported = jQuery2.ajaxSettings.xhr();
        support.cors = !!xhrSupported && "withCredentials" in xhrSupported;
        support.ajax = xhrSupported = !!xhrSupported;
        jQuery2.ajaxTransport(function(options) {
          var callback2, errorCallback;
          if (support.cors || xhrSupported && !options.crossDomain) {
            return {
              send: function(headers, complete) {
                var i2, xhr = options.xhr();
                xhr.open(options.type, options.url, options.async, options.username, options.password);
                if (options.xhrFields) {
                  for (i2 in options.xhrFields) {
                    xhr[i2] = options.xhrFields[i2];
                  }
                }
                if (options.mimeType && xhr.overrideMimeType) {
                  xhr.overrideMimeType(options.mimeType);
                }
                if (!options.crossDomain && !headers["X-Requested-With"]) {
                  headers["X-Requested-With"] = "XMLHttpRequest";
                }
                for (i2 in headers) {
                  xhr.setRequestHeader(i2, headers[i2]);
                }
                callback2 = function(type) {
                  return function() {
                    if (callback2) {
                      callback2 = errorCallback = xhr.onload = xhr.onerror = xhr.onabort = xhr.ontimeout = xhr.onreadystatechange = null;
                      if (type === "abort") {
                        xhr.abort();
                      } else if (type === "error") {
                        if (typeof xhr.status !== "number") {
                          complete(0, "error");
                        } else {
                          complete(xhr.status, xhr.statusText);
                        }
                      } else {
                        complete(xhrSuccessStatus[xhr.status] || xhr.status, xhr.statusText, (xhr.responseType || "text") !== "text" || typeof xhr.responseText !== "string" ? { binary: xhr.response } : { text: xhr.responseText }, xhr.getAllResponseHeaders());
                      }
                    }
                  };
                };
                xhr.onload = callback2();
                errorCallback = xhr.onerror = xhr.ontimeout = callback2("error");
                if (xhr.onabort !== void 0) {
                  xhr.onabort = errorCallback;
                } else {
                  xhr.onreadystatechange = function() {
                    if (xhr.readyState === 4) {
                      window2.setTimeout(function() {
                        if (callback2) {
                          errorCallback();
                        }
                      });
                    }
                  };
                }
                callback2 = callback2("abort");
                try {
                  xhr.send(options.hasContent && options.data || null);
                } catch (e2) {
                  if (callback2) {
                    throw e2;
                  }
                }
              },
              abort: function() {
                if (callback2) {
                  callback2();
                }
              }
            };
          }
        });
        jQuery2.ajaxPrefilter(function(s2) {
          if (s2.crossDomain) {
            s2.contents.script = false;
          }
        });
        jQuery2.ajaxSetup({
          accepts: {
            script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
          },
          contents: {
            script: /\b(?:java|ecma)script\b/
          },
          converters: {
            "text script": function(text) {
              jQuery2.globalEval(text);
              return text;
            }
          }
        });
        jQuery2.ajaxPrefilter("script", function(s2) {
          if (s2.cache === void 0) {
            s2.cache = false;
          }
          if (s2.crossDomain) {
            s2.type = "GET";
          }
        });
        jQuery2.ajaxTransport("script", function(s2) {
          if (s2.crossDomain || s2.scriptAttrs) {
            var script, callback2;
            return {
              send: function(_2, complete) {
                script = jQuery2("<script>").attr(s2.scriptAttrs || {}).prop({ charset: s2.scriptCharset, src: s2.url }).on("load error", callback2 = function(evt) {
                  script.remove();
                  callback2 = null;
                  if (evt) {
                    complete(evt.type === "error" ? 404 : 200, evt.type);
                  }
                });
                document2.head.appendChild(script[0]);
              },
              abort: function() {
                if (callback2) {
                  callback2();
                }
              }
            };
          }
        });
        var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/;
        jQuery2.ajaxSetup({
          jsonp: "callback",
          jsonpCallback: function() {
            var callback2 = oldCallbacks.pop() || jQuery2.expando + "_" + nonce.guid++;
            this[callback2] = true;
            return callback2;
          }
        });
        jQuery2.ajaxPrefilter("json jsonp", function(s2, originalSettings, jqXHR) {
          var callbackName, overwritten, responseContainer, jsonProp = s2.jsonp !== false && (rjsonp.test(s2.url) ? "url" : typeof s2.data === "string" && (s2.contentType || "").indexOf("application/x-www-form-urlencoded") === 0 && rjsonp.test(s2.data) && "data");
          if (jsonProp || s2.dataTypes[0] === "jsonp") {
            callbackName = s2.jsonpCallback = isFunction2(s2.jsonpCallback) ? s2.jsonpCallback() : s2.jsonpCallback;
            if (jsonProp) {
              s2[jsonProp] = s2[jsonProp].replace(rjsonp, "$1" + callbackName);
            } else if (s2.jsonp !== false) {
              s2.url += (rquery.test(s2.url) ? "&" : "?") + s2.jsonp + "=" + callbackName;
            }
            s2.converters["script json"] = function() {
              if (!responseContainer) {
                jQuery2.error(callbackName + " was not called");
              }
              return responseContainer[0];
            };
            s2.dataTypes[0] = "json";
            overwritten = window2[callbackName];
            window2[callbackName] = function() {
              responseContainer = arguments;
            };
            jqXHR.always(function() {
              if (overwritten === void 0) {
                jQuery2(window2).removeProp(callbackName);
              } else {
                window2[callbackName] = overwritten;
              }
              if (s2[callbackName]) {
                s2.jsonpCallback = originalSettings.jsonpCallback;
                oldCallbacks.push(callbackName);
              }
              if (responseContainer && isFunction2(overwritten)) {
                overwritten(responseContainer[0]);
              }
              responseContainer = overwritten = void 0;
            });
            return "script";
          }
        });
        support.createHTMLDocument = function() {
          var body = document2.implementation.createHTMLDocument("").body;
          body.innerHTML = "<form></form><form></form>";
          return body.childNodes.length === 2;
        }();
        jQuery2.parseHTML = function(data, context, keepScripts) {
          if (typeof data !== "string") {
            return [];
          }
          if (typeof context === "boolean") {
            keepScripts = context;
            context = false;
          }
          var base, parsed, scripts;
          if (!context) {
            if (support.createHTMLDocument) {
              context = document2.implementation.createHTMLDocument("");
              base = context.createElement("base");
              base.href = document2.location.href;
              context.head.appendChild(base);
            } else {
              context = document2;
            }
          }
          parsed = rsingleTag.exec(data);
          scripts = !keepScripts && [];
          if (parsed) {
            return [context.createElement(parsed[1])];
          }
          parsed = buildFragment([data], context, scripts);
          if (scripts && scripts.length) {
            jQuery2(scripts).remove();
          }
          return jQuery2.merge([], parsed.childNodes);
        };
        jQuery2.fn.load = function(url, params, callback2) {
          var selector, type, response, self2 = this, off = url.indexOf(" ");
          if (off > -1) {
            selector = stripAndCollapse(url.slice(off));
            url = url.slice(0, off);
          }
          if (isFunction2(params)) {
            callback2 = params;
            params = void 0;
          } else if (params && typeof params === "object") {
            type = "POST";
          }
          if (self2.length > 0) {
            jQuery2.ajax({
              url,
              type: type || "GET",
              dataType: "html",
              data: params
            }).done(function(responseText) {
              response = arguments;
              self2.html(selector ? jQuery2("<div>").append(jQuery2.parseHTML(responseText)).find(selector) : responseText);
            }).always(callback2 && function(jqXHR, status) {
              self2.each(function() {
                callback2.apply(this, response || [jqXHR.responseText, status, jqXHR]);
              });
            });
          }
          return this;
        };
        jQuery2.expr.pseudos.animated = function(elem) {
          return jQuery2.grep(jQuery2.timers, function(fn3) {
            return elem === fn3.elem;
          }).length;
        };
        jQuery2.offset = {
          setOffset: function(elem, options, i2) {
            var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition, position = jQuery2.css(elem, "position"), curElem = jQuery2(elem), props = {};
            if (position === "static") {
              elem.style.position = "relative";
            }
            curOffset = curElem.offset();
            curCSSTop = jQuery2.css(elem, "top");
            curCSSLeft = jQuery2.css(elem, "left");
            calculatePosition = (position === "absolute" || position === "fixed") && (curCSSTop + curCSSLeft).indexOf("auto") > -1;
            if (calculatePosition) {
              curPosition = curElem.position();
              curTop = curPosition.top;
              curLeft = curPosition.left;
            } else {
              curTop = parseFloat(curCSSTop) || 0;
              curLeft = parseFloat(curCSSLeft) || 0;
            }
            if (isFunction2(options)) {
              options = options.call(elem, i2, jQuery2.extend({}, curOffset));
            }
            if (options.top != null) {
              props.top = options.top - curOffset.top + curTop;
            }
            if (options.left != null) {
              props.left = options.left - curOffset.left + curLeft;
            }
            if ("using" in options) {
              options.using.call(elem, props);
            } else {
              curElem.css(props);
            }
          }
        };
        jQuery2.fn.extend({
          offset: function(options) {
            if (arguments.length) {
              return options === void 0 ? this : this.each(function(i2) {
                jQuery2.offset.setOffset(this, options, i2);
              });
            }
            var rect, win, elem = this[0];
            if (!elem) {
              return;
            }
            if (!elem.getClientRects().length) {
              return { top: 0, left: 0 };
            }
            rect = elem.getBoundingClientRect();
            win = elem.ownerDocument.defaultView;
            return {
              top: rect.top + win.pageYOffset,
              left: rect.left + win.pageXOffset
            };
          },
          position: function() {
            if (!this[0]) {
              return;
            }
            var offsetParent, offset2, doc, elem = this[0], parentOffset = { top: 0, left: 0 };
            if (jQuery2.css(elem, "position") === "fixed") {
              offset2 = elem.getBoundingClientRect();
            } else {
              offset2 = this.offset();
              doc = elem.ownerDocument;
              offsetParent = elem.offsetParent || doc.documentElement;
              while (offsetParent && (offsetParent === doc.body || offsetParent === doc.documentElement) && jQuery2.css(offsetParent, "position") === "static") {
                offsetParent = offsetParent.parentNode;
              }
              if (offsetParent && offsetParent !== elem && offsetParent.nodeType === 1) {
                parentOffset = jQuery2(offsetParent).offset();
                parentOffset.top += jQuery2.css(offsetParent, "borderTopWidth", true);
                parentOffset.left += jQuery2.css(offsetParent, "borderLeftWidth", true);
              }
            }
            return {
              top: offset2.top - parentOffset.top - jQuery2.css(elem, "marginTop", true),
              left: offset2.left - parentOffset.left - jQuery2.css(elem, "marginLeft", true)
            };
          },
          offsetParent: function() {
            return this.map(function() {
              var offsetParent = this.offsetParent;
              while (offsetParent && jQuery2.css(offsetParent, "position") === "static") {
                offsetParent = offsetParent.offsetParent;
              }
              return offsetParent || documentElement;
            });
          }
        });
        jQuery2.each({ scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function(method, prop) {
          var top2 = prop === "pageYOffset";
          jQuery2.fn[method] = function(val) {
            return access(this, function(elem, method2, val2) {
              var win;
              if (isWindow(elem)) {
                win = elem;
              } else if (elem.nodeType === 9) {
                win = elem.defaultView;
              }
              if (val2 === void 0) {
                return win ? win[prop] : elem[method2];
              }
              if (win) {
                win.scrollTo(!top2 ? val2 : win.pageXOffset, top2 ? val2 : win.pageYOffset);
              } else {
                elem[method2] = val2;
              }
            }, method, val, arguments.length);
          };
        });
        jQuery2.each(["top", "left"], function(_i2, prop) {
          jQuery2.cssHooks[prop] = addGetHookIf(support.pixelPosition, function(elem, computed) {
            if (computed) {
              computed = curCSS(elem, prop);
              return rnumnonpx.test(computed) ? jQuery2(elem).position()[prop] + "px" : computed;
            }
          });
        });
        jQuery2.each({ Height: "height", Width: "width" }, function(name, type) {
          jQuery2.each({
            padding: "inner" + name,
            content: type,
            "": "outer" + name
          }, function(defaultExtra, funcName) {
            jQuery2.fn[funcName] = function(margin, value) {
              var chainable = arguments.length && (defaultExtra || typeof margin !== "boolean"), extra = defaultExtra || (margin === true || value === true ? "margin" : "border");
              return access(this, function(elem, type2, value2) {
                var doc;
                if (isWindow(elem)) {
                  return funcName.indexOf("outer") === 0 ? elem["inner" + name] : elem.document.documentElement["client" + name];
                }
                if (elem.nodeType === 9) {
                  doc = elem.documentElement;
                  return Math.max(elem.body["scroll" + name], doc["scroll" + name], elem.body["offset" + name], doc["offset" + name], doc["client" + name]);
                }
                return value2 === void 0 ? jQuery2.css(elem, type2, extra) : jQuery2.style(elem, type2, value2, extra);
              }, type, chainable ? margin : void 0, chainable);
            };
          });
        });
        jQuery2.each([
          "ajaxStart",
          "ajaxStop",
          "ajaxComplete",
          "ajaxError",
          "ajaxSuccess",
          "ajaxSend"
        ], function(_i2, type) {
          jQuery2.fn[type] = function(fn3) {
            return this.on(type, fn3);
          };
        });
        jQuery2.fn.extend({
          bind: function(types, data, fn3) {
            return this.on(types, null, data, fn3);
          },
          unbind: function(types, fn3) {
            return this.off(types, null, fn3);
          },
          delegate: function(selector, types, data, fn3) {
            return this.on(types, selector, data, fn3);
          },
          undelegate: function(selector, types, fn3) {
            return arguments.length === 1 ? this.off(selector, "**") : this.off(types, selector || "**", fn3);
          },
          hover: function(fnOver, fnOut) {
            return this.mouseenter(fnOver).mouseleave(fnOut || fnOver);
          }
        });
        jQuery2.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "), function(_i2, name) {
          jQuery2.fn[name] = function(data, fn3) {
            return arguments.length > 0 ? this.on(name, null, data, fn3) : this.trigger(name);
          };
        });
        var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
        jQuery2.proxy = function(fn3, context) {
          var tmp, args, proxy;
          if (typeof context === "string") {
            tmp = fn3[context];
            context = fn3;
            fn3 = tmp;
          }
          if (!isFunction2(fn3)) {
            return void 0;
          }
          args = slice.call(arguments, 2);
          proxy = function() {
            return fn3.apply(context || this, args.concat(slice.call(arguments)));
          };
          proxy.guid = fn3.guid = fn3.guid || jQuery2.guid++;
          return proxy;
        };
        jQuery2.holdReady = function(hold) {
          if (hold) {
            jQuery2.readyWait++;
          } else {
            jQuery2.ready(true);
          }
        };
        jQuery2.isArray = Array.isArray;
        jQuery2.parseJSON = JSON.parse;
        jQuery2.nodeName = nodeName;
        jQuery2.isFunction = isFunction2;
        jQuery2.isWindow = isWindow;
        jQuery2.camelCase = camelCase;
        jQuery2.type = toType2;
        jQuery2.now = Date.now;
        jQuery2.isNumeric = function(obj) {
          var type = jQuery2.type(obj);
          return (type === "number" || type === "string") && !isNaN(obj - parseFloat(obj));
        };
        jQuery2.trim = function(text) {
          return text == null ? "" : (text + "").replace(rtrim, "");
        };
        if (typeof define === "function" && define.amd) {
          define("jquery", [], function() {
            return jQuery2;
          });
        }
        var _jQuery = window2.jQuery, _$ = window2.$;
        jQuery2.noConflict = function(deep) {
          if (window2.$ === jQuery2) {
            window2.$ = _$;
          }
          if (deep && window2.jQuery === jQuery2) {
            window2.jQuery = _jQuery;
          }
          return jQuery2;
        };
        if (typeof noGlobal === "undefined") {
          window2.jQuery = window2.$ = jQuery2;
        }
        return jQuery2;
      });
    }
  });

  // ../../node_modules/bootstrap-datetime-picker/js/bootstrap-datetimepicker.js
  var require_bootstrap_datetimepicker = __commonJS({
    "../../node_modules/bootstrap-datetime-picker/js/bootstrap-datetimepicker.js"(exports) {
      (function(factory) {
        if (typeof define === "function" && define.amd)
          define(["jquery"], factory);
        else if (typeof exports === "object")
          factory(require_jquery());
        else
          factory(jQuery);
      })(function($2, undefined2) {
        if (!("indexOf" in Array.prototype)) {
          Array.prototype.indexOf = function(find, i2) {
            if (i2 === undefined2)
              i2 = 0;
            if (i2 < 0)
              i2 += this.length;
            if (i2 < 0)
              i2 = 0;
            for (var n2 = this.length; i2 < n2; i2++) {
              if (i2 in this && this[i2] === find) {
                return i2;
              }
            }
            return -1;
          };
        }
        function timeZoneAbbreviation() {
          var abbreviation, date, formattedStr, i2, len, matchedStrings, ref, str;
          date = new Date().toString();
          formattedStr = ((ref = date.split("(")[1]) != null ? ref.slice(0, -1) : 0) || date.split(" ");
          if (formattedStr instanceof Array) {
            matchedStrings = [];
            for (var i2 = 0, len = formattedStr.length; i2 < len; i2++) {
              str = formattedStr[i2];
              if ((abbreviation = (ref = str.match(/\b[A-Z]+\b/)) !== null) ? ref[0] : 0) {
                matchedStrings.push(abbreviation);
              }
            }
            formattedStr = matchedStrings.pop();
          }
          return formattedStr;
        }
        function UTCDate() {
          return new Date(Date.UTC.apply(Date, arguments));
        }
        var Datetimepicker = function(element, options) {
          var that = this;
          this.element = $2(element);
          this.container = options.container || "body";
          this.language = options.language || this.element.data("date-language") || "en";
          this.language = this.language in dates ? this.language : this.language.split("-")[0];
          this.language = this.language in dates ? this.language : "en";
          this.isRTL = dates[this.language].rtl || false;
          this.formatType = options.formatType || this.element.data("format-type") || "standard";
          this.format = DPGlobal.parseFormat(options.format || this.element.data("date-format") || dates[this.language].format || DPGlobal.getDefaultFormat(this.formatType, "input"), this.formatType);
          this.isInline = false;
          this.isVisible = false;
          this.isInput = this.element.is("input");
          this.fontAwesome = options.fontAwesome || this.element.data("font-awesome") || false;
          this.bootcssVer = options.bootcssVer || (this.isInput ? this.element.is(".form-control") ? 3 : 2 : this.bootcssVer = this.element.is(".input-group") ? 3 : 2);
          this.component = this.element.is(".date") ? this.bootcssVer === 3 ? this.element.find(".input-group-addon .glyphicon-th, .input-group-addon .glyphicon-time, .input-group-addon .glyphicon-remove, .input-group-addon .glyphicon-calendar, .input-group-addon .fa-calendar, .input-group-addon .fa-clock-o").parent() : this.element.find(".add-on .icon-th, .add-on .icon-time, .add-on .icon-calendar, .add-on .fa-calendar, .add-on .fa-clock-o").parent() : false;
          this.componentReset = this.element.is(".date") ? this.bootcssVer === 3 ? this.element.find(".input-group-addon .glyphicon-remove, .input-group-addon .fa-times").parent() : this.element.find(".add-on .icon-remove, .add-on .fa-times").parent() : false;
          this.hasInput = this.component && this.element.find("input").length;
          if (this.component && this.component.length === 0) {
            this.component = false;
          }
          this.linkField = options.linkField || this.element.data("link-field") || false;
          this.linkFormat = DPGlobal.parseFormat(options.linkFormat || this.element.data("link-format") || DPGlobal.getDefaultFormat(this.formatType, "link"), this.formatType);
          this.minuteStep = options.minuteStep || this.element.data("minute-step") || 5;
          this.pickerPosition = options.pickerPosition || this.element.data("picker-position") || "bottom-right";
          this.showMeridian = options.showMeridian || this.element.data("show-meridian") || false;
          this.initialDate = options.initialDate || new Date();
          this.zIndex = options.zIndex || this.element.data("z-index") || undefined2;
          this.title = typeof options.title === "undefined" ? false : options.title;
          this.timezone = options.timezone || timeZoneAbbreviation();
          this.icons = {
            leftArrow: this.fontAwesome ? "fa-arrow-left" : this.bootcssVer === 3 ? "glyphicon-arrow-left" : "icon-arrow-left",
            rightArrow: this.fontAwesome ? "fa-arrow-right" : this.bootcssVer === 3 ? "glyphicon-arrow-right" : "icon-arrow-right"
          };
          this.icontype = this.fontAwesome ? "fa" : "glyphicon";
          this._attachEvents();
          this.clickedOutside = function(e2) {
            if ($2(e2.target).closest(".datetimepicker").length === 0) {
              that.hide();
            }
          };
          this.formatViewType = "datetime";
          if ("formatViewType" in options) {
            this.formatViewType = options.formatViewType;
          } else if ("formatViewType" in this.element.data()) {
            this.formatViewType = this.element.data("formatViewType");
          }
          this.minView = 0;
          if ("minView" in options) {
            this.minView = options.minView;
          } else if ("minView" in this.element.data()) {
            this.minView = this.element.data("min-view");
          }
          this.minView = DPGlobal.convertViewMode(this.minView);
          this.maxView = DPGlobal.modes.length - 1;
          if ("maxView" in options) {
            this.maxView = options.maxView;
          } else if ("maxView" in this.element.data()) {
            this.maxView = this.element.data("max-view");
          }
          this.maxView = DPGlobal.convertViewMode(this.maxView);
          this.wheelViewModeNavigation = false;
          if ("wheelViewModeNavigation" in options) {
            this.wheelViewModeNavigation = options.wheelViewModeNavigation;
          } else if ("wheelViewModeNavigation" in this.element.data()) {
            this.wheelViewModeNavigation = this.element.data("view-mode-wheel-navigation");
          }
          this.wheelViewModeNavigationInverseDirection = false;
          if ("wheelViewModeNavigationInverseDirection" in options) {
            this.wheelViewModeNavigationInverseDirection = options.wheelViewModeNavigationInverseDirection;
          } else if ("wheelViewModeNavigationInverseDirection" in this.element.data()) {
            this.wheelViewModeNavigationInverseDirection = this.element.data("view-mode-wheel-navigation-inverse-dir");
          }
          this.wheelViewModeNavigationDelay = 100;
          if ("wheelViewModeNavigationDelay" in options) {
            this.wheelViewModeNavigationDelay = options.wheelViewModeNavigationDelay;
          } else if ("wheelViewModeNavigationDelay" in this.element.data()) {
            this.wheelViewModeNavigationDelay = this.element.data("view-mode-wheel-navigation-delay");
          }
          this.startViewMode = 2;
          if ("startView" in options) {
            this.startViewMode = options.startView;
          } else if ("startView" in this.element.data()) {
            this.startViewMode = this.element.data("start-view");
          }
          this.startViewMode = DPGlobal.convertViewMode(this.startViewMode);
          this.viewMode = this.startViewMode;
          this.viewSelect = this.minView;
          if ("viewSelect" in options) {
            this.viewSelect = options.viewSelect;
          } else if ("viewSelect" in this.element.data()) {
            this.viewSelect = this.element.data("view-select");
          }
          this.viewSelect = DPGlobal.convertViewMode(this.viewSelect);
          this.forceParse = true;
          if ("forceParse" in options) {
            this.forceParse = options.forceParse;
          } else if ("dateForceParse" in this.element.data()) {
            this.forceParse = this.element.data("date-force-parse");
          }
          var template = this.bootcssVer === 3 ? DPGlobal.templateV3 : DPGlobal.template;
          while (template.indexOf("{iconType}") !== -1) {
            template = template.replace("{iconType}", this.icontype);
          }
          while (template.indexOf("{leftArrow}") !== -1) {
            template = template.replace("{leftArrow}", this.icons.leftArrow);
          }
          while (template.indexOf("{rightArrow}") !== -1) {
            template = template.replace("{rightArrow}", this.icons.rightArrow);
          }
          this.picker = $2(template).appendTo(this.isInline ? this.element : this.container).on({
            click: $2.proxy(this.click, this),
            mousedown: $2.proxy(this.mousedown, this)
          });
          if (this.wheelViewModeNavigation) {
            if ($2.fn.mousewheel) {
              this.picker.on({ mousewheel: $2.proxy(this.mousewheel, this) });
            } else {
              console.log("Mouse Wheel event is not supported. Please include the jQuery Mouse Wheel plugin before enabling this option");
            }
          }
          if (this.isInline) {
            this.picker.addClass("datetimepicker-inline");
          } else {
            this.picker.addClass("datetimepicker-dropdown-" + this.pickerPosition + " dropdown-menu");
          }
          if (this.isRTL) {
            this.picker.addClass("datetimepicker-rtl");
            var selector = this.bootcssVer === 3 ? ".prev span, .next span" : ".prev i, .next i";
            this.picker.find(selector).toggleClass(this.icons.leftArrow + " " + this.icons.rightArrow);
          }
          $2(document).on("mousedown touchend", this.clickedOutside);
          this.autoclose = false;
          if ("autoclose" in options) {
            this.autoclose = options.autoclose;
          } else if ("dateAutoclose" in this.element.data()) {
            this.autoclose = this.element.data("date-autoclose");
          }
          this.keyboardNavigation = true;
          if ("keyboardNavigation" in options) {
            this.keyboardNavigation = options.keyboardNavigation;
          } else if ("dateKeyboardNavigation" in this.element.data()) {
            this.keyboardNavigation = this.element.data("date-keyboard-navigation");
          }
          this.todayBtn = options.todayBtn || this.element.data("date-today-btn") || false;
          this.clearBtn = options.clearBtn || this.element.data("date-clear-btn") || false;
          this.todayHighlight = options.todayHighlight || this.element.data("date-today-highlight") || false;
          this.weekStart = 0;
          if (typeof options.weekStart !== "undefined") {
            this.weekStart = options.weekStart;
          } else if (typeof this.element.data("date-weekstart") !== "undefined") {
            this.weekStart = this.element.data("date-weekstart");
          } else if (typeof dates[this.language].weekStart !== "undefined") {
            this.weekStart = dates[this.language].weekStart;
          }
          this.weekStart = this.weekStart % 7;
          this.weekEnd = (this.weekStart + 6) % 7;
          this.onRenderDay = function(date) {
            var render = (options.onRenderDay || function() {
              return [];
            })(date);
            if (typeof render === "string") {
              render = [render];
            }
            var res = ["day"];
            return res.concat(render ? render : []);
          };
          this.onRenderHour = function(date) {
            var render = (options.onRenderHour || function() {
              return [];
            })(date);
            var res = ["hour"];
            if (typeof render === "string") {
              render = [render];
            }
            return res.concat(render ? render : []);
          };
          this.onRenderMinute = function(date) {
            var render = (options.onRenderMinute || function() {
              return [];
            })(date);
            var res = ["minute"];
            if (typeof render === "string") {
              render = [render];
            }
            if (date < this.startDate || date > this.endDate) {
              res.push("disabled");
            } else if (Math.floor(this.date.getUTCMinutes() / this.minuteStep) === Math.floor(date.getUTCMinutes() / this.minuteStep)) {
              res.push("active");
            }
            return res.concat(render ? render : []);
          };
          this.onRenderYear = function(date) {
            var render = (options.onRenderYear || function() {
              return [];
            })(date);
            var res = ["year"];
            if (typeof render === "string") {
              render = [render];
            }
            if (this.date.getUTCFullYear() === date.getUTCFullYear()) {
              res.push("active");
            }
            var currentYear = date.getUTCFullYear();
            var endYear = this.endDate.getUTCFullYear();
            if (date < this.startDate || currentYear > endYear) {
              res.push("disabled");
            }
            return res.concat(render ? render : []);
          };
          this.onRenderMonth = function(date) {
            var render = (options.onRenderMonth || function() {
              return [];
            })(date);
            var res = ["month"];
            if (typeof render === "string") {
              render = [render];
            }
            return res.concat(render ? render : []);
          };
          this.startDate = new Date(-8639968443048e3);
          this.endDate = new Date(8639968443048e3);
          this.datesDisabled = [];
          this.daysOfWeekDisabled = [];
          this.setStartDate(options.startDate || this.element.data("date-startdate"));
          this.setEndDate(options.endDate || this.element.data("date-enddate"));
          this.setDatesDisabled(options.datesDisabled || this.element.data("date-dates-disabled"));
          this.setDaysOfWeekDisabled(options.daysOfWeekDisabled || this.element.data("date-days-of-week-disabled"));
          this.setMinutesDisabled(options.minutesDisabled || this.element.data("date-minute-disabled"));
          this.setHoursDisabled(options.hoursDisabled || this.element.data("date-hour-disabled"));
          this.fillDow();
          this.fillMonths();
          this.update();
          this.showMode();
          if (this.isInline) {
            this.show();
          }
        };
        Datetimepicker.prototype = {
          constructor: Datetimepicker,
          _events: [],
          _attachEvents: function() {
            this._detachEvents();
            if (this.isInput) {
              this._events = [
                [this.element, {
                  focus: $2.proxy(this.show, this),
                  keyup: $2.proxy(this.update, this),
                  keydown: $2.proxy(this.keydown, this)
                }]
              ];
            } else if (this.component && this.hasInput) {
              this._events = [
                [this.element.find("input"), {
                  focus: $2.proxy(this.show, this),
                  keyup: $2.proxy(this.update, this),
                  keydown: $2.proxy(this.keydown, this)
                }],
                [this.component, {
                  click: $2.proxy(this.show, this)
                }]
              ];
              if (this.componentReset) {
                this._events.push([
                  this.componentReset,
                  { click: $2.proxy(this.reset, this) }
                ]);
              }
            } else if (this.element.is("div")) {
              this.isInline = true;
            } else {
              this._events = [
                [this.element, {
                  click: $2.proxy(this.show, this)
                }]
              ];
            }
            for (var i2 = 0, el, ev; i2 < this._events.length; i2++) {
              el = this._events[i2][0];
              ev = this._events[i2][1];
              el.on(ev);
            }
          },
          _detachEvents: function() {
            for (var i2 = 0, el, ev; i2 < this._events.length; i2++) {
              el = this._events[i2][0];
              ev = this._events[i2][1];
              el.off(ev);
            }
            this._events = [];
          },
          show: function(e2) {
            this.picker.show();
            this.height = this.component ? this.component.outerHeight() : this.element.outerHeight();
            if (this.forceParse) {
              this.update();
            }
            this.place();
            $2(window).on("resize", $2.proxy(this.place, this));
            if (e2) {
              e2.stopPropagation();
              e2.preventDefault();
            }
            this.isVisible = true;
            this.element.trigger({
              type: "show",
              date: this.date
            });
          },
          hide: function() {
            if (!this.isVisible)
              return;
            if (this.isInline)
              return;
            this.picker.hide();
            $2(window).off("resize", this.place);
            this.viewMode = this.startViewMode;
            this.showMode();
            if (!this.isInput) {
              $2(document).off("mousedown", this.hide);
            }
            if (this.forceParse && (this.isInput && this.element.val() || this.hasInput && this.element.find("input").val()))
              this.setValue();
            this.isVisible = false;
            this.element.trigger({
              type: "hide",
              date: this.date
            });
          },
          remove: function() {
            this._detachEvents();
            $2(document).off("mousedown", this.clickedOutside);
            this.picker.remove();
            delete this.picker;
            delete this.element.data().datetimepicker;
          },
          getDate: function() {
            var d2 = this.getUTCDate();
            if (d2 === null) {
              return null;
            }
            return new Date(d2.getTime() + d2.getTimezoneOffset() * 6e4);
          },
          getUTCDate: function() {
            return this.date;
          },
          getInitialDate: function() {
            return this.initialDate;
          },
          setInitialDate: function(initialDate) {
            this.initialDate = initialDate;
          },
          setDate: function(d2) {
            this.setUTCDate(new Date(d2.getTime() - d2.getTimezoneOffset() * 6e4));
          },
          setUTCDate: function(d2) {
            if (d2 >= this.startDate && d2 <= this.endDate) {
              this.date = d2;
              this.setValue();
              this.viewDate = this.date;
              this.fill();
            } else {
              this.element.trigger({
                type: "outOfRange",
                date: d2,
                startDate: this.startDate,
                endDate: this.endDate
              });
            }
          },
          setFormat: function(format3) {
            this.format = DPGlobal.parseFormat(format3, this.formatType);
            var element;
            if (this.isInput) {
              element = this.element;
            } else if (this.component) {
              element = this.element.find("input");
            }
            if (element && element.val()) {
              this.setValue();
            }
          },
          setValue: function() {
            var formatted = this.getFormattedDate();
            if (!this.isInput) {
              if (this.component) {
                this.element.find("input").val(formatted);
              }
              this.element.data("date", formatted);
            } else {
              this.element.val(formatted);
            }
            if (this.linkField) {
              $2("#" + this.linkField).val(this.getFormattedDate(this.linkFormat));
            }
          },
          getFormattedDate: function(format3) {
            format3 = format3 || this.format;
            return DPGlobal.formatDate(this.date, format3, this.language, this.formatType, this.timezone);
          },
          setStartDate: function(startDate) {
            this.startDate = startDate || this.startDate;
            if (this.startDate.valueOf() !== 8639968443048e3) {
              this.startDate = DPGlobal.parseDate(this.startDate, this.format, this.language, this.formatType, this.timezone);
            }
            this.update();
            this.updateNavArrows();
          },
          setEndDate: function(endDate) {
            this.endDate = endDate || this.endDate;
            if (this.endDate.valueOf() !== 8639968443048e3) {
              this.endDate = DPGlobal.parseDate(this.endDate, this.format, this.language, this.formatType, this.timezone);
            }
            this.update();
            this.updateNavArrows();
          },
          setDatesDisabled: function(datesDisabled) {
            this.datesDisabled = datesDisabled || [];
            if (!$2.isArray(this.datesDisabled)) {
              this.datesDisabled = this.datesDisabled.split(/,\s*/);
            }
            var mThis = this;
            this.datesDisabled = $2.map(this.datesDisabled, function(d2) {
              return DPGlobal.parseDate(d2, mThis.format, mThis.language, mThis.formatType, mThis.timezone).toDateString();
            });
            this.update();
            this.updateNavArrows();
          },
          setTitle: function(selector, value) {
            return this.picker.find(selector).find("th:eq(1)").text(this.title === false ? value : this.title);
          },
          setDaysOfWeekDisabled: function(daysOfWeekDisabled) {
            this.daysOfWeekDisabled = daysOfWeekDisabled || [];
            if (!$2.isArray(this.daysOfWeekDisabled)) {
              this.daysOfWeekDisabled = this.daysOfWeekDisabled.split(/,\s*/);
            }
            this.daysOfWeekDisabled = $2.map(this.daysOfWeekDisabled, function(d2) {
              return parseInt(d2, 10);
            });
            this.update();
            this.updateNavArrows();
          },
          setMinutesDisabled: function(minutesDisabled) {
            this.minutesDisabled = minutesDisabled || [];
            if (!$2.isArray(this.minutesDisabled)) {
              this.minutesDisabled = this.minutesDisabled.split(/,\s*/);
            }
            this.minutesDisabled = $2.map(this.minutesDisabled, function(d2) {
              return parseInt(d2, 10);
            });
            this.update();
            this.updateNavArrows();
          },
          setHoursDisabled: function(hoursDisabled) {
            this.hoursDisabled = hoursDisabled || [];
            if (!$2.isArray(this.hoursDisabled)) {
              this.hoursDisabled = this.hoursDisabled.split(/,\s*/);
            }
            this.hoursDisabled = $2.map(this.hoursDisabled, function(d2) {
              return parseInt(d2, 10);
            });
            this.update();
            this.updateNavArrows();
          },
          place: function() {
            if (this.isInline)
              return;
            if (!this.zIndex) {
              var index_highest = 0;
              $2("div").each(function() {
                var index_current = parseInt($2(this).css("zIndex"), 10);
                if (index_current > index_highest) {
                  index_highest = index_current;
                }
              });
              this.zIndex = index_highest + 10;
            }
            var offset2, top2, left2, containerOffset;
            if (this.container instanceof $2) {
              containerOffset = this.container.offset();
            } else {
              containerOffset = $2(this.container).offset();
            }
            if (this.component) {
              offset2 = this.component.offset();
              left2 = offset2.left;
              if (this.pickerPosition === "bottom-left" || this.pickerPosition === "top-left") {
                left2 += this.component.outerWidth() - this.picker.outerWidth();
              }
            } else {
              offset2 = this.element.offset();
              left2 = offset2.left;
              if (this.pickerPosition === "bottom-left" || this.pickerPosition === "top-left") {
                left2 += this.element.outerWidth() - this.picker.outerWidth();
              }
            }
            var bodyWidth = document.body.clientWidth || window.innerWidth;
            if (left2 + 220 > bodyWidth) {
              left2 = bodyWidth - 220;
            }
            if (this.pickerPosition === "top-left" || this.pickerPosition === "top-right") {
              top2 = offset2.top - this.picker.outerHeight();
            } else {
              top2 = offset2.top + this.height;
            }
            top2 = top2 - containerOffset.top;
            left2 = left2 - containerOffset.left;
            this.picker.css({
              top: top2,
              left: left2,
              zIndex: this.zIndex
            });
          },
          hour_minute: "^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]",
          update: function() {
            var date, fromArgs = false;
            if (arguments && arguments.length && (typeof arguments[0] === "string" || arguments[0] instanceof Date)) {
              date = arguments[0];
              fromArgs = true;
            } else {
              date = (this.isInput ? this.element.val() : this.element.find("input").val()) || this.element.data("date") || this.initialDate;
              if (typeof date === "string") {
                date = date.replace(/^\s+|\s+$/g, "");
              }
            }
            if (!date) {
              date = new Date();
              fromArgs = false;
            }
            if (typeof date === "string") {
              if (new RegExp(this.hour_minute).test(date) || new RegExp(this.hour_minute + ":[0-5][0-9]").test(date)) {
                date = this.getDate();
              }
            }
            this.date = DPGlobal.parseDate(date, this.format, this.language, this.formatType, this.timezone);
            if (fromArgs)
              this.setValue();
            if (this.date < this.startDate) {
              this.viewDate = new Date(this.startDate);
            } else if (this.date > this.endDate) {
              this.viewDate = new Date(this.endDate);
            } else {
              this.viewDate = new Date(this.date);
            }
            this.fill();
          },
          fillDow: function() {
            var dowCnt = this.weekStart, html = "<tr>";
            while (dowCnt < this.weekStart + 7) {
              html += '<th class="dow">' + dates[this.language].daysMin[dowCnt++ % 7] + "</th>";
            }
            html += "</tr>";
            this.picker.find(".datetimepicker-days thead").append(html);
          },
          fillMonths: function() {
            var html = "";
            var d2 = new Date(this.viewDate);
            for (var i2 = 0; i2 < 12; i2++) {
              d2.setUTCMonth(i2);
              var classes = this.onRenderMonth(d2);
              html += '<span class="' + classes.join(" ") + '">' + dates[this.language].monthsShort[i2] + "</span>";
            }
            this.picker.find(".datetimepicker-months td").html(html);
          },
          fill: function() {
            if (!this.date || !this.viewDate) {
              return;
            }
            var d2 = new Date(this.viewDate), year = d2.getUTCFullYear(), month = d2.getUTCMonth(), dayMonth = d2.getUTCDate(), hours = d2.getUTCHours(), startYear = this.startDate.getUTCFullYear(), startMonth = this.startDate.getUTCMonth(), endYear = this.endDate.getUTCFullYear(), endMonth = this.endDate.getUTCMonth() + 1, currentDate = new UTCDate(this.date.getUTCFullYear(), this.date.getUTCMonth(), this.date.getUTCDate()).valueOf(), today = new Date();
            this.setTitle(".datetimepicker-days", dates[this.language].months[month] + " " + year);
            if (this.formatViewType === "time") {
              var formatted = this.getFormattedDate();
              this.setTitle(".datetimepicker-hours", formatted);
              this.setTitle(".datetimepicker-minutes", formatted);
            } else {
              this.setTitle(".datetimepicker-hours", dayMonth + " " + dates[this.language].months[month] + " " + year);
              this.setTitle(".datetimepicker-minutes", dayMonth + " " + dates[this.language].months[month] + " " + year);
            }
            this.picker.find("tfoot th.today").text(dates[this.language].today || dates["en"].today).toggle(this.todayBtn !== false);
            this.picker.find("tfoot th.clear").text(dates[this.language].clear || dates["en"].clear).toggle(this.clearBtn !== false);
            this.updateNavArrows();
            this.fillMonths();
            var prevMonth = UTCDate(year, month - 1, 28, 0, 0, 0, 0), day = DPGlobal.getDaysInMonth(prevMonth.getUTCFullYear(), prevMonth.getUTCMonth());
            prevMonth.setUTCDate(day);
            prevMonth.setUTCDate(day - (prevMonth.getUTCDay() - this.weekStart + 7) % 7);
            var nextMonth = new Date(prevMonth);
            nextMonth.setUTCDate(nextMonth.getUTCDate() + 42);
            nextMonth = nextMonth.valueOf();
            var html = [];
            var classes;
            while (prevMonth.valueOf() < nextMonth) {
              if (prevMonth.getUTCDay() === this.weekStart) {
                html.push("<tr>");
              }
              classes = this.onRenderDay(prevMonth);
              if (prevMonth.getUTCFullYear() < year || prevMonth.getUTCFullYear() === year && prevMonth.getUTCMonth() < month) {
                classes.push("old");
              } else if (prevMonth.getUTCFullYear() > year || prevMonth.getUTCFullYear() === year && prevMonth.getUTCMonth() > month) {
                classes.push("new");
              }
              if (this.todayHighlight && prevMonth.getUTCFullYear() === today.getFullYear() && prevMonth.getUTCMonth() === today.getMonth() && prevMonth.getUTCDate() === today.getDate()) {
                classes.push("today");
              }
              if (prevMonth.valueOf() === currentDate) {
                classes.push("active");
              }
              if (prevMonth.valueOf() + 864e5 <= this.startDate || prevMonth.valueOf() > this.endDate || $2.inArray(prevMonth.getUTCDay(), this.daysOfWeekDisabled) !== -1 || $2.inArray(prevMonth.toDateString(), this.datesDisabled) !== -1) {
                classes.push("disabled");
              }
              html.push('<td class="' + classes.join(" ") + '">' + prevMonth.getUTCDate() + "</td>");
              if (prevMonth.getUTCDay() === this.weekEnd) {
                html.push("</tr>");
              }
              prevMonth.setUTCDate(prevMonth.getUTCDate() + 1);
            }
            this.picker.find(".datetimepicker-days tbody").empty().append(html.join(""));
            html = [];
            var txt = "", meridian = "", meridianOld = "";
            var hoursDisabled = this.hoursDisabled || [];
            d2 = new Date(this.viewDate);
            for (var i2 = 0; i2 < 24; i2++) {
              d2.setUTCHours(i2);
              classes = this.onRenderHour(d2);
              if (hoursDisabled.indexOf(i2) !== -1) {
                classes.push("disabled");
              }
              var actual = UTCDate(year, month, dayMonth, i2);
              if (actual.valueOf() + 36e5 <= this.startDate || actual.valueOf() > this.endDate) {
                classes.push("disabled");
              } else if (hours === i2) {
                classes.push("active");
              }
              if (this.showMeridian && dates[this.language].meridiem.length === 2) {
                meridian = i2 < 12 ? dates[this.language].meridiem[0] : dates[this.language].meridiem[1];
                if (meridian !== meridianOld) {
                  if (meridianOld !== "") {
                    html.push("</fieldset>");
                  }
                  html.push('<fieldset class="hour"><legend>' + meridian.toUpperCase() + "</legend>");
                }
                meridianOld = meridian;
                txt = i2 % 12 ? i2 % 12 : 12;
                if (i2 < 12) {
                  classes.push("hour_am");
                } else {
                  classes.push("hour_pm");
                }
                html.push('<span class="' + classes.join(" ") + '">' + txt + "</span>");
                if (i2 === 23) {
                  html.push("</fieldset>");
                }
              } else {
                txt = i2 + ":00";
                html.push('<span class="' + classes.join(" ") + '">' + txt + "</span>");
              }
            }
            this.picker.find(".datetimepicker-hours td").html(html.join(""));
            html = [];
            txt = "";
            meridian = "";
            meridianOld = "";
            var minutesDisabled = this.minutesDisabled || [];
            d2 = new Date(this.viewDate);
            for (var i2 = 0; i2 < 60; i2 += this.minuteStep) {
              if (minutesDisabled.indexOf(i2) !== -1)
                continue;
              d2.setUTCMinutes(i2);
              d2.setUTCSeconds(0);
              classes = this.onRenderMinute(d2);
              if (this.showMeridian && dates[this.language].meridiem.length === 2) {
                meridian = hours < 12 ? dates[this.language].meridiem[0] : dates[this.language].meridiem[1];
                if (meridian !== meridianOld) {
                  if (meridianOld !== "") {
                    html.push("</fieldset>");
                  }
                  html.push('<fieldset class="minute"><legend>' + meridian.toUpperCase() + "</legend>");
                }
                meridianOld = meridian;
                txt = hours % 12 ? hours % 12 : 12;
                html.push('<span class="' + classes.join(" ") + '">' + txt + ":" + (i2 < 10 ? "0" + i2 : i2) + "</span>");
                if (i2 === 59) {
                  html.push("</fieldset>");
                }
              } else {
                txt = i2 + ":00";
                html.push('<span class="' + classes.join(" ") + '">' + hours + ":" + (i2 < 10 ? "0" + i2 : i2) + "</span>");
              }
            }
            this.picker.find(".datetimepicker-minutes td").html(html.join(""));
            var currentYear = this.date.getUTCFullYear();
            var months = this.setTitle(".datetimepicker-months", year).end().find(".month").removeClass("active");
            if (currentYear === year) {
              months.eq(this.date.getUTCMonth()).addClass("active");
            }
            if (year < startYear || year > endYear) {
              months.addClass("disabled");
            }
            if (year === startYear) {
              months.slice(0, startMonth).addClass("disabled");
            }
            if (year === endYear) {
              months.slice(endMonth).addClass("disabled");
            }
            html = "";
            year = parseInt(year / 10, 10) * 10;
            var yearCont = this.setTitle(".datetimepicker-years", year + "-" + (year + 9)).end().find("td");
            year -= 1;
            d2 = new Date(this.viewDate);
            for (var i2 = -1; i2 < 11; i2++) {
              d2.setUTCFullYear(year);
              classes = this.onRenderYear(d2);
              if (i2 === -1 || i2 === 10) {
                classes.push(old);
              }
              html += '<span class="' + classes.join(" ") + '">' + year + "</span>";
              year += 1;
            }
            yearCont.html(html);
            this.place();
          },
          updateNavArrows: function() {
            var d2 = new Date(this.viewDate), year = d2.getUTCFullYear(), month = d2.getUTCMonth(), day = d2.getUTCDate(), hour = d2.getUTCHours();
            switch (this.viewMode) {
              case 0:
                if (year <= this.startDate.getUTCFullYear() && month <= this.startDate.getUTCMonth() && day <= this.startDate.getUTCDate() && hour <= this.startDate.getUTCHours()) {
                  this.picker.find(".prev").css({ visibility: "hidden" });
                } else {
                  this.picker.find(".prev").css({ visibility: "visible" });
                }
                if (year >= this.endDate.getUTCFullYear() && month >= this.endDate.getUTCMonth() && day >= this.endDate.getUTCDate() && hour >= this.endDate.getUTCHours()) {
                  this.picker.find(".next").css({ visibility: "hidden" });
                } else {
                  this.picker.find(".next").css({ visibility: "visible" });
                }
                break;
              case 1:
                if (year <= this.startDate.getUTCFullYear() && month <= this.startDate.getUTCMonth() && day <= this.startDate.getUTCDate()) {
                  this.picker.find(".prev").css({ visibility: "hidden" });
                } else {
                  this.picker.find(".prev").css({ visibility: "visible" });
                }
                if (year >= this.endDate.getUTCFullYear() && month >= this.endDate.getUTCMonth() && day >= this.endDate.getUTCDate()) {
                  this.picker.find(".next").css({ visibility: "hidden" });
                } else {
                  this.picker.find(".next").css({ visibility: "visible" });
                }
                break;
              case 2:
                if (year <= this.startDate.getUTCFullYear() && month <= this.startDate.getUTCMonth()) {
                  this.picker.find(".prev").css({ visibility: "hidden" });
                } else {
                  this.picker.find(".prev").css({ visibility: "visible" });
                }
                if (year >= this.endDate.getUTCFullYear() && month >= this.endDate.getUTCMonth()) {
                  this.picker.find(".next").css({ visibility: "hidden" });
                } else {
                  this.picker.find(".next").css({ visibility: "visible" });
                }
                break;
              case 3:
              case 4:
                if (year <= this.startDate.getUTCFullYear()) {
                  this.picker.find(".prev").css({ visibility: "hidden" });
                } else {
                  this.picker.find(".prev").css({ visibility: "visible" });
                }
                if (year >= this.endDate.getUTCFullYear()) {
                  this.picker.find(".next").css({ visibility: "hidden" });
                } else {
                  this.picker.find(".next").css({ visibility: "visible" });
                }
                break;
            }
          },
          mousewheel: function(e2) {
            e2.preventDefault();
            e2.stopPropagation();
            if (this.wheelPause) {
              return;
            }
            this.wheelPause = true;
            var originalEvent = e2.originalEvent;
            var delta = originalEvent.wheelDelta;
            var mode = delta > 0 ? 1 : delta === 0 ? 0 : -1;
            if (this.wheelViewModeNavigationInverseDirection) {
              mode = -mode;
            }
            this.showMode(mode);
            setTimeout($2.proxy(function() {
              this.wheelPause = false;
            }, this), this.wheelViewModeNavigationDelay);
          },
          click: function(e2) {
            e2.stopPropagation();
            e2.preventDefault();
            var target = $2(e2.target).closest("span, td, th, legend");
            if (target.is("." + this.icontype)) {
              target = $2(target).parent().closest("span, td, th, legend");
            }
            if (target.length === 1) {
              if (target.is(".disabled")) {
                this.element.trigger({
                  type: "outOfRange",
                  date: this.viewDate,
                  startDate: this.startDate,
                  endDate: this.endDate
                });
                return;
              }
              switch (target[0].nodeName.toLowerCase()) {
                case "th":
                  switch (target[0].className) {
                    case "switch":
                      this.showMode(1);
                      break;
                    case "prev":
                    case "next":
                      var dir = DPGlobal.modes[this.viewMode].navStep * (target[0].className === "prev" ? -1 : 1);
                      switch (this.viewMode) {
                        case 0:
                          this.viewDate = this.moveHour(this.viewDate, dir);
                          break;
                        case 1:
                          this.viewDate = this.moveDate(this.viewDate, dir);
                          break;
                        case 2:
                          this.viewDate = this.moveMonth(this.viewDate, dir);
                          break;
                        case 3:
                        case 4:
                          this.viewDate = this.moveYear(this.viewDate, dir);
                          break;
                      }
                      this.fill();
                      this.element.trigger({
                        type: target[0].className + ":" + this.convertViewModeText(this.viewMode),
                        date: this.viewDate,
                        startDate: this.startDate,
                        endDate: this.endDate
                      });
                      break;
                    case "clear":
                      this.reset();
                      if (this.autoclose) {
                        this.hide();
                      }
                      break;
                    case "today":
                      var date = new Date();
                      date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), 0);
                      if (date < this.startDate)
                        date = this.startDate;
                      else if (date > this.endDate)
                        date = this.endDate;
                      this.viewMode = this.startViewMode;
                      this.showMode(0);
                      this._setDate(date);
                      this.fill();
                      if (this.autoclose) {
                        this.hide();
                      }
                      break;
                  }
                  break;
                case "span":
                  if (!target.is(".disabled")) {
                    var year = this.viewDate.getUTCFullYear(), month = this.viewDate.getUTCMonth(), day = this.viewDate.getUTCDate(), hours = this.viewDate.getUTCHours(), minutes = this.viewDate.getUTCMinutes(), seconds = this.viewDate.getUTCSeconds();
                    if (target.is(".month")) {
                      this.viewDate.setUTCDate(1);
                      month = target.parent().find("span").index(target);
                      day = this.viewDate.getUTCDate();
                      this.viewDate.setUTCMonth(month);
                      this.element.trigger({
                        type: "changeMonth",
                        date: this.viewDate
                      });
                      if (this.viewSelect >= 3) {
                        this._setDate(UTCDate(year, month, day, hours, minutes, seconds, 0));
                      }
                    } else if (target.is(".year")) {
                      this.viewDate.setUTCDate(1);
                      year = parseInt(target.text(), 10) || 0;
                      this.viewDate.setUTCFullYear(year);
                      this.element.trigger({
                        type: "changeYear",
                        date: this.viewDate
                      });
                      if (this.viewSelect >= 4) {
                        this._setDate(UTCDate(year, month, day, hours, minutes, seconds, 0));
                      }
                    } else if (target.is(".hour")) {
                      hours = parseInt(target.text(), 10) || 0;
                      if (target.hasClass("hour_am") || target.hasClass("hour_pm")) {
                        if (hours === 12 && target.hasClass("hour_am")) {
                          hours = 0;
                        } else if (hours !== 12 && target.hasClass("hour_pm")) {
                          hours += 12;
                        }
                      }
                      this.viewDate.setUTCHours(hours);
                      this.element.trigger({
                        type: "changeHour",
                        date: this.viewDate
                      });
                      if (this.viewSelect >= 1) {
                        this._setDate(UTCDate(year, month, day, hours, minutes, seconds, 0));
                      }
                    } else if (target.is(".minute")) {
                      minutes = parseInt(target.text().substr(target.text().indexOf(":") + 1), 10) || 0;
                      this.viewDate.setUTCMinutes(minutes);
                      this.element.trigger({
                        type: "changeMinute",
                        date: this.viewDate
                      });
                      if (this.viewSelect >= 0) {
                        this._setDate(UTCDate(year, month, day, hours, minutes, seconds, 0));
                      }
                    }
                    if (this.viewMode !== 0) {
                      var oldViewMode = this.viewMode;
                      this.showMode(-1);
                      this.fill();
                      if (oldViewMode === this.viewMode && this.autoclose) {
                        this.hide();
                      }
                    } else {
                      this.fill();
                      if (this.autoclose) {
                        this.hide();
                      }
                    }
                  }
                  break;
                case "td":
                  if (target.is(".day") && !target.is(".disabled")) {
                    var day = parseInt(target.text(), 10) || 1;
                    var year = this.viewDate.getUTCFullYear(), month = this.viewDate.getUTCMonth(), hours = this.viewDate.getUTCHours(), minutes = this.viewDate.getUTCMinutes(), seconds = this.viewDate.getUTCSeconds();
                    if (target.is(".old")) {
                      if (month === 0) {
                        month = 11;
                        year -= 1;
                      } else {
                        month -= 1;
                      }
                    } else if (target.is(".new")) {
                      if (month === 11) {
                        month = 0;
                        year += 1;
                      } else {
                        month += 1;
                      }
                    }
                    this.viewDate.setUTCFullYear(year);
                    this.viewDate.setUTCMonth(month, day);
                    this.element.trigger({
                      type: "changeDay",
                      date: this.viewDate
                    });
                    if (this.viewSelect >= 2) {
                      this._setDate(UTCDate(year, month, day, hours, minutes, seconds, 0));
                    }
                  }
                  var oldViewMode = this.viewMode;
                  this.showMode(-1);
                  this.fill();
                  if (oldViewMode === this.viewMode && this.autoclose) {
                    this.hide();
                  }
                  break;
              }
            }
          },
          _setDate: function(date, which) {
            if (!which || which === "date")
              this.date = date;
            if (!which || which === "view")
              this.viewDate = date;
            this.fill();
            this.setValue();
            var element;
            if (this.isInput) {
              element = this.element;
            } else if (this.component) {
              element = this.element.find("input");
            }
            if (element) {
              element.change();
            }
            this.element.trigger({
              type: "changeDate",
              date: this.getDate()
            });
            if (date === null)
              this.date = this.viewDate;
          },
          moveMinute: function(date, dir) {
            if (!dir)
              return date;
            var new_date = new Date(date.valueOf());
            new_date.setUTCMinutes(new_date.getUTCMinutes() + dir * this.minuteStep);
            return new_date;
          },
          moveHour: function(date, dir) {
            if (!dir)
              return date;
            var new_date = new Date(date.valueOf());
            new_date.setUTCHours(new_date.getUTCHours() + dir);
            return new_date;
          },
          moveDate: function(date, dir) {
            if (!dir)
              return date;
            var new_date = new Date(date.valueOf());
            new_date.setUTCDate(new_date.getUTCDate() + dir);
            return new_date;
          },
          moveMonth: function(date, dir) {
            if (!dir)
              return date;
            var new_date = new Date(date.valueOf()), day = new_date.getUTCDate(), month = new_date.getUTCMonth(), mag = Math.abs(dir), new_month, test;
            dir = dir > 0 ? 1 : -1;
            if (mag === 1) {
              test = dir === -1 ? function() {
                return new_date.getUTCMonth() === month;
              } : function() {
                return new_date.getUTCMonth() !== new_month;
              };
              new_month = month + dir;
              new_date.setUTCMonth(new_month);
              if (new_month < 0 || new_month > 11)
                new_month = (new_month + 12) % 12;
            } else {
              for (var i2 = 0; i2 < mag; i2++)
                new_date = this.moveMonth(new_date, dir);
              new_month = new_date.getUTCMonth();
              new_date.setUTCDate(day);
              test = function() {
                return new_month !== new_date.getUTCMonth();
              };
            }
            while (test()) {
              new_date.setUTCDate(--day);
              new_date.setUTCMonth(new_month);
            }
            return new_date;
          },
          moveYear: function(date, dir) {
            return this.moveMonth(date, dir * 12);
          },
          dateWithinRange: function(date) {
            return date >= this.startDate && date <= this.endDate;
          },
          keydown: function(e2) {
            if (this.picker.is(":not(:visible)")) {
              if (e2.keyCode === 27)
                this.show();
              return;
            }
            var dateChanged = false, dir, newDate, newViewDate;
            switch (e2.keyCode) {
              case 27:
                this.hide();
                e2.preventDefault();
                break;
              case 37:
              case 39:
                if (!this.keyboardNavigation)
                  break;
                dir = e2.keyCode === 37 ? -1 : 1;
                var viewMode = this.viewMode;
                if (e2.ctrlKey) {
                  viewMode += 2;
                } else if (e2.shiftKey) {
                  viewMode += 1;
                }
                if (viewMode === 4) {
                  newDate = this.moveYear(this.date, dir);
                  newViewDate = this.moveYear(this.viewDate, dir);
                } else if (viewMode === 3) {
                  newDate = this.moveMonth(this.date, dir);
                  newViewDate = this.moveMonth(this.viewDate, dir);
                } else if (viewMode === 2) {
                  newDate = this.moveDate(this.date, dir);
                  newViewDate = this.moveDate(this.viewDate, dir);
                } else if (viewMode === 1) {
                  newDate = this.moveHour(this.date, dir);
                  newViewDate = this.moveHour(this.viewDate, dir);
                } else if (viewMode === 0) {
                  newDate = this.moveMinute(this.date, dir);
                  newViewDate = this.moveMinute(this.viewDate, dir);
                }
                if (this.dateWithinRange(newDate)) {
                  this.date = newDate;
                  this.viewDate = newViewDate;
                  this.setValue();
                  this.update();
                  e2.preventDefault();
                  dateChanged = true;
                }
                break;
              case 38:
              case 40:
                if (!this.keyboardNavigation)
                  break;
                dir = e2.keyCode === 38 ? -1 : 1;
                viewMode = this.viewMode;
                if (e2.ctrlKey) {
                  viewMode += 2;
                } else if (e2.shiftKey) {
                  viewMode += 1;
                }
                if (viewMode === 4) {
                  newDate = this.moveYear(this.date, dir);
                  newViewDate = this.moveYear(this.viewDate, dir);
                } else if (viewMode === 3) {
                  newDate = this.moveMonth(this.date, dir);
                  newViewDate = this.moveMonth(this.viewDate, dir);
                } else if (viewMode === 2) {
                  newDate = this.moveDate(this.date, dir * 7);
                  newViewDate = this.moveDate(this.viewDate, dir * 7);
                } else if (viewMode === 1) {
                  if (this.showMeridian) {
                    newDate = this.moveHour(this.date, dir * 6);
                    newViewDate = this.moveHour(this.viewDate, dir * 6);
                  } else {
                    newDate = this.moveHour(this.date, dir * 4);
                    newViewDate = this.moveHour(this.viewDate, dir * 4);
                  }
                } else if (viewMode === 0) {
                  newDate = this.moveMinute(this.date, dir * 4);
                  newViewDate = this.moveMinute(this.viewDate, dir * 4);
                }
                if (this.dateWithinRange(newDate)) {
                  this.date = newDate;
                  this.viewDate = newViewDate;
                  this.setValue();
                  this.update();
                  e2.preventDefault();
                  dateChanged = true;
                }
                break;
              case 13:
                if (this.viewMode !== 0) {
                  var oldViewMode = this.viewMode;
                  this.showMode(-1);
                  this.fill();
                  if (oldViewMode === this.viewMode && this.autoclose) {
                    this.hide();
                  }
                } else {
                  this.fill();
                  if (this.autoclose) {
                    this.hide();
                  }
                }
                e2.preventDefault();
                break;
              case 9:
                this.hide();
                break;
            }
            if (dateChanged) {
              var element;
              if (this.isInput) {
                element = this.element;
              } else if (this.component) {
                element = this.element.find("input");
              }
              if (element) {
                element.change();
              }
              this.element.trigger({
                type: "changeDate",
                date: this.getDate()
              });
            }
          },
          showMode: function(dir) {
            if (dir) {
              var newViewMode = Math.max(0, Math.min(DPGlobal.modes.length - 1, this.viewMode + dir));
              if (newViewMode >= this.minView && newViewMode <= this.maxView) {
                this.element.trigger({
                  type: "changeMode",
                  date: this.viewDate,
                  oldViewMode: this.viewMode,
                  newViewMode
                });
                this.viewMode = newViewMode;
              }
            }
            this.picker.find(">div").hide().filter(".datetimepicker-" + DPGlobal.modes[this.viewMode].clsName).css("display", "block");
            this.updateNavArrows();
          },
          reset: function() {
            this._setDate(null, "date");
          },
          convertViewModeText: function(viewMode) {
            switch (viewMode) {
              case 4:
                return "decade";
              case 3:
                return "year";
              case 2:
                return "month";
              case 1:
                return "day";
              case 0:
                return "hour";
            }
          }
        };
        var old = $2.fn.datetimepicker;
        $2.fn.datetimepicker = function(option) {
          var args = Array.apply(null, arguments);
          args.shift();
          var internal_return;
          this.each(function() {
            var $this = $2(this), data = $this.data("datetimepicker"), options = typeof option === "object" && option;
            if (!data) {
              $this.data("datetimepicker", data = new Datetimepicker(this, $2.extend({}, $2.fn.datetimepicker.defaults, options)));
            }
            if (typeof option === "string" && typeof data[option] === "function") {
              internal_return = data[option].apply(data, args);
              if (internal_return !== undefined2) {
                return false;
              }
            }
          });
          if (internal_return !== undefined2)
            return internal_return;
          else
            return this;
        };
        $2.fn.datetimepicker.defaults = {};
        $2.fn.datetimepicker.Constructor = Datetimepicker;
        var dates = $2.fn.datetimepicker.dates = {
          en: {
            days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
            daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
            daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
            months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
            monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
            meridiem: ["am", "pm"],
            suffix: ["st", "nd", "rd", "th"],
            today: "Today",
            clear: "Clear"
          }
        };
        var DPGlobal = {
          modes: [
            {
              clsName: "minutes",
              navFnc: "Hours",
              navStep: 1
            },
            {
              clsName: "hours",
              navFnc: "Date",
              navStep: 1
            },
            {
              clsName: "days",
              navFnc: "Month",
              navStep: 1
            },
            {
              clsName: "months",
              navFnc: "FullYear",
              navStep: 1
            },
            {
              clsName: "years",
              navFnc: "FullYear",
              navStep: 10
            }
          ],
          isLeapYear: function(year) {
            return year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
          },
          getDaysInMonth: function(year, month) {
            return [31, DPGlobal.isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
          },
          getDefaultFormat: function(type, field) {
            if (type === "standard") {
              if (field === "input")
                return "yyyy-mm-dd hh:ii";
              else
                return "yyyy-mm-dd hh:ii:ss";
            } else if (type === "php") {
              if (field === "input")
                return "Y-m-d H:i";
              else
                return "Y-m-d H:i:s";
            } else {
              throw new Error("Invalid format type.");
            }
          },
          validParts: function(type) {
            if (type === "standard") {
              return /t|hh?|HH?|p|P|z|Z|ii?|ss?|dd?|DD?|mm?|MM?|yy(?:yy)?/g;
            } else if (type === "php") {
              return /[dDjlNwzFmMnStyYaABgGhHis]/g;
            } else {
              throw new Error("Invalid format type.");
            }
          },
          nonpunctuation: /[^ -\/:-@\[-`{-~\t\n\rTZ]+/g,
          parseFormat: function(format3, type) {
            var separators = format3.replace(this.validParts(type), "\0").split("\0"), parts = format3.match(this.validParts(type));
            if (!separators || !separators.length || !parts || parts.length === 0) {
              throw new Error("Invalid date format.");
            }
            return { separators, parts };
          },
          parseDate: function(date, format3, language, type, timezone) {
            if (date instanceof Date) {
              var dateUTC = new Date(date.valueOf() - date.getTimezoneOffset() * 6e4);
              dateUTC.setMilliseconds(0);
              return dateUTC;
            }
            if (/^\d{4}\-\d{1,2}\-\d{1,2}$/.test(date)) {
              format3 = this.parseFormat("yyyy-mm-dd", type);
            }
            if (/^\d{4}\-\d{1,2}\-\d{1,2}[T ]\d{1,2}\:\d{1,2}$/.test(date)) {
              format3 = this.parseFormat("yyyy-mm-dd hh:ii", type);
            }
            if (/^\d{4}\-\d{1,2}\-\d{1,2}[T ]\d{1,2}\:\d{1,2}\:\d{1,2}[Z]{0,1}$/.test(date)) {
              format3 = this.parseFormat("yyyy-mm-dd hh:ii:ss", type);
            }
            if (/^[-+]\d+[dmwy]([\s,]+[-+]\d+[dmwy])*$/.test(date)) {
              var part_re = /([-+]\d+)([dmwy])/, parts = date.match(/([-+]\d+)([dmwy])/g), part, dir;
              date = new Date();
              for (var i2 = 0; i2 < parts.length; i2++) {
                part = part_re.exec(parts[i2]);
                dir = parseInt(part[1]);
                switch (part[2]) {
                  case "d":
                    date.setUTCDate(date.getUTCDate() + dir);
                    break;
                  case "m":
                    date = Datetimepicker.prototype.moveMonth.call(Datetimepicker.prototype, date, dir);
                    break;
                  case "w":
                    date.setUTCDate(date.getUTCDate() + dir * 7);
                    break;
                  case "y":
                    date = Datetimepicker.prototype.moveYear.call(Datetimepicker.prototype, date, dir);
                    break;
                }
              }
              return UTCDate(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), 0);
            }
            var parts = date && date.toString().match(this.nonpunctuation) || [], date = new Date(0, 0, 0, 0, 0, 0, 0), parsed = {}, setters_order = ["hh", "h", "ii", "i", "ss", "s", "yyyy", "yy", "M", "MM", "m", "mm", "D", "DD", "d", "dd", "H", "HH", "p", "P", "z", "Z"], setters_map = {
              hh: function(d2, v2) {
                return d2.setUTCHours(v2);
              },
              h: function(d2, v2) {
                return d2.setUTCHours(v2);
              },
              HH: function(d2, v2) {
                return d2.setUTCHours(v2 === 12 ? 0 : v2);
              },
              H: function(d2, v2) {
                return d2.setUTCHours(v2 === 12 ? 0 : v2);
              },
              ii: function(d2, v2) {
                return d2.setUTCMinutes(v2);
              },
              i: function(d2, v2) {
                return d2.setUTCMinutes(v2);
              },
              ss: function(d2, v2) {
                return d2.setUTCSeconds(v2);
              },
              s: function(d2, v2) {
                return d2.setUTCSeconds(v2);
              },
              yyyy: function(d2, v2) {
                return d2.setUTCFullYear(v2);
              },
              yy: function(d2, v2) {
                return d2.setUTCFullYear(2e3 + v2);
              },
              m: function(d2, v2) {
                v2 -= 1;
                while (v2 < 0)
                  v2 += 12;
                v2 %= 12;
                d2.setUTCMonth(v2);
                while (d2.getUTCMonth() !== v2)
                  if (isNaN(d2.getUTCMonth()))
                    return d2;
                  else
                    d2.setUTCDate(d2.getUTCDate() - 1);
                return d2;
              },
              d: function(d2, v2) {
                return d2.setUTCDate(v2);
              },
              p: function(d2, v2) {
                return d2.setUTCHours(v2 === 1 ? d2.getUTCHours() + 12 : d2.getUTCHours());
              },
              z: function() {
                return timezone;
              }
            }, val, filtered, part;
            setters_map["M"] = setters_map["MM"] = setters_map["mm"] = setters_map["m"];
            setters_map["dd"] = setters_map["d"];
            setters_map["P"] = setters_map["p"];
            setters_map["Z"] = setters_map["z"];
            date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
            if (parts.length === format3.parts.length) {
              for (var i2 = 0, cnt = format3.parts.length; i2 < cnt; i2++) {
                val = parseInt(parts[i2], 10);
                part = format3.parts[i2];
                if (isNaN(val)) {
                  switch (part) {
                    case "MM":
                      filtered = $2(dates[language].months).filter(function() {
                        var m2 = this.slice(0, parts[i2].length), p2 = parts[i2].slice(0, m2.length);
                        return m2 === p2;
                      });
                      val = $2.inArray(filtered[0], dates[language].months) + 1;
                      break;
                    case "M":
                      filtered = $2(dates[language].monthsShort).filter(function() {
                        var m2 = this.slice(0, parts[i2].length), p2 = parts[i2].slice(0, m2.length);
                        return m2.toLowerCase() === p2.toLowerCase();
                      });
                      val = $2.inArray(filtered[0], dates[language].monthsShort) + 1;
                      break;
                    case "p":
                    case "P":
                      val = $2.inArray(parts[i2].toLowerCase(), dates[language].meridiem);
                      break;
                    case "z":
                    case "Z":
                      timezone;
                      break;
                  }
                }
                parsed[part] = val;
              }
              for (var i2 = 0, s2; i2 < setters_order.length; i2++) {
                s2 = setters_order[i2];
                if (s2 in parsed && !isNaN(parsed[s2]))
                  setters_map[s2](date, parsed[s2]);
              }
            }
            return date;
          },
          formatDate: function(date, format3, language, type, timezone) {
            if (date === null) {
              return "";
            }
            var val;
            if (type === "standard") {
              val = {
                t: date.getTime(),
                yy: date.getUTCFullYear().toString().substring(2),
                yyyy: date.getUTCFullYear(),
                m: date.getUTCMonth() + 1,
                M: dates[language].monthsShort[date.getUTCMonth()],
                MM: dates[language].months[date.getUTCMonth()],
                d: date.getUTCDate(),
                D: dates[language].daysShort[date.getUTCDay()],
                DD: dates[language].days[date.getUTCDay()],
                p: dates[language].meridiem.length === 2 ? dates[language].meridiem[date.getUTCHours() < 12 ? 0 : 1] : "",
                h: date.getUTCHours(),
                i: date.getUTCMinutes(),
                s: date.getUTCSeconds(),
                z: timezone
              };
              if (dates[language].meridiem.length === 2) {
                val.H = val.h % 12 === 0 ? 12 : val.h % 12;
              } else {
                val.H = val.h;
              }
              val.HH = (val.H < 10 ? "0" : "") + val.H;
              val.P = val.p.toUpperCase();
              val.Z = val.z;
              val.hh = (val.h < 10 ? "0" : "") + val.h;
              val.ii = (val.i < 10 ? "0" : "") + val.i;
              val.ss = (val.s < 10 ? "0" : "") + val.s;
              val.dd = (val.d < 10 ? "0" : "") + val.d;
              val.mm = (val.m < 10 ? "0" : "") + val.m;
            } else if (type === "php") {
              val = {
                y: date.getUTCFullYear().toString().substring(2),
                Y: date.getUTCFullYear(),
                F: dates[language].months[date.getUTCMonth()],
                M: dates[language].monthsShort[date.getUTCMonth()],
                n: date.getUTCMonth() + 1,
                t: DPGlobal.getDaysInMonth(date.getUTCFullYear(), date.getUTCMonth()),
                j: date.getUTCDate(),
                l: dates[language].days[date.getUTCDay()],
                D: dates[language].daysShort[date.getUTCDay()],
                w: date.getUTCDay(),
                N: date.getUTCDay() === 0 ? 7 : date.getUTCDay(),
                S: date.getUTCDate() % 10 <= dates[language].suffix.length ? dates[language].suffix[date.getUTCDate() % 10 - 1] : "",
                a: dates[language].meridiem.length === 2 ? dates[language].meridiem[date.getUTCHours() < 12 ? 0 : 1] : "",
                g: date.getUTCHours() % 12 === 0 ? 12 : date.getUTCHours() % 12,
                G: date.getUTCHours(),
                i: date.getUTCMinutes(),
                s: date.getUTCSeconds()
              };
              val.m = (val.n < 10 ? "0" : "") + val.n;
              val.d = (val.j < 10 ? "0" : "") + val.j;
              val.A = val.a.toString().toUpperCase();
              val.h = (val.g < 10 ? "0" : "") + val.g;
              val.H = (val.G < 10 ? "0" : "") + val.G;
              val.i = (val.i < 10 ? "0" : "") + val.i;
              val.s = (val.s < 10 ? "0" : "") + val.s;
            } else {
              throw new Error("Invalid format type.");
            }
            var date = [], seps = $2.extend([], format3.separators);
            for (var i2 = 0, cnt = format3.parts.length; i2 < cnt; i2++) {
              if (seps.length) {
                date.push(seps.shift());
              }
              date.push(val[format3.parts[i2]]);
            }
            if (seps.length) {
              date.push(seps.shift());
            }
            return date.join("");
          },
          convertViewMode: function(viewMode) {
            switch (viewMode) {
              case 4:
              case "decade":
                viewMode = 4;
                break;
              case 3:
              case "year":
                viewMode = 3;
                break;
              case 2:
              case "month":
                viewMode = 2;
                break;
              case 1:
              case "day":
                viewMode = 1;
                break;
              case 0:
              case "hour":
                viewMode = 0;
                break;
            }
            return viewMode;
          },
          headTemplate: '<thead><tr><th class="prev"><i class="{iconType} {leftArrow}"/></th><th colspan="5" class="switch"></th><th class="next"><i class="{iconType} {rightArrow}"/></th></tr></thead>',
          headTemplateV3: '<thead><tr><th class="prev"><span class="{iconType} {leftArrow}"></span> </th><th colspan="5" class="switch"></th><th class="next"><span class="{iconType} {rightArrow}"></span> </th></tr></thead>',
          contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>',
          footTemplate: '<tfoot><tr><th colspan="7" class="today"></th></tr><tr><th colspan="7" class="clear"></th></tr></tfoot>'
        };
        DPGlobal.template = '<div class="datetimepicker"><div class="datetimepicker-minutes"><table class=" table-condensed">' + DPGlobal.headTemplate + DPGlobal.contTemplate + DPGlobal.footTemplate + '</table></div><div class="datetimepicker-hours"><table class=" table-condensed">' + DPGlobal.headTemplate + DPGlobal.contTemplate + DPGlobal.footTemplate + '</table></div><div class="datetimepicker-days"><table class=" table-condensed">' + DPGlobal.headTemplate + "<tbody></tbody>" + DPGlobal.footTemplate + '</table></div><div class="datetimepicker-months"><table class="table-condensed">' + DPGlobal.headTemplate + DPGlobal.contTemplate + DPGlobal.footTemplate + '</table></div><div class="datetimepicker-years"><table class="table-condensed">' + DPGlobal.headTemplate + DPGlobal.contTemplate + DPGlobal.footTemplate + "</table></div></div>";
        DPGlobal.templateV3 = '<div class="datetimepicker"><div class="datetimepicker-minutes"><table class=" table-condensed">' + DPGlobal.headTemplateV3 + DPGlobal.contTemplate + DPGlobal.footTemplate + '</table></div><div class="datetimepicker-hours"><table class=" table-condensed">' + DPGlobal.headTemplateV3 + DPGlobal.contTemplate + DPGlobal.footTemplate + '</table></div><div class="datetimepicker-days"><table class=" table-condensed">' + DPGlobal.headTemplateV3 + "<tbody></tbody>" + DPGlobal.footTemplate + '</table></div><div class="datetimepicker-months"><table class="table-condensed">' + DPGlobal.headTemplateV3 + DPGlobal.contTemplate + DPGlobal.footTemplate + '</table></div><div class="datetimepicker-years"><table class="table-condensed">' + DPGlobal.headTemplateV3 + DPGlobal.contTemplate + DPGlobal.footTemplate + "</table></div></div>";
        $2.fn.datetimepicker.DPGlobal = DPGlobal;
        $2.fn.datetimepicker.noConflict = function() {
          $2.fn.datetimepicker = old;
          return this;
        };
        $2(document).on("focus.datetimepicker.data-api click.datetimepicker.data-api", '[data-provide="datetimepicker"]', function(e2) {
          var $this = $2(this);
          if ($this.data("datetimepicker"))
            return;
          e2.preventDefault();
          $this.datetimepicker("show");
        });
        $2(function() {
          $2('[data-provide="datetimepicker-inline"]').datetimepicker();
        });
      });
    }
  });

  // channels/index.js
  var require_channels = __commonJS({
    "channels/index.js"() {
    }
  });

  // ../../node_modules/chartkick/dist/chartkick.js
  var require_chartkick = __commonJS({
    "../../node_modules/chartkick/dist/chartkick.js"(exports, module) {
      (function(global2, factory) {
        typeof exports === "object" && typeof module !== "undefined" ? module.exports = factory() : typeof define === "function" && define.amd ? define(factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, global2.Chartkick = factory());
      })(exports, function() {
        "use strict";
        function isArray2(variable) {
          return Object.prototype.toString.call(variable) === "[object Array]";
        }
        function isFunction2(variable) {
          return variable instanceof Function;
        }
        function isPlainObject(variable) {
          return Object.prototype.toString.call(variable) === "[object Object]" && !isFunction2(variable) && variable instanceof Object;
        }
        function extend4(target, source) {
          var key;
          for (key in source) {
            if (key === "__proto__") {
              continue;
            }
            if (isPlainObject(source[key]) || isArray2(source[key])) {
              if (isPlainObject(source[key]) && !isPlainObject(target[key])) {
                target[key] = {};
              }
              if (isArray2(source[key]) && !isArray2(target[key])) {
                target[key] = [];
              }
              extend4(target[key], source[key]);
            } else if (source[key] !== void 0) {
              target[key] = source[key];
            }
          }
        }
        function merge2(obj1, obj2) {
          var target = {};
          extend4(target, obj1);
          extend4(target, obj2);
          return target;
        }
        var DATE_PATTERN = /^(\d\d\d\d)(-)?(\d\d)(-)?(\d\d)$/i;
        function negativeValues(series) {
          var i2, j2, data;
          for (i2 = 0; i2 < series.length; i2++) {
            data = series[i2].data;
            for (j2 = 0; j2 < data.length; j2++) {
              if (data[j2][1] < 0) {
                return true;
              }
            }
          }
          return false;
        }
        function toStr(n2) {
          return "" + n2;
        }
        function toFloat(n2) {
          return parseFloat(n2);
        }
        function toDate2(n2) {
          var matches, year, month, day;
          if (typeof n2 !== "object") {
            if (typeof n2 === "number") {
              n2 = new Date(n2 * 1e3);
            } else {
              n2 = toStr(n2);
              if (matches = n2.match(DATE_PATTERN)) {
                year = parseInt(matches[1], 10);
                month = parseInt(matches[3], 10) - 1;
                day = parseInt(matches[5], 10);
                return new Date(year, month, day);
              } else {
                var str = n2.replace(/ /, "T").replace(" ", "").replace("UTC", "Z");
                n2 = new Date(Date.parse(str) || n2);
              }
            }
          }
          return n2;
        }
        function toArr(n2) {
          if (!isArray2(n2)) {
            var arr = [], i2;
            for (i2 in n2) {
              if (n2.hasOwnProperty(i2)) {
                arr.push([i2, n2[i2]]);
              }
            }
            n2 = arr;
          }
          return n2;
        }
        function jsOptionsFunc(defaultOptions3, hideLegend2, setTitle2, setMin2, setMax2, setStacked2, setXtitle2, setYtitle2) {
          return function(chart, opts, chartOptions) {
            var series = chart.data;
            var options = merge2({}, defaultOptions3);
            options = merge2(options, chartOptions || {});
            if (chart.singleSeriesFormat || "legend" in opts) {
              hideLegend2(options, opts.legend, chart.singleSeriesFormat);
            }
            if (opts.title) {
              setTitle2(options, opts.title);
            }
            if ("min" in opts) {
              setMin2(options, opts.min);
            } else if (!negativeValues(series)) {
              setMin2(options, 0);
            }
            if (opts.max) {
              setMax2(options, opts.max);
            }
            if ("stacked" in opts) {
              setStacked2(options, opts.stacked);
            }
            if (opts.colors) {
              options.colors = opts.colors;
            }
            if (opts.xtitle) {
              setXtitle2(options, opts.xtitle);
            }
            if (opts.ytitle) {
              setYtitle2(options, opts.ytitle);
            }
            options = merge2(options, opts.library || {});
            return options;
          };
        }
        function sortByTime(a2, b2) {
          return a2[0].getTime() - b2[0].getTime();
        }
        function sortByNumberSeries(a2, b2) {
          return a2[0] - b2[0];
        }
        function sortByNumber(a2, b2) {
          return a2 - b2;
        }
        function isMinute(d2) {
          return d2.getMilliseconds() === 0 && d2.getSeconds() === 0;
        }
        function isHour(d2) {
          return isMinute(d2) && d2.getMinutes() === 0;
        }
        function isDay(d2) {
          return isHour(d2) && d2.getHours() === 0;
        }
        function isWeek(d2, dayOfWeek) {
          return isDay(d2) && d2.getDay() === dayOfWeek;
        }
        function isMonth(d2) {
          return isDay(d2) && d2.getDate() === 1;
        }
        function isYear(d2) {
          return isMonth(d2) && d2.getMonth() === 0;
        }
        function isDate(obj) {
          return !isNaN(toDate2(obj)) && toStr(obj).length >= 6;
        }
        function isNumber2(obj) {
          return typeof obj === "number";
        }
        var byteSuffixes = ["bytes", "KB", "MB", "GB", "TB", "PB", "EB"];
        function formatValue(pre, value, options, axis) {
          pre = pre || "";
          if (options.prefix) {
            if (value < 0) {
              value = value * -1;
              pre += "-";
            }
            pre += options.prefix;
          }
          var suffix = options.suffix || "";
          var precision = options.precision;
          var round3 = options.round;
          if (options.byteScale) {
            var suffixIdx;
            var baseValue = axis ? options.byteScale : value;
            if (baseValue >= 1152921504606847e3) {
              value /= 1152921504606847e3;
              suffixIdx = 6;
            } else if (baseValue >= 1125899906842624) {
              value /= 1125899906842624;
              suffixIdx = 5;
            } else if (baseValue >= 1099511627776) {
              value /= 1099511627776;
              suffixIdx = 4;
            } else if (baseValue >= 1073741824) {
              value /= 1073741824;
              suffixIdx = 3;
            } else if (baseValue >= 1048576) {
              value /= 1048576;
              suffixIdx = 2;
            } else if (baseValue >= 1024) {
              value /= 1024;
              suffixIdx = 1;
            } else {
              suffixIdx = 0;
            }
            if (precision === void 0 && round3 === void 0) {
              if (value >= 1023.5) {
                if (suffixIdx < byteSuffixes.length - 1) {
                  value = 1;
                  suffixIdx += 1;
                }
              }
              precision = value >= 1e3 ? 4 : 3;
            }
            suffix = " " + byteSuffixes[suffixIdx];
          }
          if (precision !== void 0 && round3 !== void 0) {
            throw Error("Use either round or precision, not both");
          }
          if (!axis) {
            if (precision !== void 0) {
              value = value.toPrecision(precision);
              if (!options.zeros) {
                value = parseFloat(value);
              }
            }
            if (round3 !== void 0) {
              if (round3 < 0) {
                var num = Math.pow(10, -1 * round3);
                value = parseInt((1 * value / num).toFixed(0)) * num;
              } else {
                value = value.toFixed(round3);
                if (!options.zeros) {
                  value = parseFloat(value);
                }
              }
            }
          }
          if (options.thousands || options.decimal) {
            value = toStr(value);
            var parts = value.split(".");
            value = parts[0];
            if (options.thousands) {
              value = value.replace(/\B(?=(\d{3})+(?!\d))/g, options.thousands);
            }
            if (parts.length > 1) {
              value += (options.decimal || ".") + parts[1];
            }
          }
          return pre + value + suffix;
        }
        function seriesOption(chart, series, option) {
          if (option in series) {
            return series[option];
          } else if (option in chart.options) {
            return chart.options[option];
          }
          return null;
        }
        function allZeros(data) {
          var i2, j2, d2;
          for (i2 = 0; i2 < data.length; i2++) {
            d2 = data[i2].data;
            for (j2 = 0; j2 < d2.length; j2++) {
              if (d2[j2][1] != 0) {
                return false;
              }
            }
          }
          return true;
        }
        var baseOptions = {
          maintainAspectRatio: false,
          animation: false,
          plugins: {
            legend: {},
            tooltip: {
              displayColors: false,
              callbacks: {}
            },
            title: {
              font: {
                size: 20
              },
              color: "#333"
            }
          },
          interaction: {}
        };
        var defaultOptions$2 = {
          scales: {
            y: {
              ticks: {
                maxTicksLimit: 4
              },
              title: {
                font: {
                  size: 16
                },
                color: "#333"
              },
              grid: {}
            },
            x: {
              grid: {
                drawOnChartArea: false
              },
              title: {
                font: {
                  size: 16
                },
                color: "#333"
              },
              time: {},
              ticks: {}
            }
          }
        };
        var defaultColors = [
          "#3366CC",
          "#DC3912",
          "#FF9900",
          "#109618",
          "#990099",
          "#3B3EAC",
          "#0099C6",
          "#DD4477",
          "#66AA00",
          "#B82E2E",
          "#316395",
          "#994499",
          "#22AA99",
          "#AAAA11",
          "#6633CC",
          "#E67300",
          "#8B0707",
          "#329262",
          "#5574A6",
          "#651067"
        ];
        var hideLegend$2 = function(options, legend, hideLegend2) {
          if (legend !== void 0) {
            options.plugins.legend.display = !!legend;
            if (legend && legend !== true) {
              options.plugins.legend.position = legend;
            }
          } else if (hideLegend2) {
            options.plugins.legend.display = false;
          }
        };
        var setTitle$2 = function(options, title) {
          options.plugins.title.display = true;
          options.plugins.title.text = title;
        };
        var setMin$2 = function(options, min2) {
          if (min2 !== null) {
            options.scales.y.min = toFloat(min2);
          }
        };
        var setMax$2 = function(options, max2) {
          options.scales.y.max = toFloat(max2);
        };
        var setBarMin$1 = function(options, min2) {
          if (min2 !== null) {
            options.scales.x.min = toFloat(min2);
          }
        };
        var setBarMax$1 = function(options, max2) {
          options.scales.x.max = toFloat(max2);
        };
        var setStacked$2 = function(options, stacked) {
          options.scales.x.stacked = !!stacked;
          options.scales.y.stacked = !!stacked;
        };
        var setXtitle$2 = function(options, title) {
          options.scales.x.title.display = true;
          options.scales.x.title.text = title;
        };
        var setYtitle$2 = function(options, title) {
          options.scales.y.title.display = true;
          options.scales.y.title.text = title;
        };
        var addOpacity = function(hex2, opacity) {
          var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex2);
          return result ? "rgba(" + parseInt(result[1], 16) + ", " + parseInt(result[2], 16) + ", " + parseInt(result[3], 16) + ", " + opacity + ")" : hex2;
        };
        var notnull = function(x2) {
          return x2 != null;
        };
        var setLabelSize = function(chart, data, options) {
          var maxLabelSize = Math.ceil(chart.element.offsetWidth / 4 / data.labels.length);
          if (maxLabelSize > 25) {
            maxLabelSize = 25;
          } else if (maxLabelSize < 10) {
            maxLabelSize = 10;
          }
          if (!options.scales.x.ticks.callback) {
            options.scales.x.ticks.callback = function(value) {
              value = toStr(this.getLabelForValue(value));
              if (value.length > maxLabelSize) {
                return value.substring(0, maxLabelSize - 2) + "...";
              } else {
                return value;
              }
            };
          }
        };
        var setFormatOptions$1 = function(chart, options, chartType) {
          var formatOptions = {
            prefix: chart.options.prefix,
            suffix: chart.options.suffix,
            thousands: chart.options.thousands,
            decimal: chart.options.decimal,
            precision: chart.options.precision,
            round: chart.options.round,
            zeros: chart.options.zeros
          };
          if (chart.options.bytes) {
            var series = chart.data;
            if (chartType === "pie") {
              series = [{ data: series }];
            }
            var max2 = 0;
            for (var i2 = 0; i2 < series.length; i2++) {
              var s2 = series[i2];
              for (var j2 = 0; j2 < s2.data.length; j2++) {
                if (s2.data[j2][1] > max2) {
                  max2 = s2.data[j2][1];
                }
              }
            }
            var scale = 1;
            while (max2 >= 1024) {
              scale *= 1024;
              max2 /= 1024;
            }
            formatOptions.byteScale = scale;
          }
          if (chartType !== "pie") {
            var axis = options.scales.y;
            if (chartType === "bar") {
              axis = options.scales.x;
            }
            if (formatOptions.byteScale) {
              if (!axis.ticks.stepSize) {
                axis.ticks.stepSize = formatOptions.byteScale / 2;
              }
              if (!axis.ticks.maxTicksLimit) {
                axis.ticks.maxTicksLimit = 4;
              }
            }
            if (!axis.ticks.callback) {
              axis.ticks.callback = function(value) {
                return formatValue("", value, formatOptions, true);
              };
            }
          }
          if (!options.plugins.tooltip.callbacks.label) {
            if (chartType === "scatter") {
              options.plugins.tooltip.callbacks.label = function(context) {
                var label = context.dataset.label || "";
                if (label) {
                  label += ": ";
                }
                return label + "(" + context.label + ", " + context.formattedValue + ")";
              };
            } else if (chartType === "bubble") {
              options.plugins.tooltip.callbacks.label = function(context) {
                var label = context.dataset.label || "";
                if (label) {
                  label += ": ";
                }
                var dataPoint = context.raw;
                return label + "(" + dataPoint.x + ", " + dataPoint.y + ", " + dataPoint.v + ")";
              };
            } else if (chartType === "pie") {
              options.plugins.tooltip.callbacks.label = function(context) {
                var dataLabel = context.label;
                var value = ": ";
                if (isArray2(dataLabel)) {
                  dataLabel = dataLabel.slice();
                  dataLabel[0] += value;
                } else {
                  dataLabel += value;
                }
                return formatValue(dataLabel, context.parsed, formatOptions);
              };
            } else {
              var valueLabel = chartType === "bar" ? "x" : "y";
              options.plugins.tooltip.callbacks.label = function(context) {
                if (context.parsed[valueLabel] === null) {
                  return;
                }
                var label = context.dataset.label || "";
                if (label) {
                  label += ": ";
                }
                return formatValue(label, context.parsed[valueLabel], formatOptions);
              };
            }
          }
        };
        var jsOptions$2 = jsOptionsFunc(merge2(baseOptions, defaultOptions$2), hideLegend$2, setTitle$2, setMin$2, setMax$2, setStacked$2, setXtitle$2, setYtitle$2);
        var createDataTable = function(chart, options, chartType) {
          var datasets = [];
          var labels = [];
          var colors2 = chart.options.colors || defaultColors;
          var day = true;
          var week = true;
          var dayOfWeek;
          var month = true;
          var year = true;
          var hour = true;
          var minute = true;
          var series = chart.data;
          var max2 = 0;
          if (chartType === "bubble") {
            for (var i$1 = 0; i$1 < series.length; i$1++) {
              var s$1 = series[i$1];
              for (var j$1 = 0; j$1 < s$1.data.length; j$1++) {
                if (s$1.data[j$1][2] > max2) {
                  max2 = s$1.data[j$1][2];
                }
              }
            }
          }
          var i2, j2, s2, d2, key, rows = [], rows2 = [];
          if (chartType === "bar" || chartType === "column" || chart.xtype !== "number" && chart.xtype !== "bubble") {
            var sortedLabels = [];
            for (i2 = 0; i2 < series.length; i2++) {
              s2 = series[i2];
              for (j2 = 0; j2 < s2.data.length; j2++) {
                d2 = s2.data[j2];
                key = chart.xtype == "datetime" ? d2[0].getTime() : d2[0];
                if (!rows[key]) {
                  rows[key] = new Array(series.length);
                }
                rows[key][i2] = toFloat(d2[1]);
                if (sortedLabels.indexOf(key) === -1) {
                  sortedLabels.push(key);
                }
              }
            }
            if (chart.xtype === "datetime" || chart.xtype === "number") {
              sortedLabels.sort(sortByNumber);
            }
            for (j2 = 0; j2 < series.length; j2++) {
              rows2.push([]);
            }
            var value;
            var k2;
            for (k2 = 0; k2 < sortedLabels.length; k2++) {
              i2 = sortedLabels[k2];
              if (chart.xtype === "datetime") {
                value = new Date(toFloat(i2));
                day = day && isDay(value);
                if (!dayOfWeek) {
                  dayOfWeek = value.getDay();
                }
                week = week && isWeek(value, dayOfWeek);
                month = month && isMonth(value);
                year = year && isYear(value);
                hour = hour && isHour(value);
                minute = minute && isMinute(value);
              } else {
                value = i2;
              }
              labels.push(value);
              for (j2 = 0; j2 < series.length; j2++) {
                rows2[j2].push(rows[i2][j2] === void 0 ? null : rows[i2][j2]);
              }
            }
          } else {
            for (var i$2 = 0; i$2 < series.length; i$2++) {
              var s$2 = series[i$2];
              var d$1 = [];
              for (var j$2 = 0; j$2 < s$2.data.length; j$2++) {
                var point = {
                  x: toFloat(s$2.data[j$2][0]),
                  y: toFloat(s$2.data[j$2][1])
                };
                if (chartType === "bubble") {
                  point.r = toFloat(s$2.data[j$2][2]) * 20 / max2;
                  point.v = s$2.data[j$2][2];
                }
                d$1.push(point);
              }
              rows2.push(d$1);
            }
          }
          var color2;
          var backgroundColor;
          for (i2 = 0; i2 < series.length; i2++) {
            s2 = series[i2];
            if (chart.options.colors && chart.singleSeriesFormat && (chartType === "bar" || chartType === "column") && !s2.color && isArray2(chart.options.colors) && !isArray2(chart.options.colors[0])) {
              color2 = colors2;
              backgroundColor = [];
              for (var j$3 = 0; j$3 < colors2.length; j$3++) {
                backgroundColor[j$3] = addOpacity(color2[j$3], 0.5);
              }
            } else {
              color2 = s2.color || colors2[i2];
              backgroundColor = chartType !== "line" ? addOpacity(color2, 0.5) : color2;
            }
            var dataset = {
              label: s2.name || "",
              data: rows2[i2],
              fill: chartType === "area",
              borderColor: color2,
              backgroundColor,
              borderWidth: 2
            };
            var pointChart = chartType === "line" || chartType === "area" || chartType === "scatter" || chartType === "bubble";
            if (pointChart) {
              dataset.pointBackgroundColor = color2;
              dataset.pointHoverBackgroundColor = color2;
              dataset.pointHitRadius = 50;
            }
            if (chartType === "bubble") {
              dataset.pointBackgroundColor = backgroundColor;
              dataset.pointHoverBackgroundColor = backgroundColor;
              dataset.pointHoverBorderWidth = 2;
            }
            if (s2.stack) {
              dataset.stack = s2.stack;
            }
            var curve = seriesOption(chart, s2, "curve");
            if (curve === false) {
              dataset.tension = 0;
            } else if (pointChart) {
              dataset.tension = 0.4;
            }
            var points = seriesOption(chart, s2, "points");
            if (points === false) {
              dataset.pointRadius = 0;
              dataset.pointHoverRadius = 0;
            }
            dataset = merge2(dataset, chart.options.dataset || {});
            dataset = merge2(dataset, s2.library || {});
            dataset = merge2(dataset, s2.dataset || {});
            datasets.push(dataset);
          }
          var xmin = chart.options.xmin;
          var xmax = chart.options.xmax;
          if (chart.xtype === "datetime") {
            if (notnull(xmin)) {
              options.scales.x.ticks.min = toDate2(xmin).getTime();
            }
            if (notnull(xmax)) {
              options.scales.x.ticks.max = toDate2(xmax).getTime();
            }
          } else if (chart.xtype === "number") {
            if (notnull(xmin)) {
              options.scales.x.ticks.min = xmin;
            }
            if (notnull(xmax)) {
              options.scales.x.ticks.max = xmax;
            }
          }
          if (chart.xtype === "datetime" && labels.length === 0) {
            if (notnull(xmin)) {
              labels.push(toDate2(xmin));
            }
            if (notnull(xmax)) {
              labels.push(toDate2(xmax));
            }
            day = false;
            week = false;
            month = false;
            year = false;
            hour = false;
            minute = false;
          }
          if (chart.xtype === "datetime" && labels.length > 0) {
            var minTime = (notnull(xmin) ? toDate2(xmin) : labels[0]).getTime();
            var maxTime = (notnull(xmax) ? toDate2(xmax) : labels[0]).getTime();
            for (i2 = 1; i2 < labels.length; i2++) {
              var value$1 = labels[i2].getTime();
              if (value$1 < minTime) {
                minTime = value$1;
              }
              if (value$1 > maxTime) {
                maxTime = value$1;
              }
            }
            var timeDiff = (maxTime - minTime) / (86400 * 1e3);
            if (!options.scales.x.time.unit) {
              var step;
              if (year || timeDiff > 365 * 10) {
                options.scales.x.time.unit = "year";
                step = 365;
              } else if (month || timeDiff > 30 * 10) {
                options.scales.x.time.unit = "month";
                step = 30;
              } else if (day || timeDiff > 10) {
                options.scales.x.time.unit = "day";
                step = 1;
              } else if (hour || timeDiff > 0.5) {
                options.scales.x.time.displayFormats = { hour: "MMM d, h a" };
                options.scales.x.time.unit = "hour";
                step = 1 / 24;
              } else if (minute) {
                options.scales.x.time.displayFormats = { minute: "h:mm a" };
                options.scales.x.time.unit = "minute";
                step = 1 / 24 / 60;
              }
              if (step && timeDiff > 0) {
                var width = chart.element.offsetWidth;
                if (width > 0) {
                  var unitStepSize = Math.ceil(timeDiff / step / (width / 100));
                  if (week && step === 1) {
                    unitStepSize = Math.ceil(unitStepSize / 7) * 7;
                  }
                  options.scales.x.time.stepSize = unitStepSize;
                }
              }
            }
            if (!options.scales.x.time.tooltipFormat) {
              if (day) {
                options.scales.x.time.tooltipFormat = "PP";
              } else if (hour) {
                options.scales.x.time.tooltipFormat = "MMM d, h a";
              } else if (minute) {
                options.scales.x.time.tooltipFormat = "h:mm a";
              }
            }
          }
          var data = {
            labels,
            datasets
          };
          return data;
        };
        var defaultExport$2 = function defaultExport2(library) {
          this.name = "chartjs";
          this.library = library;
        };
        defaultExport$2.prototype.renderLineChart = function renderLineChart(chart, chartType) {
          var chartOptions = {};
          if (!chart.options.max && allZeros(chart.data)) {
            chartOptions.max = 1;
          }
          var options = jsOptions$2(chart, merge2(chartOptions, chart.options));
          setFormatOptions$1(chart, options, chartType);
          var data = createDataTable(chart, options, chartType || "line");
          if (chart.xtype === "number") {
            options.scales.x.type = options.scales.x.type || "linear";
            options.scales.x.position = options.scales.x.position || "bottom";
          } else {
            options.scales.x.type = chart.xtype === "string" ? "category" : "time";
          }
          this.drawChart(chart, "line", data, options);
        };
        defaultExport$2.prototype.renderPieChart = function renderPieChart(chart) {
          var options = merge2({}, baseOptions);
          if (chart.options.donut) {
            options.cutout = "50%";
          }
          if ("legend" in chart.options) {
            hideLegend$2(options, chart.options.legend);
          }
          if (chart.options.title) {
            setTitle$2(options, chart.options.title);
          }
          options = merge2(options, chart.options.library || {});
          setFormatOptions$1(chart, options, "pie");
          var labels = [];
          var values = [];
          for (var i2 = 0; i2 < chart.data.length; i2++) {
            var point = chart.data[i2];
            labels.push(point[0]);
            values.push(point[1]);
          }
          var dataset = {
            data: values,
            backgroundColor: chart.options.colors || defaultColors
          };
          dataset = merge2(dataset, chart.options.dataset || {});
          var data = {
            labels,
            datasets: [dataset]
          };
          this.drawChart(chart, "pie", data, options);
        };
        defaultExport$2.prototype.renderColumnChart = function renderColumnChart(chart, chartType) {
          var options;
          if (chartType === "bar") {
            var barOptions = merge2(baseOptions, defaultOptions$2);
            barOptions.indexAxis = "y";
            barOptions.scales.x.grid.drawOnChartArea = true;
            barOptions.scales.y.grid.drawOnChartArea = false;
            delete barOptions.scales.y.ticks.maxTicksLimit;
            options = jsOptionsFunc(barOptions, hideLegend$2, setTitle$2, setBarMin$1, setBarMax$1, setStacked$2, setXtitle$2, setYtitle$2)(chart, chart.options);
          } else {
            options = jsOptions$2(chart, chart.options);
          }
          setFormatOptions$1(chart, options, chartType);
          var data = createDataTable(chart, options, "column");
          if (chartType !== "bar") {
            setLabelSize(chart, data, options);
          }
          this.drawChart(chart, "bar", data, options);
        };
        defaultExport$2.prototype.renderAreaChart = function renderAreaChart(chart) {
          this.renderLineChart(chart, "area");
        };
        defaultExport$2.prototype.renderBarChart = function renderBarChart(chart) {
          this.renderColumnChart(chart, "bar");
        };
        defaultExport$2.prototype.renderScatterChart = function renderScatterChart(chart, chartType) {
          chartType = chartType || "scatter";
          var options = jsOptions$2(chart, chart.options);
          setFormatOptions$1(chart, options, chartType);
          if (!("showLine" in options)) {
            options.showLine = false;
          }
          var data = createDataTable(chart, options, chartType);
          options.scales.x.type = options.scales.x.type || "linear";
          options.scales.x.position = options.scales.x.position || "bottom";
          if (!("mode" in options.interaction)) {
            options.interaction.mode = "nearest";
          }
          this.drawChart(chart, chartType, data, options);
        };
        defaultExport$2.prototype.renderBubbleChart = function renderBubbleChart(chart) {
          this.renderScatterChart(chart, "bubble");
        };
        defaultExport$2.prototype.destroy = function destroy(chart) {
          if (chart.chart) {
            chart.chart.destroy();
          }
        };
        defaultExport$2.prototype.drawChart = function drawChart(chart, type, data, options) {
          this.destroy(chart);
          if (chart.destroyed) {
            return;
          }
          var chartOptions = {
            type,
            data,
            options
          };
          if (chart.options.code) {
            window.console.log("new Chart(ctx, " + JSON.stringify(chartOptions) + ");");
          }
          chart.element.innerHTML = "<canvas></canvas>";
          var ctx = chart.element.getElementsByTagName("CANVAS")[0];
          chart.chart = new this.library(ctx, chartOptions);
        };
        var defaultOptions$1 = {
          chart: {},
          xAxis: {
            title: {
              text: null
            },
            labels: {
              style: {
                fontSize: "12px"
              }
            }
          },
          yAxis: {
            title: {
              text: null
            },
            labels: {
              style: {
                fontSize: "12px"
              }
            }
          },
          title: {
            text: null
          },
          credits: {
            enabled: false
          },
          legend: {
            borderWidth: 0
          },
          tooltip: {
            style: {
              fontSize: "12px"
            }
          },
          plotOptions: {
            areaspline: {},
            area: {},
            series: {
              marker: {}
            }
          },
          time: {
            useUTC: false
          }
        };
        var hideLegend$1 = function(options, legend, hideLegend2) {
          if (legend !== void 0) {
            options.legend.enabled = !!legend;
            if (legend && legend !== true) {
              if (legend === "top" || legend === "bottom") {
                options.legend.verticalAlign = legend;
              } else {
                options.legend.layout = "vertical";
                options.legend.verticalAlign = "middle";
                options.legend.align = legend;
              }
            }
          } else if (hideLegend2) {
            options.legend.enabled = false;
          }
        };
        var setTitle$1 = function(options, title) {
          options.title.text = title;
        };
        var setMin$1 = function(options, min2) {
          options.yAxis.min = min2;
        };
        var setMax$1 = function(options, max2) {
          options.yAxis.max = max2;
        };
        var setStacked$1 = function(options, stacked) {
          var stackedValue = stacked ? stacked === true ? "normal" : stacked : null;
          options.plotOptions.series.stacking = stackedValue;
          options.plotOptions.area.stacking = stackedValue;
          options.plotOptions.areaspline.stacking = stackedValue;
        };
        var setXtitle$1 = function(options, title) {
          options.xAxis.title.text = title;
        };
        var setYtitle$1 = function(options, title) {
          options.yAxis.title.text = title;
        };
        var jsOptions$1 = jsOptionsFunc(defaultOptions$1, hideLegend$1, setTitle$1, setMin$1, setMax$1, setStacked$1, setXtitle$1, setYtitle$1);
        var setFormatOptions = function(chart, options, chartType) {
          var formatOptions = {
            prefix: chart.options.prefix,
            suffix: chart.options.suffix,
            thousands: chart.options.thousands,
            decimal: chart.options.decimal,
            precision: chart.options.precision,
            round: chart.options.round,
            zeros: chart.options.zeros
          };
          if (chartType !== "pie" && !options.yAxis.labels.formatter) {
            options.yAxis.labels.formatter = function() {
              return formatValue("", this.value, formatOptions);
            };
          }
          if (!options.tooltip.pointFormatter && !options.tooltip.pointFormat) {
            options.tooltip.pointFormatter = function() {
              return '<span style="color:' + this.color + '">\u25CF</span> ' + formatValue(this.series.name + ": <b>", this.y, formatOptions) + "</b><br/>";
            };
          }
        };
        var defaultExport$1 = function defaultExport2(library) {
          this.name = "highcharts";
          this.library = library;
        };
        defaultExport$1.prototype.renderLineChart = function renderLineChart(chart, chartType) {
          chartType = chartType || "spline";
          var chartOptions = {};
          if (chartType === "areaspline") {
            chartOptions = {
              plotOptions: {
                areaspline: {
                  stacking: "normal"
                },
                area: {
                  stacking: "normal"
                },
                series: {
                  marker: {
                    enabled: false
                  }
                }
              }
            };
          }
          if (chart.options.curve === false) {
            if (chartType === "areaspline") {
              chartType = "area";
            } else if (chartType === "spline") {
              chartType = "line";
            }
          }
          var options = jsOptions$1(chart, chart.options, chartOptions), data, i2, j2;
          if (chart.xtype === "number") {
            options.xAxis.type = options.xAxis.type || "linear";
          } else {
            options.xAxis.type = chart.xtype === "string" ? "category" : "datetime";
          }
          if (!options.chart.type) {
            options.chart.type = chartType;
          }
          setFormatOptions(chart, options, chartType);
          var series = chart.data;
          for (i2 = 0; i2 < series.length; i2++) {
            series[i2].name = series[i2].name || "Value";
            data = series[i2].data;
            if (chart.xtype === "datetime") {
              for (j2 = 0; j2 < data.length; j2++) {
                data[j2][0] = data[j2][0].getTime();
              }
            }
            series[i2].marker = { symbol: "circle" };
            if (chart.options.points === false) {
              series[i2].marker.enabled = false;
            }
          }
          this.drawChart(chart, series, options);
        };
        defaultExport$1.prototype.renderScatterChart = function renderScatterChart(chart) {
          var options = jsOptions$1(chart, chart.options, {});
          options.chart.type = "scatter";
          this.drawChart(chart, chart.data, options);
        };
        defaultExport$1.prototype.renderPieChart = function renderPieChart(chart) {
          var chartOptions = merge2(defaultOptions$1, {});
          if (chart.options.colors) {
            chartOptions.colors = chart.options.colors;
          }
          if (chart.options.donut) {
            chartOptions.plotOptions = { pie: { innerSize: "50%" } };
          }
          if ("legend" in chart.options) {
            hideLegend$1(chartOptions, chart.options.legend);
          }
          if (chart.options.title) {
            setTitle$1(chartOptions, chart.options.title);
          }
          var options = merge2(chartOptions, chart.options.library || {});
          setFormatOptions(chart, options, "pie");
          var series = [{
            type: "pie",
            name: chart.options.label || "Value",
            data: chart.data
          }];
          this.drawChart(chart, series, options);
        };
        defaultExport$1.prototype.renderColumnChart = function renderColumnChart(chart, chartType) {
          chartType = chartType || "column";
          var series = chart.data;
          var options = jsOptions$1(chart, chart.options), i2, j2, s2, d2, rows = [], categories = [];
          options.chart.type = chartType;
          setFormatOptions(chart, options, chartType);
          for (i2 = 0; i2 < series.length; i2++) {
            s2 = series[i2];
            for (j2 = 0; j2 < s2.data.length; j2++) {
              d2 = s2.data[j2];
              if (!rows[d2[0]]) {
                rows[d2[0]] = new Array(series.length);
                categories.push(d2[0]);
              }
              rows[d2[0]][i2] = d2[1];
            }
          }
          if (chart.xtype === "number") {
            categories.sort(sortByNumber);
          }
          options.xAxis.categories = categories;
          var newSeries = [], d22;
          for (i2 = 0; i2 < series.length; i2++) {
            d2 = [];
            for (j2 = 0; j2 < categories.length; j2++) {
              d2.push(rows[categories[j2]][i2] || 0);
            }
            d22 = {
              name: series[i2].name || "Value",
              data: d2
            };
            if (series[i2].stack) {
              d22.stack = series[i2].stack;
            }
            newSeries.push(d22);
          }
          this.drawChart(chart, newSeries, options);
        };
        defaultExport$1.prototype.renderBarChart = function renderBarChart(chart) {
          this.renderColumnChart(chart, "bar");
        };
        defaultExport$1.prototype.renderAreaChart = function renderAreaChart(chart) {
          this.renderLineChart(chart, "areaspline");
        };
        defaultExport$1.prototype.destroy = function destroy(chart) {
          if (chart.chart) {
            chart.chart.destroy();
          }
        };
        defaultExport$1.prototype.drawChart = function drawChart(chart, data, options) {
          this.destroy(chart);
          if (chart.destroyed) {
            return;
          }
          options.chart.renderTo = chart.element.id;
          options.series = data;
          if (chart.options.code) {
            window.console.log("new Highcharts.Chart(" + JSON.stringify(options) + ");");
          }
          chart.chart = new this.library.Chart(options);
        };
        var loaded = {};
        var callbacks = [];
        var defaultOptions2 = {
          chartArea: {},
          fontName: "'Lucida Grande', 'Lucida Sans Unicode', Verdana, Arial, Helvetica, sans-serif",
          pointSize: 6,
          legend: {
            textStyle: {
              fontSize: 12,
              color: "#444"
            },
            alignment: "center",
            position: "right"
          },
          curveType: "function",
          hAxis: {
            textStyle: {
              color: "#666",
              fontSize: 12
            },
            titleTextStyle: {},
            gridlines: {
              color: "transparent"
            },
            baselineColor: "#ccc",
            viewWindow: {}
          },
          vAxis: {
            textStyle: {
              color: "#666",
              fontSize: 12
            },
            titleTextStyle: {},
            baselineColor: "#ccc",
            viewWindow: {}
          },
          tooltip: {
            textStyle: {
              color: "#666",
              fontSize: 12
            }
          }
        };
        var hideLegend = function(options, legend, hideLegend2) {
          if (legend !== void 0) {
            var position;
            if (!legend) {
              position = "none";
            } else if (legend === true) {
              position = "right";
            } else {
              position = legend;
            }
            options.legend.position = position;
          } else if (hideLegend2) {
            options.legend.position = "none";
          }
        };
        var setTitle = function(options, title) {
          options.title = title;
          options.titleTextStyle = { color: "#333", fontSize: "20px" };
        };
        var setMin = function(options, min2) {
          options.vAxis.viewWindow.min = min2;
        };
        var setMax = function(options, max2) {
          options.vAxis.viewWindow.max = max2;
        };
        var setBarMin = function(options, min2) {
          options.hAxis.viewWindow.min = min2;
        };
        var setBarMax = function(options, max2) {
          options.hAxis.viewWindow.max = max2;
        };
        var setStacked = function(options, stacked) {
          options.isStacked = stacked ? stacked : false;
        };
        var setXtitle = function(options, title) {
          options.hAxis.title = title;
          options.hAxis.titleTextStyle.italic = false;
        };
        var setYtitle = function(options, title) {
          options.vAxis.title = title;
          options.vAxis.titleTextStyle.italic = false;
        };
        var jsOptions = jsOptionsFunc(defaultOptions2, hideLegend, setTitle, setMin, setMax, setStacked, setXtitle, setYtitle);
        var resize = function(callback2) {
          if (window.attachEvent) {
            window.attachEvent("onresize", callback2);
          } else if (window.addEventListener) {
            window.addEventListener("resize", callback2, true);
          }
          callback2();
        };
        var defaultExport = function defaultExport2(library) {
          this.name = "google";
          this.library = library;
        };
        defaultExport.prototype.renderLineChart = function renderLineChart(chart) {
          var this$1 = this;
          this.waitForLoaded(chart, function() {
            var chartOptions = {};
            if (chart.options.curve === false) {
              chartOptions.curveType = "none";
            }
            if (chart.options.points === false) {
              chartOptions.pointSize = 0;
            }
            var options = jsOptions(chart, chart.options, chartOptions);
            var data = this$1.createDataTable(chart.data, chart.xtype);
            this$1.drawChart(chart, "LineChart", data, options);
          });
        };
        defaultExport.prototype.renderPieChart = function renderPieChart(chart) {
          var this$1 = this;
          this.waitForLoaded(chart, function() {
            var chartOptions = {
              chartArea: {
                top: "10%",
                height: "80%"
              },
              legend: {}
            };
            if (chart.options.colors) {
              chartOptions.colors = chart.options.colors;
            }
            if (chart.options.donut) {
              chartOptions.pieHole = 0.5;
            }
            if ("legend" in chart.options) {
              hideLegend(chartOptions, chart.options.legend);
            }
            if (chart.options.title) {
              setTitle(chartOptions, chart.options.title);
            }
            var options = merge2(merge2(defaultOptions2, chartOptions), chart.options.library || {});
            var data = new this$1.library.visualization.DataTable();
            data.addColumn("string", "");
            data.addColumn("number", "Value");
            data.addRows(chart.data);
            this$1.drawChart(chart, "PieChart", data, options);
          });
        };
        defaultExport.prototype.renderColumnChart = function renderColumnChart(chart) {
          var this$1 = this;
          this.waitForLoaded(chart, function() {
            var options = jsOptions(chart, chart.options);
            var data = this$1.createDataTable(chart.data, chart.xtype);
            this$1.drawChart(chart, "ColumnChart", data, options);
          });
        };
        defaultExport.prototype.renderBarChart = function renderBarChart(chart) {
          var this$1 = this;
          this.waitForLoaded(chart, function() {
            var chartOptions = {
              hAxis: {
                gridlines: {
                  color: "#ccc"
                }
              }
            };
            var options = jsOptionsFunc(defaultOptions2, hideLegend, setTitle, setBarMin, setBarMax, setStacked, setXtitle, setYtitle)(chart, chart.options, chartOptions);
            var data = this$1.createDataTable(chart.data, chart.xtype);
            this$1.drawChart(chart, "BarChart", data, options);
          });
        };
        defaultExport.prototype.renderAreaChart = function renderAreaChart(chart) {
          var this$1 = this;
          this.waitForLoaded(chart, function() {
            var chartOptions = {
              isStacked: true,
              pointSize: 0,
              areaOpacity: 0.5
            };
            var options = jsOptions(chart, chart.options, chartOptions);
            var data = this$1.createDataTable(chart.data, chart.xtype);
            this$1.drawChart(chart, "AreaChart", data, options);
          });
        };
        defaultExport.prototype.renderGeoChart = function renderGeoChart(chart) {
          var this$1 = this;
          this.waitForLoaded(chart, "geochart", function() {
            var chartOptions = {
              legend: "none",
              colorAxis: {
                colors: chart.options.colors || ["#f6c7b6", "#ce502d"]
              }
            };
            var options = merge2(merge2(defaultOptions2, chartOptions), chart.options.library || {});
            var data = new this$1.library.visualization.DataTable();
            data.addColumn("string", "");
            data.addColumn("number", chart.options.label || "Value");
            data.addRows(chart.data);
            this$1.drawChart(chart, "GeoChart", data, options);
          });
        };
        defaultExport.prototype.renderScatterChart = function renderScatterChart(chart) {
          var this$1 = this;
          this.waitForLoaded(chart, function() {
            var chartOptions = {};
            var options = jsOptions(chart, chart.options, chartOptions);
            var series = chart.data, rows2 = [], i2, j2, data, d2;
            for (i2 = 0; i2 < series.length; i2++) {
              series[i2].name = series[i2].name || "Value";
              d2 = series[i2].data;
              for (j2 = 0; j2 < d2.length; j2++) {
                var row = new Array(series.length + 1);
                row[0] = d2[j2][0];
                row[i2 + 1] = d2[j2][1];
                rows2.push(row);
              }
            }
            data = new this$1.library.visualization.DataTable();
            data.addColumn("number", "");
            for (i2 = 0; i2 < series.length; i2++) {
              data.addColumn("number", series[i2].name);
            }
            data.addRows(rows2);
            this$1.drawChart(chart, "ScatterChart", data, options);
          });
        };
        defaultExport.prototype.renderTimeline = function renderTimeline(chart) {
          var this$1 = this;
          this.waitForLoaded(chart, "timeline", function() {
            var chartOptions = {
              legend: "none"
            };
            if (chart.options.colors) {
              chartOptions.colors = chart.options.colors;
            }
            var options = merge2(merge2(defaultOptions2, chartOptions), chart.options.library || {});
            var data = new this$1.library.visualization.DataTable();
            data.addColumn({ type: "string", id: "Name" });
            data.addColumn({ type: "date", id: "Start" });
            data.addColumn({ type: "date", id: "End" });
            data.addRows(chart.data);
            chart.element.style.lineHeight = "normal";
            this$1.drawChart(chart, "Timeline", data, options);
          });
        };
        defaultExport.prototype.destroy = function destroy(chart) {
          if (chart.chart) {
            chart.chart.clearChart();
          }
        };
        defaultExport.prototype.drawChart = function drawChart(chart, type, data, options) {
          this.destroy(chart);
          if (chart.destroyed) {
            return;
          }
          if (chart.options.code) {
            window.console.log("var data = new google.visualization.DataTable(" + data.toJSON() + ");\nvar chart = new google.visualization." + type + "(element);\nchart.draw(data, " + JSON.stringify(options) + ");");
          }
          chart.chart = new this.library.visualization[type](chart.element);
          resize(function() {
            chart.chart.draw(data, options);
          });
        };
        defaultExport.prototype.waitForLoaded = function waitForLoaded(chart, pack, callback2) {
          var this$1 = this;
          if (!callback2) {
            callback2 = pack;
            pack = "corechart";
          }
          callbacks.push({ pack, callback: callback2 });
          if (loaded[pack]) {
            this.runCallbacks();
          } else {
            loaded[pack] = true;
            var loadOptions = {
              packages: [pack],
              callback: function() {
                this$1.runCallbacks();
              }
            };
            var config2 = chart.__config();
            if (config2.language) {
              loadOptions.language = config2.language;
            }
            if (pack === "geochart" && config2.mapsApiKey) {
              loadOptions.mapsApiKey = config2.mapsApiKey;
            }
            this.library.charts.load("current", loadOptions);
          }
        };
        defaultExport.prototype.runCallbacks = function runCallbacks() {
          var cb, call;
          for (var i2 = 0; i2 < callbacks.length; i2++) {
            cb = callbacks[i2];
            call = this.library.visualization && (cb.pack === "corechart" && this.library.visualization.LineChart || cb.pack === "timeline" && this.library.visualization.Timeline || cb.pack === "geochart" && this.library.visualization.GeoChart);
            if (call) {
              cb.callback();
              callbacks.splice(i2, 1);
              i2--;
            }
          }
        };
        defaultExport.prototype.createDataTable = function createDataTable2(series, columnType) {
          var i2, j2, s2, d2, key, rows = [], sortedLabels = [];
          for (i2 = 0; i2 < series.length; i2++) {
            s2 = series[i2];
            series[i2].name = series[i2].name || "Value";
            for (j2 = 0; j2 < s2.data.length; j2++) {
              d2 = s2.data[j2];
              key = columnType === "datetime" ? d2[0].getTime() : d2[0];
              if (!rows[key]) {
                rows[key] = new Array(series.length);
                sortedLabels.push(key);
              }
              rows[key][i2] = toFloat(d2[1]);
            }
          }
          var rows2 = [];
          var day = true;
          var value;
          for (j2 = 0; j2 < sortedLabels.length; j2++) {
            i2 = sortedLabels[j2];
            if (columnType === "datetime") {
              value = new Date(toFloat(i2));
              day = day && isDay(value);
            } else if (columnType === "number") {
              value = toFloat(i2);
            } else {
              value = i2;
            }
            rows2.push([value].concat(rows[i2]));
          }
          if (columnType === "datetime") {
            rows2.sort(sortByTime);
          } else if (columnType === "number") {
            rows2.sort(sortByNumberSeries);
            for (i2 = 0; i2 < rows2.length; i2++) {
              rows2[i2][0] = toStr(rows2[i2][0]);
            }
            columnType = "string";
          }
          var data = new this.library.visualization.DataTable();
          columnType = columnType === "datetime" && day ? "date" : columnType;
          data.addColumn(columnType, "");
          for (i2 = 0; i2 < series.length; i2++) {
            data.addColumn("number", series[i2].name);
          }
          data.addRows(rows2);
          return data;
        };
        function formatSeriesData(data, keyType) {
          var r2 = [], j2, keyFunc;
          if (keyType === "number") {
            keyFunc = toFloat;
          } else if (keyType === "datetime") {
            keyFunc = toDate2;
          } else {
            keyFunc = toStr;
          }
          if (keyType === "bubble") {
            for (j2 = 0; j2 < data.length; j2++) {
              r2.push([toFloat(data[j2][0]), toFloat(data[j2][1]), toFloat(data[j2][2])]);
            }
          } else {
            for (j2 = 0; j2 < data.length; j2++) {
              r2.push([keyFunc(data[j2][0]), toFloat(data[j2][1])]);
            }
          }
          if (keyType === "datetime") {
            r2.sort(sortByTime);
          } else if (keyType === "number") {
            r2.sort(sortByNumberSeries);
          }
          return r2;
        }
        function detectXType(series, noDatetime, options) {
          if (dataEmpty(series)) {
            if ((options.xmin || options.xmax) && (!options.xmin || isDate(options.xmin)) && (!options.xmax || isDate(options.xmax))) {
              return "datetime";
            } else {
              return "number";
            }
          } else if (detectXTypeWithFunction(series, isNumber2)) {
            return "number";
          } else if (!noDatetime && detectXTypeWithFunction(series, isDate)) {
            return "datetime";
          } else {
            return "string";
          }
        }
        function detectXTypeWithFunction(series, func) {
          var i2, j2, data;
          for (i2 = 0; i2 < series.length; i2++) {
            data = toArr(series[i2].data);
            for (j2 = 0; j2 < data.length; j2++) {
              if (!func(data[j2][0])) {
                return false;
              }
            }
          }
          return true;
        }
        function copySeries(series) {
          var newSeries = [], i2, j2;
          for (i2 = 0; i2 < series.length; i2++) {
            var copy = {};
            for (j2 in series[i2]) {
              if (series[i2].hasOwnProperty(j2)) {
                copy[j2] = series[i2][j2];
              }
            }
            newSeries.push(copy);
          }
          return newSeries;
        }
        function processSeries(chart, keyType, noDatetime) {
          var i2;
          var opts = chart.options;
          var series = chart.rawData;
          chart.singleSeriesFormat = !isArray2(series) || typeof series[0] !== "object" || isArray2(series[0]);
          if (chart.singleSeriesFormat) {
            series = [{ name: opts.label, data: series }];
          }
          series = copySeries(series);
          for (i2 = 0; i2 < series.length; i2++) {
            series[i2].data = toArr(series[i2].data);
          }
          chart.xtype = keyType ? keyType : opts.discrete ? "string" : detectXType(series, noDatetime, opts);
          for (i2 = 0; i2 < series.length; i2++) {
            series[i2].data = formatSeriesData(series[i2].data, chart.xtype);
          }
          return series;
        }
        function processSimple(chart) {
          var perfectData = toArr(chart.rawData), i2;
          for (i2 = 0; i2 < perfectData.length; i2++) {
            perfectData[i2] = [toStr(perfectData[i2][0]), toFloat(perfectData[i2][1])];
          }
          return perfectData;
        }
        function dataEmpty(data, chartType) {
          if (chartType === "PieChart" || chartType === "GeoChart" || chartType === "Timeline") {
            return data.length === 0;
          } else {
            for (var i2 = 0; i2 < data.length; i2++) {
              if (data[i2].data.length > 0) {
                return false;
              }
            }
            return true;
          }
        }
        function addDownloadButton(chart) {
          var element = chart.element;
          var link = document.createElement("a");
          var download = chart.options.download;
          if (download === true) {
            download = {};
          } else if (typeof download === "string") {
            download = { filename: download };
          }
          link.download = download.filename || "chart.png";
          link.style.position = "absolute";
          link.style.top = "20px";
          link.style.right = "20px";
          link.style.zIndex = 1e3;
          link.style.lineHeight = "20px";
          link.target = "_blank";
          var image = document.createElement("img");
          image.alt = "Download";
          image.style.border = "none";
          image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAMAAAC6V+0/AAABCFBMVEUAAADMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMywEsqxAAAAV3RSTlMAAQIDBggJCgsMDQ4PERQaHB0eISIjJCouLzE0OTo/QUJHSUpLTU5PUllhYmltcHh5foWLjI+SlaCio6atr7S1t7m6vsHHyM7R2tze5Obo7fHz9ff5+/1hlxK2AAAA30lEQVQYGUXBhVYCQQBA0TdYWAt2d3d3YWAHyur7/z9xgD16Lw0DW+XKx+1GgX+FRzM3HWQWrHl5N/oapW5RPe0PkBu+UYeICvozTWZVK23Ao04B79oJrOsJDOoxkZoQPWgX29pHpCZEk7rEvQYiNSFq1UMqvlCjJkRBS1R8hb00Vb/TajtBL7nTHE1X1vyMQF732dQhyF2o6SAwrzP06iUQzvwsArlnzcOdrgBhJyHa1QOgO9U1GsKuvjUTjavliZYQ8nNPapG6sap/3nrIdJ6bOWzmX/fy0XVpfzZP3S8OJT3g9EEiJwAAAABJRU5ErkJggg==";
          link.appendChild(image);
          element.style.position = "relative";
          chart.__downloadAttached = true;
          chart.__enterEvent = addEvent(element, "mouseover", function(e2) {
            var related = e2.relatedTarget;
            if ((!related || related !== this && !childOf(this, related)) && chart.options.download) {
              link.href = chart.toImage(download);
              element.appendChild(link);
            }
          });
          chart.__leaveEvent = addEvent(element, "mouseout", function(e2) {
            var related = e2.relatedTarget;
            if (!related || related !== this && !childOf(this, related)) {
              if (link.parentNode) {
                link.parentNode.removeChild(link);
              }
            }
          });
        }
        function addEvent(elem, event, fn3) {
          if (elem.addEventListener) {
            elem.addEventListener(event, fn3, false);
            return fn3;
          } else {
            var fn22 = function() {
              return fn3.call(elem, window.event);
            };
            elem.attachEvent("on" + event, fn22);
            return fn22;
          }
        }
        function removeEvent(elem, event, fn3) {
          if (elem.removeEventListener) {
            elem.removeEventListener(event, fn3, false);
          } else {
            elem.detachEvent("on" + event, fn3);
          }
        }
        function childOf(p2, c2) {
          if (p2 === c2) {
            return false;
          }
          while (c2 && c2 !== p2) {
            c2 = c2.parentNode;
          }
          return c2 === p2;
        }
        var pendingRequests = [], runningRequests = 0, maxRequests = 4;
        function pushRequest(url, success, error3) {
          pendingRequests.push([url, success, error3]);
          runNext();
        }
        function runNext() {
          if (runningRequests < maxRequests) {
            var request = pendingRequests.shift();
            if (request) {
              runningRequests++;
              getJSON(request[0], request[1], request[2]);
              runNext();
            }
          }
        }
        function requestComplete() {
          runningRequests--;
          runNext();
        }
        function getJSON(url, success, error3) {
          ajaxCall(url, success, function(jqXHR, textStatus, errorThrown) {
            var message = typeof errorThrown === "string" ? errorThrown : errorThrown.message;
            error3(message);
          });
        }
        function ajaxCall(url, success, error3) {
          var $2 = window.jQuery || window.Zepto || window.$;
          if ($2 && $2.ajax) {
            $2.ajax({
              dataType: "json",
              url,
              success,
              error: error3,
              complete: requestComplete
            });
          } else {
            var xhr = new XMLHttpRequest();
            xhr.open("GET", url, true);
            xhr.setRequestHeader("Content-Type", "application/json");
            xhr.onload = function() {
              requestComplete();
              if (xhr.status === 200) {
                success(JSON.parse(xhr.responseText), xhr.statusText, xhr);
              } else {
                error3(xhr, "error", xhr.statusText);
              }
            };
            xhr.send();
          }
        }
        var config = {};
        var adapters2 = [];
        function setText(element, text) {
          if (document.body.innerText) {
            element.innerText = text;
          } else {
            element.textContent = text;
          }
        }
        function chartError(element, message, noPrefix) {
          if (!noPrefix) {
            message = "Error Loading Chart: " + message;
          }
          setText(element, message);
          element.style.color = "#ff0000";
        }
        function errorCatcher(chart) {
          try {
            chart.__render();
          } catch (err) {
            chartError(chart.element, err.message);
            throw err;
          }
        }
        function fetchDataSource(chart, dataSource, showLoading) {
          if (showLoading && chart.options.loading && (typeof dataSource === "string" || typeof dataSource === "function")) {
            setText(chart.element, chart.options.loading);
          }
          if (typeof dataSource === "string") {
            pushRequest(dataSource, function(data) {
              chart.rawData = data;
              errorCatcher(chart);
            }, function(message) {
              chartError(chart.element, message);
            });
          } else if (typeof dataSource === "function") {
            try {
              dataSource(function(data) {
                chart.rawData = data;
                errorCatcher(chart);
              }, function(message) {
                chartError(chart.element, message, true);
              });
            } catch (err) {
              chartError(chart.element, err, true);
            }
          } else {
            chart.rawData = dataSource;
            errorCatcher(chart);
          }
        }
        function getAdapterType(library) {
          if (library) {
            if (library.product === "Highcharts") {
              return defaultExport$1;
            } else if (library.charts) {
              return defaultExport;
            } else if (isFunction2(library)) {
              return defaultExport$2;
            }
          }
          throw new Error("Unknown adapter");
        }
        function addAdapter(library) {
          var adapterType = getAdapterType(library);
          var adapter = new adapterType(library);
          if (adapters2.indexOf(adapter) === -1) {
            adapters2.push(adapter);
          }
        }
        function loadAdapters() {
          if ("Chart" in window) {
            addAdapter(window.Chart);
          }
          if ("Highcharts" in window) {
            addAdapter(window.Highcharts);
          }
          if (window.google && window.google.charts) {
            addAdapter(window.google);
          }
        }
        function renderChart(chartType, chart) {
          if (dataEmpty(chart.data, chartType)) {
            var message = chart.options.empty || chart.options.messages && chart.options.messages.empty || "No data";
            setText(chart.element, message);
          } else {
            callAdapter(chartType, chart);
            if (chart.options.download && !chart.__downloadAttached && chart.adapter === "chartjs") {
              addDownloadButton(chart);
            }
          }
        }
        function callAdapter(chartType, chart) {
          var i2, adapter, fnName, adapterName;
          fnName = "render" + chartType;
          adapterName = chart.options.adapter;
          loadAdapters();
          for (i2 = 0; i2 < adapters2.length; i2++) {
            adapter = adapters2[i2];
            if ((!adapterName || adapterName === adapter.name) && isFunction2(adapter[fnName])) {
              chart.adapter = adapter.name;
              chart.__adapterObject = adapter;
              return adapter[fnName](chart);
            }
          }
          if (adapters2.length > 0) {
            throw new Error("No charting library found for " + chartType);
          } else {
            throw new Error("No charting libraries found - be sure to include one before your charts");
          }
        }
        var Chart2 = function Chart3(element, dataSource, options) {
          var elementId;
          if (typeof element === "string") {
            elementId = element;
            element = document.getElementById(element);
            if (!element) {
              throw new Error("No element with id " + elementId);
            }
          }
          this.element = element;
          this.options = merge2(Chartkick2.options, options || {});
          this.dataSource = dataSource;
          Chartkick2.charts[element.id] = this;
          fetchDataSource(this, dataSource, true);
          if (this.options.refresh) {
            this.startRefresh();
          }
        };
        Chart2.prototype.getElement = function getElement2() {
          return this.element;
        };
        Chart2.prototype.getDataSource = function getDataSource() {
          return this.dataSource;
        };
        Chart2.prototype.getData = function getData() {
          return this.data;
        };
        Chart2.prototype.getOptions = function getOptions() {
          return this.options;
        };
        Chart2.prototype.getChartObject = function getChartObject() {
          return this.chart;
        };
        Chart2.prototype.getAdapter = function getAdapter() {
          return this.adapter;
        };
        Chart2.prototype.updateData = function updateData(dataSource, options) {
          this.dataSource = dataSource;
          if (options) {
            this.__updateOptions(options);
          }
          fetchDataSource(this, dataSource, true);
        };
        Chart2.prototype.setOptions = function setOptions(options) {
          this.__updateOptions(options);
          this.redraw();
        };
        Chart2.prototype.redraw = function redraw() {
          fetchDataSource(this, this.rawData);
        };
        Chart2.prototype.refreshData = function refreshData() {
          if (typeof this.dataSource === "string") {
            var sep = this.dataSource.indexOf("?") === -1 ? "?" : "&";
            var url = this.dataSource + sep + "_=" + new Date().getTime();
            fetchDataSource(this, url);
          } else if (typeof this.dataSource === "function") {
            fetchDataSource(this, this.dataSource);
          }
        };
        Chart2.prototype.startRefresh = function startRefresh() {
          var this$1 = this;
          var refresh = this.options.refresh;
          if (refresh && typeof this.dataSource !== "string" && typeof this.dataSource !== "function") {
            throw new Error("Data source must be a URL or callback for refresh");
          }
          if (!this.intervalId) {
            if (refresh) {
              this.intervalId = setInterval(function() {
                this$1.refreshData();
              }, refresh * 1e3);
            } else {
              throw new Error("No refresh interval");
            }
          }
        };
        Chart2.prototype.stopRefresh = function stopRefresh() {
          if (this.intervalId) {
            clearInterval(this.intervalId);
            this.intervalId = null;
          }
        };
        Chart2.prototype.toImage = function toImage(download) {
          if (this.adapter === "chartjs") {
            if (download && download.background && download.background !== "transparent") {
              var canvas = this.chart.canvas;
              var ctx = this.chart.ctx;
              var tmpCanvas = document.createElement("canvas");
              var tmpCtx = tmpCanvas.getContext("2d");
              tmpCanvas.width = ctx.canvas.width;
              tmpCanvas.height = ctx.canvas.height;
              tmpCtx.fillStyle = download.background;
              tmpCtx.fillRect(0, 0, tmpCanvas.width, tmpCanvas.height);
              tmpCtx.drawImage(canvas, 0, 0);
              return tmpCanvas.toDataURL("image/png");
            } else {
              return this.chart.toBase64Image();
            }
          } else {
            throw new Error("Feature only available for Chart.js");
          }
        };
        Chart2.prototype.destroy = function destroy() {
          this.destroyed = true;
          this.stopRefresh();
          if (this.__adapterObject) {
            this.__adapterObject.destroy(this);
          }
          if (this.__enterEvent) {
            removeEvent(this.element, "mouseover", this.__enterEvent);
          }
          if (this.__leaveEvent) {
            removeEvent(this.element, "mouseout", this.__leaveEvent);
          }
        };
        Chart2.prototype.__updateOptions = function __updateOptions(options) {
          var updateRefresh = options.refresh && options.refresh !== this.options.refresh;
          this.options = merge2(Chartkick2.options, options);
          if (updateRefresh) {
            this.stopRefresh();
            this.startRefresh();
          }
        };
        Chart2.prototype.__render = function __render() {
          this.data = this.__processData();
          renderChart(this.__chartName(), this);
        };
        Chart2.prototype.__config = function __config() {
          return config;
        };
        var LineChart = /* @__PURE__ */ function(Chart3) {
          function LineChart2() {
            Chart3.apply(this, arguments);
          }
          if (Chart3)
            LineChart2.__proto__ = Chart3;
          LineChart2.prototype = Object.create(Chart3 && Chart3.prototype);
          LineChart2.prototype.constructor = LineChart2;
          LineChart2.prototype.__processData = function __processData() {
            return processSeries(this);
          };
          LineChart2.prototype.__chartName = function __chartName() {
            return "LineChart";
          };
          return LineChart2;
        }(Chart2);
        var PieChart = /* @__PURE__ */ function(Chart3) {
          function PieChart2() {
            Chart3.apply(this, arguments);
          }
          if (Chart3)
            PieChart2.__proto__ = Chart3;
          PieChart2.prototype = Object.create(Chart3 && Chart3.prototype);
          PieChart2.prototype.constructor = PieChart2;
          PieChart2.prototype.__processData = function __processData() {
            return processSimple(this);
          };
          PieChart2.prototype.__chartName = function __chartName() {
            return "PieChart";
          };
          return PieChart2;
        }(Chart2);
        var ColumnChart = /* @__PURE__ */ function(Chart3) {
          function ColumnChart2() {
            Chart3.apply(this, arguments);
          }
          if (Chart3)
            ColumnChart2.__proto__ = Chart3;
          ColumnChart2.prototype = Object.create(Chart3 && Chart3.prototype);
          ColumnChart2.prototype.constructor = ColumnChart2;
          ColumnChart2.prototype.__processData = function __processData() {
            return processSeries(this, null, true);
          };
          ColumnChart2.prototype.__chartName = function __chartName() {
            return "ColumnChart";
          };
          return ColumnChart2;
        }(Chart2);
        var BarChart = /* @__PURE__ */ function(Chart3) {
          function BarChart2() {
            Chart3.apply(this, arguments);
          }
          if (Chart3)
            BarChart2.__proto__ = Chart3;
          BarChart2.prototype = Object.create(Chart3 && Chart3.prototype);
          BarChart2.prototype.constructor = BarChart2;
          BarChart2.prototype.__processData = function __processData() {
            return processSeries(this, null, true);
          };
          BarChart2.prototype.__chartName = function __chartName() {
            return "BarChart";
          };
          return BarChart2;
        }(Chart2);
        var AreaChart = /* @__PURE__ */ function(Chart3) {
          function AreaChart2() {
            Chart3.apply(this, arguments);
          }
          if (Chart3)
            AreaChart2.__proto__ = Chart3;
          AreaChart2.prototype = Object.create(Chart3 && Chart3.prototype);
          AreaChart2.prototype.constructor = AreaChart2;
          AreaChart2.prototype.__processData = function __processData() {
            return processSeries(this);
          };
          AreaChart2.prototype.__chartName = function __chartName() {
            return "AreaChart";
          };
          return AreaChart2;
        }(Chart2);
        var GeoChart = /* @__PURE__ */ function(Chart3) {
          function GeoChart2() {
            Chart3.apply(this, arguments);
          }
          if (Chart3)
            GeoChart2.__proto__ = Chart3;
          GeoChart2.prototype = Object.create(Chart3 && Chart3.prototype);
          GeoChart2.prototype.constructor = GeoChart2;
          GeoChart2.prototype.__processData = function __processData() {
            return processSimple(this);
          };
          GeoChart2.prototype.__chartName = function __chartName() {
            return "GeoChart";
          };
          return GeoChart2;
        }(Chart2);
        var ScatterChart = /* @__PURE__ */ function(Chart3) {
          function ScatterChart2() {
            Chart3.apply(this, arguments);
          }
          if (Chart3)
            ScatterChart2.__proto__ = Chart3;
          ScatterChart2.prototype = Object.create(Chart3 && Chart3.prototype);
          ScatterChart2.prototype.constructor = ScatterChart2;
          ScatterChart2.prototype.__processData = function __processData() {
            return processSeries(this, "number");
          };
          ScatterChart2.prototype.__chartName = function __chartName() {
            return "ScatterChart";
          };
          return ScatterChart2;
        }(Chart2);
        var BubbleChart = /* @__PURE__ */ function(Chart3) {
          function BubbleChart2() {
            Chart3.apply(this, arguments);
          }
          if (Chart3)
            BubbleChart2.__proto__ = Chart3;
          BubbleChart2.prototype = Object.create(Chart3 && Chart3.prototype);
          BubbleChart2.prototype.constructor = BubbleChart2;
          BubbleChart2.prototype.__processData = function __processData() {
            return processSeries(this, "bubble");
          };
          BubbleChart2.prototype.__chartName = function __chartName() {
            return "BubbleChart";
          };
          return BubbleChart2;
        }(Chart2);
        var Timeline = /* @__PURE__ */ function(Chart3) {
          function Timeline2() {
            Chart3.apply(this, arguments);
          }
          if (Chart3)
            Timeline2.__proto__ = Chart3;
          Timeline2.prototype = Object.create(Chart3 && Chart3.prototype);
          Timeline2.prototype.constructor = Timeline2;
          Timeline2.prototype.__processData = function __processData() {
            var i2, data = this.rawData;
            for (i2 = 0; i2 < data.length; i2++) {
              data[i2][1] = toDate2(data[i2][1]);
              data[i2][2] = toDate2(data[i2][2]);
            }
            return data;
          };
          Timeline2.prototype.__chartName = function __chartName() {
            return "Timeline";
          };
          return Timeline2;
        }(Chart2);
        var Chartkick2 = {
          LineChart,
          PieChart,
          ColumnChart,
          BarChart,
          AreaChart,
          GeoChart,
          ScatterChart,
          BubbleChart,
          Timeline,
          charts: {},
          configure: function(options) {
            for (var key in options) {
              if (options.hasOwnProperty(key)) {
                config[key] = options[key];
              }
            }
          },
          setDefaultOptions: function(opts) {
            Chartkick2.options = opts;
          },
          eachChart: function(callback2) {
            for (var chartId in Chartkick2.charts) {
              if (Chartkick2.charts.hasOwnProperty(chartId)) {
                callback2(Chartkick2.charts[chartId]);
              }
            }
          },
          destroyAll: function() {
            for (var chartId in Chartkick2.charts) {
              if (Chartkick2.charts.hasOwnProperty(chartId)) {
                Chartkick2.charts[chartId].destroy();
                delete Chartkick2.charts[chartId];
              }
            }
          },
          config,
          options: {},
          adapters: adapters2,
          addAdapter,
          use: function(adapter) {
            addAdapter(adapter);
            return Chartkick2;
          }
        };
        if (typeof window !== "undefined" && !window.Chartkick) {
          window.Chartkick = Chartkick2;
          document.addEventListener("turbolinks:before-render", function() {
            Chartkick2.destroyAll();
          });
          setTimeout(function() {
            window.dispatchEvent(new Event("chartkick:load"));
          }, 0);
        }
        Chartkick2.default = Chartkick2;
        return Chartkick2;
      });
    }
  });

  // ../../node_modules/@rails/activestorage/app/assets/javascripts/activestorage.js
  var require_activestorage = __commonJS({
    "../../node_modules/@rails/activestorage/app/assets/javascripts/activestorage.js"(exports, module) {
      (function(global2, factory) {
        typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && define.amd ? define(["exports"], factory) : factory(global2.ActiveStorage = {});
      })(exports, function(exports2) {
        "use strict";
        function createCommonjsModule(fn3, module2) {
          return module2 = {
            exports: {}
          }, fn3(module2, module2.exports), module2.exports;
        }
        var sparkMd52 = createCommonjsModule(function(module2, exports3) {
          (function(factory) {
            {
              module2.exports = factory();
            }
          })(function(undefined2) {
            var hex_chr = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"];
            function md5cycle(x2, k2) {
              var a2 = x2[0], b2 = x2[1], c2 = x2[2], d2 = x2[3];
              a2 += (b2 & c2 | ~b2 & d2) + k2[0] - 680876936 | 0;
              a2 = (a2 << 7 | a2 >>> 25) + b2 | 0;
              d2 += (a2 & b2 | ~a2 & c2) + k2[1] - 389564586 | 0;
              d2 = (d2 << 12 | d2 >>> 20) + a2 | 0;
              c2 += (d2 & a2 | ~d2 & b2) + k2[2] + 606105819 | 0;
              c2 = (c2 << 17 | c2 >>> 15) + d2 | 0;
              b2 += (c2 & d2 | ~c2 & a2) + k2[3] - 1044525330 | 0;
              b2 = (b2 << 22 | b2 >>> 10) + c2 | 0;
              a2 += (b2 & c2 | ~b2 & d2) + k2[4] - 176418897 | 0;
              a2 = (a2 << 7 | a2 >>> 25) + b2 | 0;
              d2 += (a2 & b2 | ~a2 & c2) + k2[5] + 1200080426 | 0;
              d2 = (d2 << 12 | d2 >>> 20) + a2 | 0;
              c2 += (d2 & a2 | ~d2 & b2) + k2[6] - 1473231341 | 0;
              c2 = (c2 << 17 | c2 >>> 15) + d2 | 0;
              b2 += (c2 & d2 | ~c2 & a2) + k2[7] - 45705983 | 0;
              b2 = (b2 << 22 | b2 >>> 10) + c2 | 0;
              a2 += (b2 & c2 | ~b2 & d2) + k2[8] + 1770035416 | 0;
              a2 = (a2 << 7 | a2 >>> 25) + b2 | 0;
              d2 += (a2 & b2 | ~a2 & c2) + k2[9] - 1958414417 | 0;
              d2 = (d2 << 12 | d2 >>> 20) + a2 | 0;
              c2 += (d2 & a2 | ~d2 & b2) + k2[10] - 42063 | 0;
              c2 = (c2 << 17 | c2 >>> 15) + d2 | 0;
              b2 += (c2 & d2 | ~c2 & a2) + k2[11] - 1990404162 | 0;
              b2 = (b2 << 22 | b2 >>> 10) + c2 | 0;
              a2 += (b2 & c2 | ~b2 & d2) + k2[12] + 1804603682 | 0;
              a2 = (a2 << 7 | a2 >>> 25) + b2 | 0;
              d2 += (a2 & b2 | ~a2 & c2) + k2[13] - 40341101 | 0;
              d2 = (d2 << 12 | d2 >>> 20) + a2 | 0;
              c2 += (d2 & a2 | ~d2 & b2) + k2[14] - 1502002290 | 0;
              c2 = (c2 << 17 | c2 >>> 15) + d2 | 0;
              b2 += (c2 & d2 | ~c2 & a2) + k2[15] + 1236535329 | 0;
              b2 = (b2 << 22 | b2 >>> 10) + c2 | 0;
              a2 += (b2 & d2 | c2 & ~d2) + k2[1] - 165796510 | 0;
              a2 = (a2 << 5 | a2 >>> 27) + b2 | 0;
              d2 += (a2 & c2 | b2 & ~c2) + k2[6] - 1069501632 | 0;
              d2 = (d2 << 9 | d2 >>> 23) + a2 | 0;
              c2 += (d2 & b2 | a2 & ~b2) + k2[11] + 643717713 | 0;
              c2 = (c2 << 14 | c2 >>> 18) + d2 | 0;
              b2 += (c2 & a2 | d2 & ~a2) + k2[0] - 373897302 | 0;
              b2 = (b2 << 20 | b2 >>> 12) + c2 | 0;
              a2 += (b2 & d2 | c2 & ~d2) + k2[5] - 701558691 | 0;
              a2 = (a2 << 5 | a2 >>> 27) + b2 | 0;
              d2 += (a2 & c2 | b2 & ~c2) + k2[10] + 38016083 | 0;
              d2 = (d2 << 9 | d2 >>> 23) + a2 | 0;
              c2 += (d2 & b2 | a2 & ~b2) + k2[15] - 660478335 | 0;
              c2 = (c2 << 14 | c2 >>> 18) + d2 | 0;
              b2 += (c2 & a2 | d2 & ~a2) + k2[4] - 405537848 | 0;
              b2 = (b2 << 20 | b2 >>> 12) + c2 | 0;
              a2 += (b2 & d2 | c2 & ~d2) + k2[9] + 568446438 | 0;
              a2 = (a2 << 5 | a2 >>> 27) + b2 | 0;
              d2 += (a2 & c2 | b2 & ~c2) + k2[14] - 1019803690 | 0;
              d2 = (d2 << 9 | d2 >>> 23) + a2 | 0;
              c2 += (d2 & b2 | a2 & ~b2) + k2[3] - 187363961 | 0;
              c2 = (c2 << 14 | c2 >>> 18) + d2 | 0;
              b2 += (c2 & a2 | d2 & ~a2) + k2[8] + 1163531501 | 0;
              b2 = (b2 << 20 | b2 >>> 12) + c2 | 0;
              a2 += (b2 & d2 | c2 & ~d2) + k2[13] - 1444681467 | 0;
              a2 = (a2 << 5 | a2 >>> 27) + b2 | 0;
              d2 += (a2 & c2 | b2 & ~c2) + k2[2] - 51403784 | 0;
              d2 = (d2 << 9 | d2 >>> 23) + a2 | 0;
              c2 += (d2 & b2 | a2 & ~b2) + k2[7] + 1735328473 | 0;
              c2 = (c2 << 14 | c2 >>> 18) + d2 | 0;
              b2 += (c2 & a2 | d2 & ~a2) + k2[12] - 1926607734 | 0;
              b2 = (b2 << 20 | b2 >>> 12) + c2 | 0;
              a2 += (b2 ^ c2 ^ d2) + k2[5] - 378558 | 0;
              a2 = (a2 << 4 | a2 >>> 28) + b2 | 0;
              d2 += (a2 ^ b2 ^ c2) + k2[8] - 2022574463 | 0;
              d2 = (d2 << 11 | d2 >>> 21) + a2 | 0;
              c2 += (d2 ^ a2 ^ b2) + k2[11] + 1839030562 | 0;
              c2 = (c2 << 16 | c2 >>> 16) + d2 | 0;
              b2 += (c2 ^ d2 ^ a2) + k2[14] - 35309556 | 0;
              b2 = (b2 << 23 | b2 >>> 9) + c2 | 0;
              a2 += (b2 ^ c2 ^ d2) + k2[1] - 1530992060 | 0;
              a2 = (a2 << 4 | a2 >>> 28) + b2 | 0;
              d2 += (a2 ^ b2 ^ c2) + k2[4] + 1272893353 | 0;
              d2 = (d2 << 11 | d2 >>> 21) + a2 | 0;
              c2 += (d2 ^ a2 ^ b2) + k2[7] - 155497632 | 0;
              c2 = (c2 << 16 | c2 >>> 16) + d2 | 0;
              b2 += (c2 ^ d2 ^ a2) + k2[10] - 1094730640 | 0;
              b2 = (b2 << 23 | b2 >>> 9) + c2 | 0;
              a2 += (b2 ^ c2 ^ d2) + k2[13] + 681279174 | 0;
              a2 = (a2 << 4 | a2 >>> 28) + b2 | 0;
              d2 += (a2 ^ b2 ^ c2) + k2[0] - 358537222 | 0;
              d2 = (d2 << 11 | d2 >>> 21) + a2 | 0;
              c2 += (d2 ^ a2 ^ b2) + k2[3] - 722521979 | 0;
              c2 = (c2 << 16 | c2 >>> 16) + d2 | 0;
              b2 += (c2 ^ d2 ^ a2) + k2[6] + 76029189 | 0;
              b2 = (b2 << 23 | b2 >>> 9) + c2 | 0;
              a2 += (b2 ^ c2 ^ d2) + k2[9] - 640364487 | 0;
              a2 = (a2 << 4 | a2 >>> 28) + b2 | 0;
              d2 += (a2 ^ b2 ^ c2) + k2[12] - 421815835 | 0;
              d2 = (d2 << 11 | d2 >>> 21) + a2 | 0;
              c2 += (d2 ^ a2 ^ b2) + k2[15] + 530742520 | 0;
              c2 = (c2 << 16 | c2 >>> 16) + d2 | 0;
              b2 += (c2 ^ d2 ^ a2) + k2[2] - 995338651 | 0;
              b2 = (b2 << 23 | b2 >>> 9) + c2 | 0;
              a2 += (c2 ^ (b2 | ~d2)) + k2[0] - 198630844 | 0;
              a2 = (a2 << 6 | a2 >>> 26) + b2 | 0;
              d2 += (b2 ^ (a2 | ~c2)) + k2[7] + 1126891415 | 0;
              d2 = (d2 << 10 | d2 >>> 22) + a2 | 0;
              c2 += (a2 ^ (d2 | ~b2)) + k2[14] - 1416354905 | 0;
              c2 = (c2 << 15 | c2 >>> 17) + d2 | 0;
              b2 += (d2 ^ (c2 | ~a2)) + k2[5] - 57434055 | 0;
              b2 = (b2 << 21 | b2 >>> 11) + c2 | 0;
              a2 += (c2 ^ (b2 | ~d2)) + k2[12] + 1700485571 | 0;
              a2 = (a2 << 6 | a2 >>> 26) + b2 | 0;
              d2 += (b2 ^ (a2 | ~c2)) + k2[3] - 1894986606 | 0;
              d2 = (d2 << 10 | d2 >>> 22) + a2 | 0;
              c2 += (a2 ^ (d2 | ~b2)) + k2[10] - 1051523 | 0;
              c2 = (c2 << 15 | c2 >>> 17) + d2 | 0;
              b2 += (d2 ^ (c2 | ~a2)) + k2[1] - 2054922799 | 0;
              b2 = (b2 << 21 | b2 >>> 11) + c2 | 0;
              a2 += (c2 ^ (b2 | ~d2)) + k2[8] + 1873313359 | 0;
              a2 = (a2 << 6 | a2 >>> 26) + b2 | 0;
              d2 += (b2 ^ (a2 | ~c2)) + k2[15] - 30611744 | 0;
              d2 = (d2 << 10 | d2 >>> 22) + a2 | 0;
              c2 += (a2 ^ (d2 | ~b2)) + k2[6] - 1560198380 | 0;
              c2 = (c2 << 15 | c2 >>> 17) + d2 | 0;
              b2 += (d2 ^ (c2 | ~a2)) + k2[13] + 1309151649 | 0;
              b2 = (b2 << 21 | b2 >>> 11) + c2 | 0;
              a2 += (c2 ^ (b2 | ~d2)) + k2[4] - 145523070 | 0;
              a2 = (a2 << 6 | a2 >>> 26) + b2 | 0;
              d2 += (b2 ^ (a2 | ~c2)) + k2[11] - 1120210379 | 0;
              d2 = (d2 << 10 | d2 >>> 22) + a2 | 0;
              c2 += (a2 ^ (d2 | ~b2)) + k2[2] + 718787259 | 0;
              c2 = (c2 << 15 | c2 >>> 17) + d2 | 0;
              b2 += (d2 ^ (c2 | ~a2)) + k2[9] - 343485551 | 0;
              b2 = (b2 << 21 | b2 >>> 11) + c2 | 0;
              x2[0] = a2 + x2[0] | 0;
              x2[1] = b2 + x2[1] | 0;
              x2[2] = c2 + x2[2] | 0;
              x2[3] = d2 + x2[3] | 0;
            }
            function md5blk(s2) {
              var md5blks = [], i2;
              for (i2 = 0; i2 < 64; i2 += 4) {
                md5blks[i2 >> 2] = s2.charCodeAt(i2) + (s2.charCodeAt(i2 + 1) << 8) + (s2.charCodeAt(i2 + 2) << 16) + (s2.charCodeAt(i2 + 3) << 24);
              }
              return md5blks;
            }
            function md5blk_array(a2) {
              var md5blks = [], i2;
              for (i2 = 0; i2 < 64; i2 += 4) {
                md5blks[i2 >> 2] = a2[i2] + (a2[i2 + 1] << 8) + (a2[i2 + 2] << 16) + (a2[i2 + 3] << 24);
              }
              return md5blks;
            }
            function md51(s2) {
              var n2 = s2.length, state = [1732584193, -271733879, -1732584194, 271733878], i2, length, tail, tmp, lo, hi2;
              for (i2 = 64; i2 <= n2; i2 += 64) {
                md5cycle(state, md5blk(s2.substring(i2 - 64, i2)));
              }
              s2 = s2.substring(i2 - 64);
              length = s2.length;
              tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
              for (i2 = 0; i2 < length; i2 += 1) {
                tail[i2 >> 2] |= s2.charCodeAt(i2) << (i2 % 4 << 3);
              }
              tail[i2 >> 2] |= 128 << (i2 % 4 << 3);
              if (i2 > 55) {
                md5cycle(state, tail);
                for (i2 = 0; i2 < 16; i2 += 1) {
                  tail[i2] = 0;
                }
              }
              tmp = n2 * 8;
              tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
              lo = parseInt(tmp[2], 16);
              hi2 = parseInt(tmp[1], 16) || 0;
              tail[14] = lo;
              tail[15] = hi2;
              md5cycle(state, tail);
              return state;
            }
            function md51_array(a2) {
              var n2 = a2.length, state = [1732584193, -271733879, -1732584194, 271733878], i2, length, tail, tmp, lo, hi2;
              for (i2 = 64; i2 <= n2; i2 += 64) {
                md5cycle(state, md5blk_array(a2.subarray(i2 - 64, i2)));
              }
              a2 = i2 - 64 < n2 ? a2.subarray(i2 - 64) : new Uint8Array(0);
              length = a2.length;
              tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
              for (i2 = 0; i2 < length; i2 += 1) {
                tail[i2 >> 2] |= a2[i2] << (i2 % 4 << 3);
              }
              tail[i2 >> 2] |= 128 << (i2 % 4 << 3);
              if (i2 > 55) {
                md5cycle(state, tail);
                for (i2 = 0; i2 < 16; i2 += 1) {
                  tail[i2] = 0;
                }
              }
              tmp = n2 * 8;
              tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
              lo = parseInt(tmp[2], 16);
              hi2 = parseInt(tmp[1], 16) || 0;
              tail[14] = lo;
              tail[15] = hi2;
              md5cycle(state, tail);
              return state;
            }
            function rhex(n2) {
              var s2 = "", j2;
              for (j2 = 0; j2 < 4; j2 += 1) {
                s2 += hex_chr[n2 >> j2 * 8 + 4 & 15] + hex_chr[n2 >> j2 * 8 & 15];
              }
              return s2;
            }
            function hex2(x2) {
              var i2;
              for (i2 = 0; i2 < x2.length; i2 += 1) {
                x2[i2] = rhex(x2[i2]);
              }
              return x2.join("");
            }
            if (hex2(md51("hello")) !== "5d41402abc4b2a76b9719d911017c592")
              ;
            if (typeof ArrayBuffer !== "undefined" && !ArrayBuffer.prototype.slice) {
              (function() {
                function clamp(val, length) {
                  val = val | 0 || 0;
                  if (val < 0) {
                    return Math.max(val + length, 0);
                  }
                  return Math.min(val, length);
                }
                ArrayBuffer.prototype.slice = function(from, to) {
                  var length = this.byteLength, begin = clamp(from, length), end2 = length, num, target, targetArray, sourceArray;
                  if (to !== undefined2) {
                    end2 = clamp(to, length);
                  }
                  if (begin > end2) {
                    return new ArrayBuffer(0);
                  }
                  num = end2 - begin;
                  target = new ArrayBuffer(num);
                  targetArray = new Uint8Array(target);
                  sourceArray = new Uint8Array(this, begin, num);
                  targetArray.set(sourceArray);
                  return target;
                };
              })();
            }
            function toUtf8(str) {
              if (/[\u0080-\uFFFF]/.test(str)) {
                str = unescape(encodeURIComponent(str));
              }
              return str;
            }
            function utf8Str2ArrayBuffer(str, returnUInt8Array) {
              var length = str.length, buff = new ArrayBuffer(length), arr = new Uint8Array(buff), i2;
              for (i2 = 0; i2 < length; i2 += 1) {
                arr[i2] = str.charCodeAt(i2);
              }
              return returnUInt8Array ? arr : buff;
            }
            function arrayBuffer2Utf8Str(buff) {
              return String.fromCharCode.apply(null, new Uint8Array(buff));
            }
            function concatenateArrayBuffers(first, second, returnUInt8Array) {
              var result = new Uint8Array(first.byteLength + second.byteLength);
              result.set(new Uint8Array(first));
              result.set(new Uint8Array(second), first.byteLength);
              return returnUInt8Array ? result : result.buffer;
            }
            function hexToBinaryString(hex3) {
              var bytes = [], length = hex3.length, x2;
              for (x2 = 0; x2 < length - 1; x2 += 2) {
                bytes.push(parseInt(hex3.substr(x2, 2), 16));
              }
              return String.fromCharCode.apply(String, bytes);
            }
            function SparkMD52() {
              this.reset();
            }
            SparkMD52.prototype.append = function(str) {
              this.appendBinary(toUtf8(str));
              return this;
            };
            SparkMD52.prototype.appendBinary = function(contents) {
              this._buff += contents;
              this._length += contents.length;
              var length = this._buff.length, i2;
              for (i2 = 64; i2 <= length; i2 += 64) {
                md5cycle(this._hash, md5blk(this._buff.substring(i2 - 64, i2)));
              }
              this._buff = this._buff.substring(i2 - 64);
              return this;
            };
            SparkMD52.prototype.end = function(raw) {
              var buff = this._buff, length = buff.length, i2, tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ret;
              for (i2 = 0; i2 < length; i2 += 1) {
                tail[i2 >> 2] |= buff.charCodeAt(i2) << (i2 % 4 << 3);
              }
              this._finish(tail, length);
              ret = hex2(this._hash);
              if (raw) {
                ret = hexToBinaryString(ret);
              }
              this.reset();
              return ret;
            };
            SparkMD52.prototype.reset = function() {
              this._buff = "";
              this._length = 0;
              this._hash = [1732584193, -271733879, -1732584194, 271733878];
              return this;
            };
            SparkMD52.prototype.getState = function() {
              return {
                buff: this._buff,
                length: this._length,
                hash: this._hash
              };
            };
            SparkMD52.prototype.setState = function(state) {
              this._buff = state.buff;
              this._length = state.length;
              this._hash = state.hash;
              return this;
            };
            SparkMD52.prototype.destroy = function() {
              delete this._hash;
              delete this._buff;
              delete this._length;
            };
            SparkMD52.prototype._finish = function(tail, length) {
              var i2 = length, tmp, lo, hi2;
              tail[i2 >> 2] |= 128 << (i2 % 4 << 3);
              if (i2 > 55) {
                md5cycle(this._hash, tail);
                for (i2 = 0; i2 < 16; i2 += 1) {
                  tail[i2] = 0;
                }
              }
              tmp = this._length * 8;
              tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
              lo = parseInt(tmp[2], 16);
              hi2 = parseInt(tmp[1], 16) || 0;
              tail[14] = lo;
              tail[15] = hi2;
              md5cycle(this._hash, tail);
            };
            SparkMD52.hash = function(str, raw) {
              return SparkMD52.hashBinary(toUtf8(str), raw);
            };
            SparkMD52.hashBinary = function(content, raw) {
              var hash3 = md51(content), ret = hex2(hash3);
              return raw ? hexToBinaryString(ret) : ret;
            };
            SparkMD52.ArrayBuffer = function() {
              this.reset();
            };
            SparkMD52.ArrayBuffer.prototype.append = function(arr) {
              var buff = concatenateArrayBuffers(this._buff.buffer, arr, true), length = buff.length, i2;
              this._length += arr.byteLength;
              for (i2 = 64; i2 <= length; i2 += 64) {
                md5cycle(this._hash, md5blk_array(buff.subarray(i2 - 64, i2)));
              }
              this._buff = i2 - 64 < length ? new Uint8Array(buff.buffer.slice(i2 - 64)) : new Uint8Array(0);
              return this;
            };
            SparkMD52.ArrayBuffer.prototype.end = function(raw) {
              var buff = this._buff, length = buff.length, tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], i2, ret;
              for (i2 = 0; i2 < length; i2 += 1) {
                tail[i2 >> 2] |= buff[i2] << (i2 % 4 << 3);
              }
              this._finish(tail, length);
              ret = hex2(this._hash);
              if (raw) {
                ret = hexToBinaryString(ret);
              }
              this.reset();
              return ret;
            };
            SparkMD52.ArrayBuffer.prototype.reset = function() {
              this._buff = new Uint8Array(0);
              this._length = 0;
              this._hash = [1732584193, -271733879, -1732584194, 271733878];
              return this;
            };
            SparkMD52.ArrayBuffer.prototype.getState = function() {
              var state = SparkMD52.prototype.getState.call(this);
              state.buff = arrayBuffer2Utf8Str(state.buff);
              return state;
            };
            SparkMD52.ArrayBuffer.prototype.setState = function(state) {
              state.buff = utf8Str2ArrayBuffer(state.buff, true);
              return SparkMD52.prototype.setState.call(this, state);
            };
            SparkMD52.ArrayBuffer.prototype.destroy = SparkMD52.prototype.destroy;
            SparkMD52.ArrayBuffer.prototype._finish = SparkMD52.prototype._finish;
            SparkMD52.ArrayBuffer.hash = function(arr, raw) {
              var hash3 = md51_array(new Uint8Array(arr)), ret = hex2(hash3);
              return raw ? hexToBinaryString(ret) : ret;
            };
            return SparkMD52;
          });
        });
        var classCallCheck = function(instance, Constructor) {
          if (!(instance instanceof Constructor)) {
            throw new TypeError("Cannot call a class as a function");
          }
        };
        var createClass = function() {
          function defineProperties(target, props) {
            for (var i2 = 0; i2 < props.length; i2++) {
              var descriptor = props[i2];
              descriptor.enumerable = descriptor.enumerable || false;
              descriptor.configurable = true;
              if ("value" in descriptor)
                descriptor.writable = true;
              Object.defineProperty(target, descriptor.key, descriptor);
            }
          }
          return function(Constructor, protoProps, staticProps) {
            if (protoProps)
              defineProperties(Constructor.prototype, protoProps);
            if (staticProps)
              defineProperties(Constructor, staticProps);
            return Constructor;
          };
        }();
        var fileSlice2 = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice;
        var FileChecksum2 = function() {
          createClass(FileChecksum3, null, [{
            key: "create",
            value: function create(file, callback2) {
              var instance = new FileChecksum3(file);
              instance.create(callback2);
            }
          }]);
          function FileChecksum3(file) {
            classCallCheck(this, FileChecksum3);
            this.file = file;
            this.chunkSize = 2097152;
            this.chunkCount = Math.ceil(this.file.size / this.chunkSize);
            this.chunkIndex = 0;
          }
          createClass(FileChecksum3, [{
            key: "create",
            value: function create(callback2) {
              var _this = this;
              this.callback = callback2;
              this.md5Buffer = new sparkMd52.ArrayBuffer();
              this.fileReader = new FileReader();
              this.fileReader.addEventListener("load", function(event) {
                return _this.fileReaderDidLoad(event);
              });
              this.fileReader.addEventListener("error", function(event) {
                return _this.fileReaderDidError(event);
              });
              this.readNextChunk();
            }
          }, {
            key: "fileReaderDidLoad",
            value: function fileReaderDidLoad(event) {
              this.md5Buffer.append(event.target.result);
              if (!this.readNextChunk()) {
                var binaryDigest = this.md5Buffer.end(true);
                var base64digest = btoa(binaryDigest);
                this.callback(null, base64digest);
              }
            }
          }, {
            key: "fileReaderDidError",
            value: function fileReaderDidError(event) {
              this.callback("Error reading " + this.file.name);
            }
          }, {
            key: "readNextChunk",
            value: function readNextChunk() {
              if (this.chunkIndex < this.chunkCount || this.chunkIndex == 0 && this.chunkCount == 0) {
                var start5 = this.chunkIndex * this.chunkSize;
                var end2 = Math.min(start5 + this.chunkSize, this.file.size);
                var bytes = fileSlice2.call(this.file, start5, end2);
                this.fileReader.readAsArrayBuffer(bytes);
                this.chunkIndex++;
                return true;
              } else {
                return false;
              }
            }
          }]);
          return FileChecksum3;
        }();
        function getMetaValue2(name) {
          var element = findElement2(document.head, 'meta[name="' + name + '"]');
          if (element) {
            return element.getAttribute("content");
          }
        }
        function findElements2(root, selector) {
          if (typeof root == "string") {
            selector = root;
            root = document;
          }
          var elements2 = root.querySelectorAll(selector);
          return toArray$1(elements2);
        }
        function findElement2(root, selector) {
          if (typeof root == "string") {
            selector = root;
            root = document;
          }
          return root.querySelector(selector);
        }
        function dispatchEvent3(element, type) {
          var eventInit = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
          var disabled = element.disabled;
          var bubbles = eventInit.bubbles, cancelable = eventInit.cancelable, detail = eventInit.detail;
          var event = document.createEvent("Event");
          event.initEvent(type, bubbles || true, cancelable || true);
          event.detail = detail || {};
          try {
            element.disabled = false;
            element.dispatchEvent(event);
          } finally {
            element.disabled = disabled;
          }
          return event;
        }
        function toArray$1(value) {
          if (Array.isArray(value)) {
            return value;
          } else if (Array.from) {
            return Array.from(value);
          } else {
            return [].slice.call(value);
          }
        }
        var BlobRecord2 = function() {
          function BlobRecord3(file, checksum, url) {
            var _this = this;
            classCallCheck(this, BlobRecord3);
            this.file = file;
            this.attributes = {
              filename: file.name,
              content_type: file.type || "application/octet-stream",
              byte_size: file.size,
              checksum
            };
            this.xhr = new XMLHttpRequest();
            this.xhr.open("POST", url, true);
            this.xhr.responseType = "json";
            this.xhr.setRequestHeader("Content-Type", "application/json");
            this.xhr.setRequestHeader("Accept", "application/json");
            this.xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
            var csrfToken = getMetaValue2("csrf-token");
            if (csrfToken != void 0) {
              this.xhr.setRequestHeader("X-CSRF-Token", csrfToken);
            }
            this.xhr.addEventListener("load", function(event) {
              return _this.requestDidLoad(event);
            });
            this.xhr.addEventListener("error", function(event) {
              return _this.requestDidError(event);
            });
          }
          createClass(BlobRecord3, [{
            key: "create",
            value: function create(callback2) {
              this.callback = callback2;
              this.xhr.send(JSON.stringify({
                blob: this.attributes
              }));
            }
          }, {
            key: "requestDidLoad",
            value: function requestDidLoad(event) {
              if (this.status >= 200 && this.status < 300) {
                var response = this.response;
                var direct_upload = response.direct_upload;
                delete response.direct_upload;
                this.attributes = response;
                this.directUploadData = direct_upload;
                this.callback(null, this.toJSON());
              } else {
                this.requestDidError(event);
              }
            }
          }, {
            key: "requestDidError",
            value: function requestDidError(event) {
              this.callback('Error creating Blob for "' + this.file.name + '". Status: ' + this.status);
            }
          }, {
            key: "toJSON",
            value: function toJSON() {
              var result = {};
              for (var key in this.attributes) {
                result[key] = this.attributes[key];
              }
              return result;
            }
          }, {
            key: "status",
            get: function get$$1() {
              return this.xhr.status;
            }
          }, {
            key: "response",
            get: function get$$1() {
              var _xhr = this.xhr, responseType = _xhr.responseType, response = _xhr.response;
              if (responseType == "json") {
                return response;
              } else {
                return JSON.parse(response);
              }
            }
          }]);
          return BlobRecord3;
        }();
        var BlobUpload2 = function() {
          function BlobUpload3(blob) {
            var _this = this;
            classCallCheck(this, BlobUpload3);
            this.blob = blob;
            this.file = blob.file;
            var _blob$directUploadDat = blob.directUploadData, url = _blob$directUploadDat.url, headers = _blob$directUploadDat.headers;
            this.xhr = new XMLHttpRequest();
            this.xhr.open("PUT", url, true);
            this.xhr.responseType = "text";
            for (var key in headers) {
              this.xhr.setRequestHeader(key, headers[key]);
            }
            this.xhr.addEventListener("load", function(event) {
              return _this.requestDidLoad(event);
            });
            this.xhr.addEventListener("error", function(event) {
              return _this.requestDidError(event);
            });
          }
          createClass(BlobUpload3, [{
            key: "create",
            value: function create(callback2) {
              this.callback = callback2;
              this.xhr.send(this.file.slice());
            }
          }, {
            key: "requestDidLoad",
            value: function requestDidLoad(event) {
              var _xhr = this.xhr, status = _xhr.status, response = _xhr.response;
              if (status >= 200 && status < 300) {
                this.callback(null, response);
              } else {
                this.requestDidError(event);
              }
            }
          }, {
            key: "requestDidError",
            value: function requestDidError(event) {
              this.callback('Error storing "' + this.file.name + '". Status: ' + this.xhr.status);
            }
          }]);
          return BlobUpload3;
        }();
        var id2 = 0;
        var DirectUpload2 = function() {
          function DirectUpload3(file, url, delegate) {
            classCallCheck(this, DirectUpload3);
            this.id = ++id2;
            this.file = file;
            this.url = url;
            this.delegate = delegate;
          }
          createClass(DirectUpload3, [{
            key: "create",
            value: function create(callback2) {
              var _this = this;
              FileChecksum2.create(this.file, function(error3, checksum) {
                if (error3) {
                  callback2(error3);
                  return;
                }
                var blob = new BlobRecord2(_this.file, checksum, _this.url);
                notify2(_this.delegate, "directUploadWillCreateBlobWithXHR", blob.xhr);
                blob.create(function(error4) {
                  if (error4) {
                    callback2(error4);
                  } else {
                    var upload = new BlobUpload2(blob);
                    notify2(_this.delegate, "directUploadWillStoreFileWithXHR", upload.xhr);
                    upload.create(function(error5) {
                      if (error5) {
                        callback2(error5);
                      } else {
                        callback2(null, blob.toJSON());
                      }
                    });
                  }
                });
              });
            }
          }]);
          return DirectUpload3;
        }();
        function notify2(object, methodName) {
          if (object && typeof object[methodName] == "function") {
            for (var _len = arguments.length, messages = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
              messages[_key - 2] = arguments[_key];
            }
            return object[methodName].apply(object, messages);
          }
        }
        var DirectUploadController2 = function() {
          function DirectUploadController3(input, file) {
            classCallCheck(this, DirectUploadController3);
            this.input = input;
            this.file = file;
            this.directUpload = new DirectUpload2(this.file, this.url, this);
            this.dispatch("initialize");
          }
          createClass(DirectUploadController3, [{
            key: "start",
            value: function start5(callback2) {
              var _this = this;
              var hiddenInput = document.createElement("input");
              hiddenInput.type = "hidden";
              hiddenInput.name = this.input.name;
              this.input.insertAdjacentElement("beforebegin", hiddenInput);
              this.dispatch("start");
              this.directUpload.create(function(error3, attributes) {
                if (error3) {
                  hiddenInput.parentNode.removeChild(hiddenInput);
                  _this.dispatchError(error3);
                } else {
                  hiddenInput.value = attributes.signed_id;
                }
                _this.dispatch("end");
                callback2(error3);
              });
            }
          }, {
            key: "uploadRequestDidProgress",
            value: function uploadRequestDidProgress(event) {
              var progress = event.loaded / event.total * 100;
              if (progress) {
                this.dispatch("progress", {
                  progress
                });
              }
            }
          }, {
            key: "dispatch",
            value: function dispatch2(name) {
              var detail = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
              detail.file = this.file;
              detail.id = this.directUpload.id;
              return dispatchEvent3(this.input, "direct-upload:" + name, {
                detail
              });
            }
          }, {
            key: "dispatchError",
            value: function dispatchError(error3) {
              var event = this.dispatch("error", {
                error: error3
              });
              if (!event.defaultPrevented) {
                alert(error3);
              }
            }
          }, {
            key: "directUploadWillCreateBlobWithXHR",
            value: function directUploadWillCreateBlobWithXHR(xhr) {
              this.dispatch("before-blob-request", {
                xhr
              });
            }
          }, {
            key: "directUploadWillStoreFileWithXHR",
            value: function directUploadWillStoreFileWithXHR(xhr) {
              var _this2 = this;
              this.dispatch("before-storage-request", {
                xhr
              });
              xhr.upload.addEventListener("progress", function(event) {
                return _this2.uploadRequestDidProgress(event);
              });
            }
          }, {
            key: "url",
            get: function get$$1() {
              return this.input.getAttribute("data-direct-upload-url");
            }
          }]);
          return DirectUploadController3;
        }();
        var inputSelector2 = "input[type=file][data-direct-upload-url]:not([disabled])";
        var DirectUploadsController2 = function() {
          function DirectUploadsController3(form) {
            classCallCheck(this, DirectUploadsController3);
            this.form = form;
            this.inputs = findElements2(form, inputSelector2).filter(function(input) {
              return input.files.length;
            });
          }
          createClass(DirectUploadsController3, [{
            key: "start",
            value: function start5(callback2) {
              var _this = this;
              var controllers2 = this.createDirectUploadControllers();
              var startNextController = function startNextController2() {
                var controller = controllers2.shift();
                if (controller) {
                  controller.start(function(error3) {
                    if (error3) {
                      callback2(error3);
                      _this.dispatch("end");
                    } else {
                      startNextController2();
                    }
                  });
                } else {
                  callback2();
                  _this.dispatch("end");
                }
              };
              this.dispatch("start");
              startNextController();
            }
          }, {
            key: "createDirectUploadControllers",
            value: function createDirectUploadControllers() {
              var controllers2 = [];
              this.inputs.forEach(function(input) {
                toArray$1(input.files).forEach(function(file) {
                  var controller = new DirectUploadController2(input, file);
                  controllers2.push(controller);
                });
              });
              return controllers2;
            }
          }, {
            key: "dispatch",
            value: function dispatch2(name) {
              var detail = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
              return dispatchEvent3(this.form, "direct-uploads:" + name, {
                detail
              });
            }
          }]);
          return DirectUploadsController3;
        }();
        var processingAttribute2 = "data-direct-uploads-processing";
        var submitButtonsByForm2 = /* @__PURE__ */ new WeakMap();
        var started2 = false;
        function start4() {
          if (!started2) {
            started2 = true;
            document.addEventListener("click", didClick2, true);
            document.addEventListener("submit", didSubmitForm2);
            document.addEventListener("ajax:before", didSubmitRemoteElement2);
          }
        }
        function didClick2(event) {
          var target = event.target;
          if ((target.tagName == "INPUT" || target.tagName == "BUTTON") && target.type == "submit" && target.form) {
            submitButtonsByForm2.set(target.form, target);
          }
        }
        function didSubmitForm2(event) {
          handleFormSubmissionEvent2(event);
        }
        function didSubmitRemoteElement2(event) {
          if (event.target.tagName == "FORM") {
            handleFormSubmissionEvent2(event);
          }
        }
        function handleFormSubmissionEvent2(event) {
          var form = event.target;
          if (form.hasAttribute(processingAttribute2)) {
            event.preventDefault();
            return;
          }
          var controller = new DirectUploadsController2(form);
          var inputs = controller.inputs;
          if (inputs.length) {
            event.preventDefault();
            form.setAttribute(processingAttribute2, "");
            inputs.forEach(disable2);
            controller.start(function(error3) {
              form.removeAttribute(processingAttribute2);
              if (error3) {
                inputs.forEach(enable2);
              } else {
                submitForm2(form);
              }
            });
          }
        }
        function submitForm2(form) {
          var button = submitButtonsByForm2.get(form) || findElement2(form, "input[type=submit], button[type=submit]");
          if (button) {
            var _button = button, disabled = _button.disabled;
            button.disabled = false;
            button.focus();
            button.click();
            button.disabled = disabled;
          } else {
            button = document.createElement("input");
            button.type = "submit";
            button.style.display = "none";
            form.appendChild(button);
            button.click();
            form.removeChild(button);
          }
          submitButtonsByForm2.delete(form);
        }
        function disable2(input) {
          input.disabled = true;
        }
        function enable2(input) {
          input.disabled = false;
        }
        function autostart2() {
          if (window.ActiveStorage) {
            start4();
          }
        }
        setTimeout(autostart2, 1);
        exports2.start = start4;
        exports2.DirectUpload = DirectUpload2;
        Object.defineProperty(exports2, "__esModule", {
          value: true
        });
      });
    }
  });

  // ../../node_modules/@hotwired/turbo/dist/turbo.es2017-esm.js
  var turbo_es2017_esm_exports = {};
  __export(turbo_es2017_esm_exports, {
    FetchEnctype: () => FetchEnctype,
    FetchMethod: () => FetchMethod,
    FetchRequest: () => FetchRequest,
    FetchResponse: () => FetchResponse,
    FrameElement: () => FrameElement,
    FrameLoadingStyle: () => FrameLoadingStyle,
    FrameRenderer: () => FrameRenderer,
    PageRenderer: () => PageRenderer,
    PageSnapshot: () => PageSnapshot,
    StreamActions: () => StreamActions,
    StreamElement: () => StreamElement,
    StreamSourceElement: () => StreamSourceElement,
    cache: () => cache,
    clearCache: () => clearCache,
    connectStreamSource: () => connectStreamSource,
    disconnectStreamSource: () => disconnectStreamSource,
    fetch: () => fetchWithTurboHeaders,
    fetchEnctypeFromString: () => fetchEnctypeFromString,
    fetchMethodFromString: () => fetchMethodFromString,
    isSafe: () => isSafe,
    navigator: () => navigator$1,
    registerAdapter: () => registerAdapter,
    renderStreamMessage: () => renderStreamMessage,
    session: () => session,
    setConfirmMethod: () => setConfirmMethod,
    setFormMode: () => setFormMode,
    setProgressBarDelay: () => setProgressBarDelay,
    start: () => start,
    visit: () => visit
  });
  (function(prototype) {
    if (typeof prototype.requestSubmit == "function")
      return;
    prototype.requestSubmit = function(submitter) {
      if (submitter) {
        validateSubmitter(submitter, this);
        submitter.click();
      } else {
        submitter = document.createElement("input");
        submitter.type = "submit";
        submitter.hidden = true;
        this.appendChild(submitter);
        submitter.click();
        this.removeChild(submitter);
      }
    };
    function validateSubmitter(submitter, form) {
      submitter instanceof HTMLElement || raise(TypeError, "parameter 1 is not of type 'HTMLElement'");
      submitter.type == "submit" || raise(TypeError, "The specified element is not a submit button");
      submitter.form == form || raise(DOMException, "The specified element is not owned by this form element", "NotFoundError");
    }
    function raise(errorConstructor, message, name) {
      throw new errorConstructor("Failed to execute 'requestSubmit' on 'HTMLFormElement': " + message + ".", name);
    }
  })(HTMLFormElement.prototype);
  var submittersByForm = /* @__PURE__ */ new WeakMap();
  function findSubmitterFromClickTarget(target) {
    const element = target instanceof Element ? target : target instanceof Node ? target.parentElement : null;
    const candidate = element ? element.closest("input, button") : null;
    return candidate?.type == "submit" ? candidate : null;
  }
  function clickCaptured(event) {
    const submitter = findSubmitterFromClickTarget(event.target);
    if (submitter && submitter.form) {
      submittersByForm.set(submitter.form, submitter);
    }
  }
  (function() {
    if ("submitter" in Event.prototype)
      return;
    let prototype = window.Event.prototype;
    if ("SubmitEvent" in window) {
      const prototypeOfSubmitEvent = window.SubmitEvent.prototype;
      if (/Apple Computer/.test(navigator.vendor) && !("submitter" in prototypeOfSubmitEvent)) {
        prototype = prototypeOfSubmitEvent;
      } else {
        return;
      }
    }
    addEventListener("click", clickCaptured, true);
    Object.defineProperty(prototype, "submitter", {
      get() {
        if (this.type == "submit" && this.target instanceof HTMLFormElement) {
          return submittersByForm.get(this.target);
        }
      }
    });
  })();
  var FrameLoadingStyle = {
    eager: "eager",
    lazy: "lazy"
  };
  var _FrameElement = class extends HTMLElement {
    loaded = Promise.resolve();
    static get observedAttributes() {
      return ["disabled", "complete", "loading", "src"];
    }
    constructor() {
      super();
      this.delegate = new _FrameElement.delegateConstructor(this);
    }
    connectedCallback() {
      this.delegate.connect();
    }
    disconnectedCallback() {
      this.delegate.disconnect();
    }
    reload() {
      return this.delegate.sourceURLReloaded();
    }
    attributeChangedCallback(name) {
      if (name == "loading") {
        this.delegate.loadingStyleChanged();
      } else if (name == "complete") {
        this.delegate.completeChanged();
      } else if (name == "src") {
        this.delegate.sourceURLChanged();
      } else {
        this.delegate.disabledChanged();
      }
    }
    get src() {
      return this.getAttribute("src");
    }
    set src(value) {
      if (value) {
        this.setAttribute("src", value);
      } else {
        this.removeAttribute("src");
      }
    }
    get refresh() {
      return this.getAttribute("refresh");
    }
    set refresh(value) {
      if (value) {
        this.setAttribute("refresh", value);
      } else {
        this.removeAttribute("refresh");
      }
    }
    get loading() {
      return frameLoadingStyleFromString(this.getAttribute("loading") || "");
    }
    set loading(value) {
      if (value) {
        this.setAttribute("loading", value);
      } else {
        this.removeAttribute("loading");
      }
    }
    get disabled() {
      return this.hasAttribute("disabled");
    }
    set disabled(value) {
      if (value) {
        this.setAttribute("disabled", "");
      } else {
        this.removeAttribute("disabled");
      }
    }
    get autoscroll() {
      return this.hasAttribute("autoscroll");
    }
    set autoscroll(value) {
      if (value) {
        this.setAttribute("autoscroll", "");
      } else {
        this.removeAttribute("autoscroll");
      }
    }
    get complete() {
      return !this.delegate.isLoading;
    }
    get isActive() {
      return this.ownerDocument === document && !this.isPreview;
    }
    get isPreview() {
      return this.ownerDocument?.documentElement?.hasAttribute("data-turbo-preview");
    }
  };
  var FrameElement = _FrameElement;
  __publicField(FrameElement, "delegateConstructor");
  function frameLoadingStyleFromString(style) {
    switch (style.toLowerCase()) {
      case "lazy":
        return FrameLoadingStyle.lazy;
      default:
        return FrameLoadingStyle.eager;
    }
  }
  function expandURL(locatable) {
    return new URL(locatable.toString(), document.baseURI);
  }
  function getAnchor(url) {
    let anchorMatch;
    if (url.hash) {
      return url.hash.slice(1);
    } else if (anchorMatch = url.href.match(/#(.*)$/)) {
      return anchorMatch[1];
    }
  }
  function getAction$1(form, submitter) {
    const action = submitter?.getAttribute("formaction") || form.getAttribute("action") || form.action;
    return expandURL(action);
  }
  function getExtension(url) {
    return (getLastPathComponent(url).match(/\.[^.]*$/) || [])[0] || "";
  }
  function isHTML(url) {
    return !!getExtension(url).match(/^(?:|\.(?:htm|html|xhtml|php))$/);
  }
  function isPrefixedBy(baseURL, url) {
    const prefix = getPrefix(url);
    return baseURL.href === expandURL(prefix).href || baseURL.href.startsWith(prefix);
  }
  function locationIsVisitable(location2, rootLocation) {
    return isPrefixedBy(location2, rootLocation) && isHTML(location2);
  }
  function getRequestURL(url) {
    const anchor = getAnchor(url);
    return anchor != null ? url.href.slice(0, -(anchor.length + 1)) : url.href;
  }
  function toCacheKey(url) {
    return getRequestURL(url);
  }
  function urlsAreEqual(left2, right2) {
    return expandURL(left2).href == expandURL(right2).href;
  }
  function getPathComponents(url) {
    return url.pathname.split("/").slice(1);
  }
  function getLastPathComponent(url) {
    return getPathComponents(url).slice(-1)[0];
  }
  function getPrefix(url) {
    return addTrailingSlash(url.origin + url.pathname);
  }
  function addTrailingSlash(value) {
    return value.endsWith("/") ? value : value + "/";
  }
  var FetchResponse = class {
    constructor(response) {
      this.response = response;
    }
    get succeeded() {
      return this.response.ok;
    }
    get failed() {
      return !this.succeeded;
    }
    get clientError() {
      return this.statusCode >= 400 && this.statusCode <= 499;
    }
    get serverError() {
      return this.statusCode >= 500 && this.statusCode <= 599;
    }
    get redirected() {
      return this.response.redirected;
    }
    get location() {
      return expandURL(this.response.url);
    }
    get isHTML() {
      return this.contentType && this.contentType.match(/^(?:text\/([^\s;,]+\b)?html|application\/xhtml\+xml)\b/);
    }
    get statusCode() {
      return this.response.status;
    }
    get contentType() {
      return this.header("Content-Type");
    }
    get responseText() {
      return this.response.clone().text();
    }
    get responseHTML() {
      if (this.isHTML) {
        return this.response.clone().text();
      } else {
        return Promise.resolve(void 0);
      }
    }
    header(name) {
      return this.response.headers.get(name);
    }
  };
  function activateScriptElement(element) {
    if (element.getAttribute("data-turbo-eval") == "false") {
      return element;
    } else {
      const createdScriptElement = document.createElement("script");
      const cspNonce = getMetaContent("csp-nonce");
      if (cspNonce) {
        createdScriptElement.nonce = cspNonce;
      }
      createdScriptElement.textContent = element.textContent;
      createdScriptElement.async = false;
      copyElementAttributes(createdScriptElement, element);
      return createdScriptElement;
    }
  }
  function copyElementAttributes(destinationElement, sourceElement) {
    for (const { name, value } of sourceElement.attributes) {
      destinationElement.setAttribute(name, value);
    }
  }
  function createDocumentFragment(html) {
    const template = document.createElement("template");
    template.innerHTML = html;
    return template.content;
  }
  function dispatch(eventName, { target, cancelable, detail } = {}) {
    const event = new CustomEvent(eventName, {
      cancelable,
      bubbles: true,
      composed: true,
      detail
    });
    if (target && target.isConnected) {
      target.dispatchEvent(event);
    } else {
      document.documentElement.dispatchEvent(event);
    }
    return event;
  }
  function nextRepaint() {
    if (document.visibilityState === "hidden") {
      return nextEventLoopTick();
    } else {
      return nextAnimationFrame();
    }
  }
  function nextAnimationFrame() {
    return new Promise((resolve2) => requestAnimationFrame(() => resolve2()));
  }
  function nextEventLoopTick() {
    return new Promise((resolve2) => setTimeout(() => resolve2(), 0));
  }
  function nextMicrotask() {
    return Promise.resolve();
  }
  function parseHTMLDocument(html = "") {
    return new DOMParser().parseFromString(html, "text/html");
  }
  function unindent(strings, ...values) {
    const lines = interpolate(strings, values).replace(/^\n/, "").split("\n");
    const match2 = lines[0].match(/^\s+/);
    const indent = match2 ? match2[0].length : 0;
    return lines.map((line) => line.slice(indent)).join("\n");
  }
  function interpolate(strings, values) {
    return strings.reduce((result, string, i2) => {
      const value = values[i2] == void 0 ? "" : values[i2];
      return result + string + value;
    }, "");
  }
  function uuid() {
    return Array.from({ length: 36 }).map((_2, i2) => {
      if (i2 == 8 || i2 == 13 || i2 == 18 || i2 == 23) {
        return "-";
      } else if (i2 == 14) {
        return "4";
      } else if (i2 == 19) {
        return (Math.floor(Math.random() * 4) + 8).toString(16);
      } else {
        return Math.floor(Math.random() * 15).toString(16);
      }
    }).join("");
  }
  function getAttribute(attributeName, ...elements2) {
    for (const value of elements2.map((element) => element?.getAttribute(attributeName))) {
      if (typeof value == "string")
        return value;
    }
    return null;
  }
  function hasAttribute(attributeName, ...elements2) {
    return elements2.some((element) => element && element.hasAttribute(attributeName));
  }
  function markAsBusy(...elements2) {
    for (const element of elements2) {
      if (element.localName == "turbo-frame") {
        element.setAttribute("busy", "");
      }
      element.setAttribute("aria-busy", "true");
    }
  }
  function clearBusyState(...elements2) {
    for (const element of elements2) {
      if (element.localName == "turbo-frame") {
        element.removeAttribute("busy");
      }
      element.removeAttribute("aria-busy");
    }
  }
  function waitForLoad(element, timeoutInMilliseconds = 2e3) {
    return new Promise((resolve2) => {
      const onComplete = () => {
        element.removeEventListener("error", onComplete);
        element.removeEventListener("load", onComplete);
        resolve2();
      };
      element.addEventListener("load", onComplete, { once: true });
      element.addEventListener("error", onComplete, { once: true });
      setTimeout(resolve2, timeoutInMilliseconds);
    });
  }
  function getHistoryMethodForAction(action) {
    switch (action) {
      case "replace":
        return history.replaceState;
      case "advance":
      case "restore":
        return history.pushState;
    }
  }
  function isAction(action) {
    return action == "advance" || action == "replace" || action == "restore";
  }
  function getVisitAction(...elements2) {
    const action = getAttribute("data-turbo-action", ...elements2);
    return isAction(action) ? action : null;
  }
  function getMetaElement(name) {
    return document.querySelector(`meta[name="${name}"]`);
  }
  function getMetaContent(name) {
    const element = getMetaElement(name);
    return element && element.content;
  }
  function setMetaContent(name, content) {
    let element = getMetaElement(name);
    if (!element) {
      element = document.createElement("meta");
      element.setAttribute("name", name);
      document.head.appendChild(element);
    }
    element.setAttribute("content", content);
    return element;
  }
  function findClosestRecursively(element, selector) {
    if (element instanceof Element) {
      return element.closest(selector) || findClosestRecursively(element.assignedSlot || element.getRootNode()?.host, selector);
    }
  }
  function elementIsFocusable(element) {
    const inertDisabledOrHidden = "[inert], :disabled, [hidden], details:not([open]), dialog:not([open])";
    return !!element && element.closest(inertDisabledOrHidden) == null && typeof element.focus == "function";
  }
  function queryAutofocusableElement(elementOrDocumentFragment) {
    return Array.from(elementOrDocumentFragment.querySelectorAll("[autofocus]")).find(elementIsFocusable);
  }
  async function around(callback2, reader) {
    const before = reader();
    callback2();
    await nextAnimationFrame();
    const after = reader();
    return [before, after];
  }
  function doesNotTargetIFrame(anchor) {
    if (anchor.hasAttribute("target")) {
      for (const element of document.getElementsByName(anchor.target)) {
        if (element instanceof HTMLIFrameElement)
          return false;
      }
    }
    return true;
  }
  function findLinkFromClickTarget(target) {
    return findClosestRecursively(target, "a[href]:not([target^=_]):not([download])");
  }
  function getLocationForLink(link) {
    return expandURL(link.getAttribute("href") || "");
  }
  function debounce(fn3, delay) {
    let timeoutId = null;
    return (...args) => {
      const callback2 = () => fn3.apply(this, args);
      clearTimeout(timeoutId);
      timeoutId = setTimeout(callback2, delay);
    };
  }
  var LimitedSet = class extends Set {
    constructor(maxSize) {
      super();
      this.maxSize = maxSize;
    }
    add(value) {
      if (this.size >= this.maxSize) {
        const iterator = this.values();
        const oldestValue = iterator.next().value;
        this.delete(oldestValue);
      }
      super.add(value);
    }
  };
  var recentRequests = new LimitedSet(20);
  var nativeFetch = window.fetch;
  function fetchWithTurboHeaders(url, options = {}) {
    const modifiedHeaders = new Headers(options.headers || {});
    const requestUID = uuid();
    recentRequests.add(requestUID);
    modifiedHeaders.append("X-Turbo-Request-Id", requestUID);
    return nativeFetch(url, {
      ...options,
      headers: modifiedHeaders
    });
  }
  function fetchMethodFromString(method) {
    switch (method.toLowerCase()) {
      case "get":
        return FetchMethod.get;
      case "post":
        return FetchMethod.post;
      case "put":
        return FetchMethod.put;
      case "patch":
        return FetchMethod.patch;
      case "delete":
        return FetchMethod.delete;
    }
  }
  var FetchMethod = {
    get: "get",
    post: "post",
    put: "put",
    patch: "patch",
    delete: "delete"
  };
  function fetchEnctypeFromString(encoding) {
    switch (encoding.toLowerCase()) {
      case FetchEnctype.multipart:
        return FetchEnctype.multipart;
      case FetchEnctype.plain:
        return FetchEnctype.plain;
      default:
        return FetchEnctype.urlEncoded;
    }
  }
  var FetchEnctype = {
    urlEncoded: "application/x-www-form-urlencoded",
    multipart: "multipart/form-data",
    plain: "text/plain"
  };
  var FetchRequest = class {
    abortController = new AbortController();
    #resolveRequestPromise = (_value) => {
    };
    constructor(delegate, method, location2, requestBody = new URLSearchParams(), target = null, enctype = FetchEnctype.urlEncoded) {
      const [url, body] = buildResourceAndBody(expandURL(location2), method, requestBody, enctype);
      this.delegate = delegate;
      this.url = url;
      this.target = target;
      this.fetchOptions = {
        credentials: "same-origin",
        redirect: "follow",
        method,
        headers: { ...this.defaultHeaders },
        body,
        signal: this.abortSignal,
        referrer: this.delegate.referrer?.href
      };
      this.enctype = enctype;
    }
    get method() {
      return this.fetchOptions.method;
    }
    set method(value) {
      const fetchBody = this.isSafe ? this.url.searchParams : this.fetchOptions.body || new FormData();
      const fetchMethod = fetchMethodFromString(value) || FetchMethod.get;
      this.url.search = "";
      const [url, body] = buildResourceAndBody(this.url, fetchMethod, fetchBody, this.enctype);
      this.url = url;
      this.fetchOptions.body = body;
      this.fetchOptions.method = fetchMethod;
    }
    get headers() {
      return this.fetchOptions.headers;
    }
    set headers(value) {
      this.fetchOptions.headers = value;
    }
    get body() {
      if (this.isSafe) {
        return this.url.searchParams;
      } else {
        return this.fetchOptions.body;
      }
    }
    set body(value) {
      this.fetchOptions.body = value;
    }
    get location() {
      return this.url;
    }
    get params() {
      return this.url.searchParams;
    }
    get entries() {
      return this.body ? Array.from(this.body.entries()) : [];
    }
    cancel() {
      this.abortController.abort();
    }
    async perform() {
      const { fetchOptions } = this;
      this.delegate.prepareRequest(this);
      const event = await this.#allowRequestToBeIntercepted(fetchOptions);
      try {
        this.delegate.requestStarted(this);
        if (event.detail.fetchRequest) {
          this.response = event.detail.fetchRequest.response;
        } else {
          this.response = fetchWithTurboHeaders(this.url.href, fetchOptions);
        }
        const response = await this.response;
        return await this.receive(response);
      } catch (error3) {
        if (error3.name !== "AbortError") {
          if (this.#willDelegateErrorHandling(error3)) {
            this.delegate.requestErrored(this, error3);
          }
          throw error3;
        }
      } finally {
        this.delegate.requestFinished(this);
      }
    }
    async receive(response) {
      const fetchResponse = new FetchResponse(response);
      const event = dispatch("turbo:before-fetch-response", {
        cancelable: true,
        detail: { fetchResponse },
        target: this.target
      });
      if (event.defaultPrevented) {
        this.delegate.requestPreventedHandlingResponse(this, fetchResponse);
      } else if (fetchResponse.succeeded) {
        this.delegate.requestSucceededWithResponse(this, fetchResponse);
      } else {
        this.delegate.requestFailedWithResponse(this, fetchResponse);
      }
      return fetchResponse;
    }
    get defaultHeaders() {
      return {
        Accept: "text/html, application/xhtml+xml"
      };
    }
    get isSafe() {
      return isSafe(this.method);
    }
    get abortSignal() {
      return this.abortController.signal;
    }
    acceptResponseType(mimeType) {
      this.headers["Accept"] = [mimeType, this.headers["Accept"]].join(", ");
    }
    async #allowRequestToBeIntercepted(fetchOptions) {
      const requestInterception = new Promise((resolve2) => this.#resolveRequestPromise = resolve2);
      const event = dispatch("turbo:before-fetch-request", {
        cancelable: true,
        detail: {
          fetchOptions,
          url: this.url,
          resume: this.#resolveRequestPromise
        },
        target: this.target
      });
      this.url = event.detail.url;
      if (event.defaultPrevented)
        await requestInterception;
      return event;
    }
    #willDelegateErrorHandling(error3) {
      const event = dispatch("turbo:fetch-request-error", {
        target: this.target,
        cancelable: true,
        detail: { request: this, error: error3 }
      });
      return !event.defaultPrevented;
    }
  };
  function isSafe(fetchMethod) {
    return fetchMethodFromString(fetchMethod) == FetchMethod.get;
  }
  function buildResourceAndBody(resource, method, requestBody, enctype) {
    const searchParams = Array.from(requestBody).length > 0 ? new URLSearchParams(entriesExcludingFiles(requestBody)) : resource.searchParams;
    if (isSafe(method)) {
      return [mergeIntoURLSearchParams(resource, searchParams), null];
    } else if (enctype == FetchEnctype.urlEncoded) {
      return [resource, searchParams];
    } else {
      return [resource, requestBody];
    }
  }
  function entriesExcludingFiles(requestBody) {
    const entries = [];
    for (const [name, value] of requestBody) {
      if (value instanceof File)
        continue;
      else
        entries.push([name, value]);
    }
    return entries;
  }
  function mergeIntoURLSearchParams(url, requestBody) {
    const searchParams = new URLSearchParams(entriesExcludingFiles(requestBody));
    url.search = searchParams.toString();
    return url;
  }
  var AppearanceObserver = class {
    started = false;
    constructor(delegate, element) {
      this.delegate = delegate;
      this.element = element;
      this.intersectionObserver = new IntersectionObserver(this.intersect);
    }
    start() {
      if (!this.started) {
        this.started = true;
        this.intersectionObserver.observe(this.element);
      }
    }
    stop() {
      if (this.started) {
        this.started = false;
        this.intersectionObserver.unobserve(this.element);
      }
    }
    intersect = (entries) => {
      const lastEntry = entries.slice(-1)[0];
      if (lastEntry?.isIntersecting) {
        this.delegate.elementAppearedInViewport(this.element);
      }
    };
  };
  var StreamMessage = class {
    static wrap(message) {
      if (typeof message == "string") {
        return new this(createDocumentFragment(message));
      } else {
        return message;
      }
    }
    constructor(fragment) {
      this.fragment = importStreamElements(fragment);
    }
  };
  __publicField(StreamMessage, "contentType", "text/vnd.turbo-stream.html");
  function importStreamElements(fragment) {
    for (const element of fragment.querySelectorAll("turbo-stream")) {
      const streamElement = document.importNode(element, true);
      for (const inertScriptElement of streamElement.templateElement.content.querySelectorAll("script")) {
        inertScriptElement.replaceWith(activateScriptElement(inertScriptElement));
      }
      element.replaceWith(streamElement);
    }
    return fragment;
  }
  var PREFETCH_DELAY = 100;
  var PrefetchCache = class {
    #prefetchTimeout = null;
    #prefetched = null;
    get(url) {
      if (this.#prefetched && this.#prefetched.url === url && this.#prefetched.expire > Date.now()) {
        return this.#prefetched.request;
      }
    }
    setLater(url, request, ttl) {
      this.clear();
      this.#prefetchTimeout = setTimeout(() => {
        request.perform();
        this.set(url, request, ttl);
        this.#prefetchTimeout = null;
      }, PREFETCH_DELAY);
    }
    set(url, request, ttl) {
      this.#prefetched = { url, request, expire: new Date(new Date().getTime() + ttl) };
    }
    clear() {
      if (this.#prefetchTimeout)
        clearTimeout(this.#prefetchTimeout);
      this.#prefetched = null;
    }
  };
  var cacheTtl = 10 * 1e3;
  var prefetchCache = new PrefetchCache();
  var FormSubmissionState = {
    initialized: "initialized",
    requesting: "requesting",
    waiting: "waiting",
    receiving: "receiving",
    stopping: "stopping",
    stopped: "stopped"
  };
  var FormSubmission = class {
    state = FormSubmissionState.initialized;
    static confirmMethod(message, _element, _submitter) {
      return Promise.resolve(confirm(message));
    }
    constructor(delegate, formElement, submitter, mustRedirect = false) {
      const method = getMethod(formElement, submitter);
      const action = getAction(getFormAction(formElement, submitter), method);
      const body = buildFormData(formElement, submitter);
      const enctype = getEnctype(formElement, submitter);
      this.delegate = delegate;
      this.formElement = formElement;
      this.submitter = submitter;
      this.fetchRequest = new FetchRequest(this, method, action, body, formElement, enctype);
      this.mustRedirect = mustRedirect;
    }
    get method() {
      return this.fetchRequest.method;
    }
    set method(value) {
      this.fetchRequest.method = value;
    }
    get action() {
      return this.fetchRequest.url.toString();
    }
    set action(value) {
      this.fetchRequest.url = expandURL(value);
    }
    get body() {
      return this.fetchRequest.body;
    }
    get enctype() {
      return this.fetchRequest.enctype;
    }
    get isSafe() {
      return this.fetchRequest.isSafe;
    }
    get location() {
      return this.fetchRequest.url;
    }
    async start() {
      const { initialized, requesting } = FormSubmissionState;
      const confirmationMessage = getAttribute("data-turbo-confirm", this.submitter, this.formElement);
      if (typeof confirmationMessage === "string") {
        const answer = await FormSubmission.confirmMethod(confirmationMessage, this.formElement, this.submitter);
        if (!answer) {
          return;
        }
      }
      if (this.state == initialized) {
        this.state = requesting;
        return this.fetchRequest.perform();
      }
    }
    stop() {
      const { stopping, stopped } = FormSubmissionState;
      if (this.state != stopping && this.state != stopped) {
        this.state = stopping;
        this.fetchRequest.cancel();
        return true;
      }
    }
    prepareRequest(request) {
      if (!request.isSafe) {
        const token = getCookieValue(getMetaContent("csrf-param")) || getMetaContent("csrf-token");
        if (token) {
          request.headers["X-CSRF-Token"] = token;
        }
      }
      if (this.requestAcceptsTurboStreamResponse(request)) {
        request.acceptResponseType(StreamMessage.contentType);
      }
    }
    requestStarted(_request) {
      this.state = FormSubmissionState.waiting;
      this.submitter?.setAttribute("disabled", "");
      this.setSubmitsWith();
      markAsBusy(this.formElement);
      dispatch("turbo:submit-start", {
        target: this.formElement,
        detail: { formSubmission: this }
      });
      this.delegate.formSubmissionStarted(this);
    }
    requestPreventedHandlingResponse(request, response) {
      prefetchCache.clear();
      this.result = { success: response.succeeded, fetchResponse: response };
    }
    requestSucceededWithResponse(request, response) {
      if (response.clientError || response.serverError) {
        this.delegate.formSubmissionFailedWithResponse(this, response);
        return;
      }
      prefetchCache.clear();
      if (this.requestMustRedirect(request) && responseSucceededWithoutRedirect(response)) {
        const error3 = new Error("Form responses must redirect to another location");
        this.delegate.formSubmissionErrored(this, error3);
      } else {
        this.state = FormSubmissionState.receiving;
        this.result = { success: true, fetchResponse: response };
        this.delegate.formSubmissionSucceededWithResponse(this, response);
      }
    }
    requestFailedWithResponse(request, response) {
      this.result = { success: false, fetchResponse: response };
      this.delegate.formSubmissionFailedWithResponse(this, response);
    }
    requestErrored(request, error3) {
      this.result = { success: false, error: error3 };
      this.delegate.formSubmissionErrored(this, error3);
    }
    requestFinished(_request) {
      this.state = FormSubmissionState.stopped;
      this.submitter?.removeAttribute("disabled");
      this.resetSubmitterText();
      clearBusyState(this.formElement);
      dispatch("turbo:submit-end", {
        target: this.formElement,
        detail: { formSubmission: this, ...this.result }
      });
      this.delegate.formSubmissionFinished(this);
    }
    setSubmitsWith() {
      if (!this.submitter || !this.submitsWith)
        return;
      if (this.submitter.matches("button")) {
        this.originalSubmitText = this.submitter.innerHTML;
        this.submitter.innerHTML = this.submitsWith;
      } else if (this.submitter.matches("input")) {
        const input = this.submitter;
        this.originalSubmitText = input.value;
        input.value = this.submitsWith;
      }
    }
    resetSubmitterText() {
      if (!this.submitter || !this.originalSubmitText)
        return;
      if (this.submitter.matches("button")) {
        this.submitter.innerHTML = this.originalSubmitText;
      } else if (this.submitter.matches("input")) {
        const input = this.submitter;
        input.value = this.originalSubmitText;
      }
    }
    requestMustRedirect(request) {
      return !request.isSafe && this.mustRedirect;
    }
    requestAcceptsTurboStreamResponse(request) {
      return !request.isSafe || hasAttribute("data-turbo-stream", this.submitter, this.formElement);
    }
    get submitsWith() {
      return this.submitter?.getAttribute("data-turbo-submits-with");
    }
  };
  function buildFormData(formElement, submitter) {
    const formData = new FormData(formElement);
    const name = submitter?.getAttribute("name");
    const value = submitter?.getAttribute("value");
    if (name) {
      formData.append(name, value || "");
    }
    return formData;
  }
  function getCookieValue(cookieName) {
    if (cookieName != null) {
      const cookies = document.cookie ? document.cookie.split("; ") : [];
      const cookie = cookies.find((cookie2) => cookie2.startsWith(cookieName));
      if (cookie) {
        const value = cookie.split("=").slice(1).join("=");
        return value ? decodeURIComponent(value) : void 0;
      }
    }
  }
  function responseSucceededWithoutRedirect(response) {
    return response.statusCode == 200 && !response.redirected;
  }
  function getFormAction(formElement, submitter) {
    const formElementAction = typeof formElement.action === "string" ? formElement.action : null;
    if (submitter?.hasAttribute("formaction")) {
      return submitter.getAttribute("formaction") || "";
    } else {
      return formElement.getAttribute("action") || formElementAction || "";
    }
  }
  function getAction(formAction, fetchMethod) {
    const action = expandURL(formAction);
    if (isSafe(fetchMethod)) {
      action.search = "";
    }
    return action;
  }
  function getMethod(formElement, submitter) {
    const method = submitter?.getAttribute("formmethod") || formElement.getAttribute("method") || "";
    return fetchMethodFromString(method.toLowerCase()) || FetchMethod.get;
  }
  function getEnctype(formElement, submitter) {
    return fetchEnctypeFromString(submitter?.getAttribute("formenctype") || formElement.enctype);
  }
  var Snapshot = class {
    constructor(element) {
      this.element = element;
    }
    get activeElement() {
      return this.element.ownerDocument.activeElement;
    }
    get children() {
      return [...this.element.children];
    }
    hasAnchor(anchor) {
      return this.getElementForAnchor(anchor) != null;
    }
    getElementForAnchor(anchor) {
      return anchor ? this.element.querySelector(`[id='${anchor}'], a[name='${anchor}']`) : null;
    }
    get isConnected() {
      return this.element.isConnected;
    }
    get firstAutofocusableElement() {
      return queryAutofocusableElement(this.element);
    }
    get permanentElements() {
      return queryPermanentElementsAll(this.element);
    }
    getPermanentElementById(id2) {
      return getPermanentElementById(this.element, id2);
    }
    getPermanentElementMapForSnapshot(snapshot) {
      const permanentElementMap = {};
      for (const currentPermanentElement of this.permanentElements) {
        const { id: id2 } = currentPermanentElement;
        const newPermanentElement = snapshot.getPermanentElementById(id2);
        if (newPermanentElement) {
          permanentElementMap[id2] = [currentPermanentElement, newPermanentElement];
        }
      }
      return permanentElementMap;
    }
  };
  function getPermanentElementById(node, id2) {
    return node.querySelector(`#${id2}[data-turbo-permanent]`);
  }
  function queryPermanentElementsAll(node) {
    return node.querySelectorAll("[id][data-turbo-permanent]");
  }
  var FormSubmitObserver = class {
    started = false;
    constructor(delegate, eventTarget) {
      this.delegate = delegate;
      this.eventTarget = eventTarget;
    }
    start() {
      if (!this.started) {
        this.eventTarget.addEventListener("submit", this.submitCaptured, true);
        this.started = true;
      }
    }
    stop() {
      if (this.started) {
        this.eventTarget.removeEventListener("submit", this.submitCaptured, true);
        this.started = false;
      }
    }
    submitCaptured = () => {
      this.eventTarget.removeEventListener("submit", this.submitBubbled, false);
      this.eventTarget.addEventListener("submit", this.submitBubbled, false);
    };
    submitBubbled = (event) => {
      if (!event.defaultPrevented) {
        const form = event.target instanceof HTMLFormElement ? event.target : void 0;
        const submitter = event.submitter || void 0;
        if (form && submissionDoesNotDismissDialog(form, submitter) && submissionDoesNotTargetIFrame(form, submitter) && this.delegate.willSubmitForm(form, submitter)) {
          event.preventDefault();
          event.stopImmediatePropagation();
          this.delegate.formSubmitted(form, submitter);
        }
      }
    };
  };
  function submissionDoesNotDismissDialog(form, submitter) {
    const method = submitter?.getAttribute("formmethod") || form.getAttribute("method");
    return method != "dialog";
  }
  function submissionDoesNotTargetIFrame(form, submitter) {
    if (submitter?.hasAttribute("formtarget") || form.hasAttribute("target")) {
      const target = submitter?.getAttribute("formtarget") || form.target;
      for (const element of document.getElementsByName(target)) {
        if (element instanceof HTMLIFrameElement)
          return false;
      }
      return true;
    } else {
      return true;
    }
  }
  var View = class {
    #resolveRenderPromise = (_value) => {
    };
    #resolveInterceptionPromise = (_value) => {
    };
    constructor(delegate, element) {
      this.delegate = delegate;
      this.element = element;
    }
    scrollToAnchor(anchor) {
      const element = this.snapshot.getElementForAnchor(anchor);
      if (element) {
        this.scrollToElement(element);
        this.focusElement(element);
      } else {
        this.scrollToPosition({ x: 0, y: 0 });
      }
    }
    scrollToAnchorFromLocation(location2) {
      this.scrollToAnchor(getAnchor(location2));
    }
    scrollToElement(element) {
      element.scrollIntoView();
    }
    focusElement(element) {
      if (element instanceof HTMLElement) {
        if (element.hasAttribute("tabindex")) {
          element.focus();
        } else {
          element.setAttribute("tabindex", "-1");
          element.focus();
          element.removeAttribute("tabindex");
        }
      }
    }
    scrollToPosition({ x: x2, y: y2 }) {
      this.scrollRoot.scrollTo(x2, y2);
    }
    scrollToTop() {
      this.scrollToPosition({ x: 0, y: 0 });
    }
    get scrollRoot() {
      return window;
    }
    async render(renderer) {
      const { isPreview, shouldRender, willRender, newSnapshot: snapshot } = renderer;
      const shouldInvalidate = willRender;
      if (shouldRender) {
        try {
          this.renderPromise = new Promise((resolve2) => this.#resolveRenderPromise = resolve2);
          this.renderer = renderer;
          await this.prepareToRenderSnapshot(renderer);
          const renderInterception = new Promise((resolve2) => this.#resolveInterceptionPromise = resolve2);
          const options = { resume: this.#resolveInterceptionPromise, render: this.renderer.renderElement, renderMethod: this.renderer.renderMethod };
          const immediateRender = this.delegate.allowsImmediateRender(snapshot, options);
          if (!immediateRender)
            await renderInterception;
          await this.renderSnapshot(renderer);
          this.delegate.viewRenderedSnapshot(snapshot, isPreview, this.renderer.renderMethod);
          this.delegate.preloadOnLoadLinksForView(this.element);
          this.finishRenderingSnapshot(renderer);
        } finally {
          delete this.renderer;
          this.#resolveRenderPromise(void 0);
          delete this.renderPromise;
        }
      } else if (shouldInvalidate) {
        this.invalidate(renderer.reloadReason);
      }
    }
    invalidate(reason) {
      this.delegate.viewInvalidated(reason);
    }
    async prepareToRenderSnapshot(renderer) {
      this.markAsPreview(renderer.isPreview);
      await renderer.prepareToRender();
    }
    markAsPreview(isPreview) {
      if (isPreview) {
        this.element.setAttribute("data-turbo-preview", "");
      } else {
        this.element.removeAttribute("data-turbo-preview");
      }
    }
    markVisitDirection(direction) {
      this.element.setAttribute("data-turbo-visit-direction", direction);
    }
    unmarkVisitDirection() {
      this.element.removeAttribute("data-turbo-visit-direction");
    }
    async renderSnapshot(renderer) {
      await renderer.render();
    }
    finishRenderingSnapshot(renderer) {
      renderer.finishRendering();
    }
  };
  var FrameView = class extends View {
    missing() {
      this.element.innerHTML = `<strong class="turbo-frame-error">Content missing</strong>`;
    }
    get snapshot() {
      return new Snapshot(this.element);
    }
  };
  var LinkInterceptor = class {
    constructor(delegate, element) {
      this.delegate = delegate;
      this.element = element;
    }
    start() {
      this.element.addEventListener("click", this.clickBubbled);
      document.addEventListener("turbo:click", this.linkClicked);
      document.addEventListener("turbo:before-visit", this.willVisit);
    }
    stop() {
      this.element.removeEventListener("click", this.clickBubbled);
      document.removeEventListener("turbo:click", this.linkClicked);
      document.removeEventListener("turbo:before-visit", this.willVisit);
    }
    clickBubbled = (event) => {
      if (this.respondsToEventTarget(event.target)) {
        this.clickEvent = event;
      } else {
        delete this.clickEvent;
      }
    };
    linkClicked = (event) => {
      if (this.clickEvent && this.respondsToEventTarget(event.target) && event.target instanceof Element) {
        if (this.delegate.shouldInterceptLinkClick(event.target, event.detail.url, event.detail.originalEvent)) {
          this.clickEvent.preventDefault();
          event.preventDefault();
          this.delegate.linkClickIntercepted(event.target, event.detail.url, event.detail.originalEvent);
        }
      }
      delete this.clickEvent;
    };
    willVisit = (_event) => {
      delete this.clickEvent;
    };
    respondsToEventTarget(target) {
      const element = target instanceof Element ? target : target instanceof Node ? target.parentElement : null;
      return element && element.closest("turbo-frame, html") == this.element;
    }
  };
  var LinkClickObserver = class {
    started = false;
    constructor(delegate, eventTarget) {
      this.delegate = delegate;
      this.eventTarget = eventTarget;
    }
    start() {
      if (!this.started) {
        this.eventTarget.addEventListener("click", this.clickCaptured, true);
        this.started = true;
      }
    }
    stop() {
      if (this.started) {
        this.eventTarget.removeEventListener("click", this.clickCaptured, true);
        this.started = false;
      }
    }
    clickCaptured = () => {
      this.eventTarget.removeEventListener("click", this.clickBubbled, false);
      this.eventTarget.addEventListener("click", this.clickBubbled, false);
    };
    clickBubbled = (event) => {
      if (event instanceof MouseEvent && this.clickEventIsSignificant(event)) {
        const target = event.composedPath && event.composedPath()[0] || event.target;
        const link = findLinkFromClickTarget(target);
        if (link && doesNotTargetIFrame(link)) {
          const location2 = getLocationForLink(link);
          if (this.delegate.willFollowLinkToLocation(link, location2, event)) {
            event.preventDefault();
            this.delegate.followedLinkToLocation(link, location2);
          }
        }
      }
    };
    clickEventIsSignificant(event) {
      return !(event.target && event.target.isContentEditable || event.defaultPrevented || event.which > 1 || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey);
    }
  };
  var FormLinkClickObserver = class {
    constructor(delegate, element) {
      this.delegate = delegate;
      this.linkInterceptor = new LinkClickObserver(this, element);
    }
    start() {
      this.linkInterceptor.start();
    }
    stop() {
      this.linkInterceptor.stop();
    }
    canPrefetchRequestToLocation(link, location2) {
      return false;
    }
    prefetchAndCacheRequestToLocation(link, location2) {
      return;
    }
    willFollowLinkToLocation(link, location2, originalEvent) {
      return this.delegate.willSubmitFormLinkToLocation(link, location2, originalEvent) && (link.hasAttribute("data-turbo-method") || link.hasAttribute("data-turbo-stream"));
    }
    followedLinkToLocation(link, location2) {
      const form = document.createElement("form");
      const type = "hidden";
      for (const [name, value] of location2.searchParams) {
        form.append(Object.assign(document.createElement("input"), { type, name, value }));
      }
      const action = Object.assign(location2, { search: "" });
      form.setAttribute("data-turbo", "true");
      form.setAttribute("action", action.href);
      form.setAttribute("hidden", "");
      const method = link.getAttribute("data-turbo-method");
      if (method)
        form.setAttribute("method", method);
      const turboFrame = link.getAttribute("data-turbo-frame");
      if (turboFrame)
        form.setAttribute("data-turbo-frame", turboFrame);
      const turboAction = getVisitAction(link);
      if (turboAction)
        form.setAttribute("data-turbo-action", turboAction);
      const turboConfirm = link.getAttribute("data-turbo-confirm");
      if (turboConfirm)
        form.setAttribute("data-turbo-confirm", turboConfirm);
      const turboStream = link.hasAttribute("data-turbo-stream");
      if (turboStream)
        form.setAttribute("data-turbo-stream", "");
      this.delegate.submittedFormLinkToLocation(link, location2, form);
      document.body.appendChild(form);
      form.addEventListener("turbo:submit-end", () => form.remove(), { once: true });
      requestAnimationFrame(() => form.requestSubmit());
    }
  };
  var Bardo = class {
    static async preservingPermanentElements(delegate, permanentElementMap, callback2) {
      const bardo = new this(delegate, permanentElementMap);
      bardo.enter();
      await callback2();
      bardo.leave();
    }
    constructor(delegate, permanentElementMap) {
      this.delegate = delegate;
      this.permanentElementMap = permanentElementMap;
    }
    enter() {
      for (const id2 in this.permanentElementMap) {
        const [currentPermanentElement, newPermanentElement] = this.permanentElementMap[id2];
        this.delegate.enteringBardo(currentPermanentElement, newPermanentElement);
        this.replaceNewPermanentElementWithPlaceholder(newPermanentElement);
      }
    }
    leave() {
      for (const id2 in this.permanentElementMap) {
        const [currentPermanentElement] = this.permanentElementMap[id2];
        this.replaceCurrentPermanentElementWithClone(currentPermanentElement);
        this.replacePlaceholderWithPermanentElement(currentPermanentElement);
        this.delegate.leavingBardo(currentPermanentElement);
      }
    }
    replaceNewPermanentElementWithPlaceholder(permanentElement) {
      const placeholder = createPlaceholderForPermanentElement(permanentElement);
      permanentElement.replaceWith(placeholder);
    }
    replaceCurrentPermanentElementWithClone(permanentElement) {
      const clone2 = permanentElement.cloneNode(true);
      permanentElement.replaceWith(clone2);
    }
    replacePlaceholderWithPermanentElement(permanentElement) {
      const placeholder = this.getPlaceholderById(permanentElement.id);
      placeholder?.replaceWith(permanentElement);
    }
    getPlaceholderById(id2) {
      return this.placeholders.find((element) => element.content == id2);
    }
    get placeholders() {
      return [...document.querySelectorAll("meta[name=turbo-permanent-placeholder][content]")];
    }
  };
  function createPlaceholderForPermanentElement(permanentElement) {
    const element = document.createElement("meta");
    element.setAttribute("name", "turbo-permanent-placeholder");
    element.setAttribute("content", permanentElement.id);
    return element;
  }
  var Renderer = class {
    #activeElement = null;
    constructor(currentSnapshot, newSnapshot, renderElement, isPreview, willRender = true) {
      this.currentSnapshot = currentSnapshot;
      this.newSnapshot = newSnapshot;
      this.isPreview = isPreview;
      this.willRender = willRender;
      this.renderElement = renderElement;
      this.promise = new Promise((resolve2, reject) => this.resolvingFunctions = { resolve: resolve2, reject });
    }
    get shouldRender() {
      return true;
    }
    get reloadReason() {
      return;
    }
    prepareToRender() {
      return;
    }
    render() {
    }
    finishRendering() {
      if (this.resolvingFunctions) {
        this.resolvingFunctions.resolve();
        delete this.resolvingFunctions;
      }
    }
    async preservingPermanentElements(callback2) {
      await Bardo.preservingPermanentElements(this, this.permanentElementMap, callback2);
    }
    focusFirstAutofocusableElement() {
      const element = this.connectedSnapshot.firstAutofocusableElement;
      if (element) {
        element.focus();
      }
    }
    enteringBardo(currentPermanentElement) {
      if (this.#activeElement)
        return;
      if (currentPermanentElement.contains(this.currentSnapshot.activeElement)) {
        this.#activeElement = this.currentSnapshot.activeElement;
      }
    }
    leavingBardo(currentPermanentElement) {
      if (currentPermanentElement.contains(this.#activeElement) && this.#activeElement instanceof HTMLElement) {
        this.#activeElement.focus();
        this.#activeElement = null;
      }
    }
    get connectedSnapshot() {
      return this.newSnapshot.isConnected ? this.newSnapshot : this.currentSnapshot;
    }
    get currentElement() {
      return this.currentSnapshot.element;
    }
    get newElement() {
      return this.newSnapshot.element;
    }
    get permanentElementMap() {
      return this.currentSnapshot.getPermanentElementMapForSnapshot(this.newSnapshot);
    }
    get renderMethod() {
      return "replace";
    }
  };
  var FrameRenderer = class extends Renderer {
    static renderElement(currentElement, newElement) {
      const destinationRange = document.createRange();
      destinationRange.selectNodeContents(currentElement);
      destinationRange.deleteContents();
      const frameElement = newElement;
      const sourceRange = frameElement.ownerDocument?.createRange();
      if (sourceRange) {
        sourceRange.selectNodeContents(frameElement);
        currentElement.appendChild(sourceRange.extractContents());
      }
    }
    constructor(delegate, currentSnapshot, newSnapshot, renderElement, isPreview, willRender = true) {
      super(currentSnapshot, newSnapshot, renderElement, isPreview, willRender);
      this.delegate = delegate;
    }
    get shouldRender() {
      return true;
    }
    async render() {
      await nextRepaint();
      this.preservingPermanentElements(() => {
        this.loadFrameElement();
      });
      this.scrollFrameIntoView();
      await nextRepaint();
      this.focusFirstAutofocusableElement();
      await nextRepaint();
      this.activateScriptElements();
    }
    loadFrameElement() {
      this.delegate.willRenderFrame(this.currentElement, this.newElement);
      this.renderElement(this.currentElement, this.newElement);
    }
    scrollFrameIntoView() {
      if (this.currentElement.autoscroll || this.newElement.autoscroll) {
        const element = this.currentElement.firstElementChild;
        const block = readScrollLogicalPosition(this.currentElement.getAttribute("data-autoscroll-block"), "end");
        const behavior = readScrollBehavior(this.currentElement.getAttribute("data-autoscroll-behavior"), "auto");
        if (element) {
          element.scrollIntoView({ block, behavior });
          return true;
        }
      }
      return false;
    }
    activateScriptElements() {
      for (const inertScriptElement of this.newScriptElements) {
        const activatedScriptElement = activateScriptElement(inertScriptElement);
        inertScriptElement.replaceWith(activatedScriptElement);
      }
    }
    get newScriptElements() {
      return this.currentElement.querySelectorAll("script");
    }
  };
  function readScrollLogicalPosition(value, defaultValue) {
    if (value == "end" || value == "start" || value == "center" || value == "nearest") {
      return value;
    } else {
      return defaultValue;
    }
  }
  function readScrollBehavior(value, defaultValue) {
    if (value == "auto" || value == "smooth") {
      return value;
    } else {
      return defaultValue;
    }
  }
  var _ProgressBar = class {
    static get defaultCSS() {
      return unindent`
      .turbo-progress-bar {
        position: fixed;
        display: block;
        top: 0;
        left: 0;
        height: 3px;
        background: #0076ff;
        z-index: 2147483647;
        transition:
          width ${_ProgressBar.animationDuration}ms ease-out,
          opacity ${_ProgressBar.animationDuration / 2}ms ${_ProgressBar.animationDuration / 2}ms ease-in;
        transform: translate3d(0, 0, 0);
      }
    `;
    }
    hiding = false;
    value = 0;
    visible = false;
    constructor() {
      this.stylesheetElement = this.createStylesheetElement();
      this.progressElement = this.createProgressElement();
      this.installStylesheetElement();
      this.setValue(0);
    }
    show() {
      if (!this.visible) {
        this.visible = true;
        this.installProgressElement();
        this.startTrickling();
      }
    }
    hide() {
      if (this.visible && !this.hiding) {
        this.hiding = true;
        this.fadeProgressElement(() => {
          this.uninstallProgressElement();
          this.stopTrickling();
          this.visible = false;
          this.hiding = false;
        });
      }
    }
    setValue(value) {
      this.value = value;
      this.refresh();
    }
    installStylesheetElement() {
      document.head.insertBefore(this.stylesheetElement, document.head.firstChild);
    }
    installProgressElement() {
      this.progressElement.style.width = "0";
      this.progressElement.style.opacity = "1";
      document.documentElement.insertBefore(this.progressElement, document.body);
      this.refresh();
    }
    fadeProgressElement(callback2) {
      this.progressElement.style.opacity = "0";
      setTimeout(callback2, _ProgressBar.animationDuration * 1.5);
    }
    uninstallProgressElement() {
      if (this.progressElement.parentNode) {
        document.documentElement.removeChild(this.progressElement);
      }
    }
    startTrickling() {
      if (!this.trickleInterval) {
        this.trickleInterval = window.setInterval(this.trickle, _ProgressBar.animationDuration);
      }
    }
    stopTrickling() {
      window.clearInterval(this.trickleInterval);
      delete this.trickleInterval;
    }
    trickle = () => {
      this.setValue(this.value + Math.random() / 100);
    };
    refresh() {
      requestAnimationFrame(() => {
        this.progressElement.style.width = `${10 + this.value * 90}%`;
      });
    }
    createStylesheetElement() {
      const element = document.createElement("style");
      element.type = "text/css";
      element.textContent = _ProgressBar.defaultCSS;
      if (this.cspNonce) {
        element.nonce = this.cspNonce;
      }
      return element;
    }
    createProgressElement() {
      const element = document.createElement("div");
      element.className = "turbo-progress-bar";
      return element;
    }
    get cspNonce() {
      return getMetaContent("csp-nonce");
    }
  };
  var ProgressBar = _ProgressBar;
  __publicField(ProgressBar, "animationDuration", 300);
  var HeadSnapshot = class extends Snapshot {
    detailsByOuterHTML = this.children.filter((element) => !elementIsNoscript(element)).map((element) => elementWithoutNonce(element)).reduce((result, element) => {
      const { outerHTML } = element;
      const details = outerHTML in result ? result[outerHTML] : {
        type: elementType(element),
        tracked: elementIsTracked(element),
        elements: []
      };
      return {
        ...result,
        [outerHTML]: {
          ...details,
          elements: [...details.elements, element]
        }
      };
    }, {});
    get trackedElementSignature() {
      return Object.keys(this.detailsByOuterHTML).filter((outerHTML) => this.detailsByOuterHTML[outerHTML].tracked).join("");
    }
    getScriptElementsNotInSnapshot(snapshot) {
      return this.getElementsMatchingTypeNotInSnapshot("script", snapshot);
    }
    getStylesheetElementsNotInSnapshot(snapshot) {
      return this.getElementsMatchingTypeNotInSnapshot("stylesheet", snapshot);
    }
    getElementsMatchingTypeNotInSnapshot(matchedType, snapshot) {
      return Object.keys(this.detailsByOuterHTML).filter((outerHTML) => !(outerHTML in snapshot.detailsByOuterHTML)).map((outerHTML) => this.detailsByOuterHTML[outerHTML]).filter(({ type }) => type == matchedType).map(({ elements: [element] }) => element);
    }
    get provisionalElements() {
      return Object.keys(this.detailsByOuterHTML).reduce((result, outerHTML) => {
        const { type, tracked, elements: elements2 } = this.detailsByOuterHTML[outerHTML];
        if (type == null && !tracked) {
          return [...result, ...elements2];
        } else if (elements2.length > 1) {
          return [...result, ...elements2.slice(1)];
        } else {
          return result;
        }
      }, []);
    }
    getMetaValue(name) {
      const element = this.findMetaElementByName(name);
      return element ? element.getAttribute("content") : null;
    }
    findMetaElementByName(name) {
      return Object.keys(this.detailsByOuterHTML).reduce((result, outerHTML) => {
        const {
          elements: [element]
        } = this.detailsByOuterHTML[outerHTML];
        return elementIsMetaElementWithName(element, name) ? element : result;
      }, void 0 | void 0);
    }
  };
  function elementType(element) {
    if (elementIsScript(element)) {
      return "script";
    } else if (elementIsStylesheet(element)) {
      return "stylesheet";
    }
  }
  function elementIsTracked(element) {
    return element.getAttribute("data-turbo-track") == "reload";
  }
  function elementIsScript(element) {
    const tagName = element.localName;
    return tagName == "script";
  }
  function elementIsNoscript(element) {
    const tagName = element.localName;
    return tagName == "noscript";
  }
  function elementIsStylesheet(element) {
    const tagName = element.localName;
    return tagName == "style" || tagName == "link" && element.getAttribute("rel") == "stylesheet";
  }
  function elementIsMetaElementWithName(element, name) {
    const tagName = element.localName;
    return tagName == "meta" && element.getAttribute("name") == name;
  }
  function elementWithoutNonce(element) {
    if (element.hasAttribute("nonce")) {
      element.setAttribute("nonce", "");
    }
    return element;
  }
  var PageSnapshot = class extends Snapshot {
    static fromHTMLString(html = "") {
      return this.fromDocument(parseHTMLDocument(html));
    }
    static fromElement(element) {
      return this.fromDocument(element.ownerDocument);
    }
    static fromDocument({ documentElement, body, head }) {
      return new this(documentElement, body, new HeadSnapshot(head));
    }
    constructor(documentElement, body, headSnapshot) {
      super(body);
      this.documentElement = documentElement;
      this.headSnapshot = headSnapshot;
    }
    clone() {
      const clonedElement = this.element.cloneNode(true);
      const selectElements = this.element.querySelectorAll("select");
      const clonedSelectElements = clonedElement.querySelectorAll("select");
      for (const [index, source] of selectElements.entries()) {
        const clone2 = clonedSelectElements[index];
        for (const option of clone2.selectedOptions)
          option.selected = false;
        for (const option of source.selectedOptions)
          clone2.options[option.index].selected = true;
      }
      for (const clonedPasswordInput of clonedElement.querySelectorAll('input[type="password"]')) {
        clonedPasswordInput.value = "";
      }
      return new PageSnapshot(this.documentElement, clonedElement, this.headSnapshot);
    }
    get lang() {
      return this.documentElement.getAttribute("lang");
    }
    get headElement() {
      return this.headSnapshot.element;
    }
    get rootLocation() {
      const root = this.getSetting("root") ?? "/";
      return expandURL(root);
    }
    get cacheControlValue() {
      return this.getSetting("cache-control");
    }
    get isPreviewable() {
      return this.cacheControlValue != "no-preview";
    }
    get isCacheable() {
      return this.cacheControlValue != "no-cache";
    }
    get isVisitable() {
      return this.getSetting("visit-control") != "reload";
    }
    get prefersViewTransitions() {
      return this.headSnapshot.getMetaValue("view-transition") === "same-origin";
    }
    get shouldMorphPage() {
      return this.getSetting("refresh-method") === "morph";
    }
    get shouldPreserveScrollPosition() {
      return this.getSetting("refresh-scroll") === "preserve";
    }
    getSetting(name) {
      return this.headSnapshot.getMetaValue(`turbo-${name}`);
    }
  };
  var ViewTransitioner = class {
    #viewTransitionStarted = false;
    #lastOperation = Promise.resolve();
    renderChange(useViewTransition, render) {
      if (useViewTransition && this.viewTransitionsAvailable && !this.#viewTransitionStarted) {
        this.#viewTransitionStarted = true;
        this.#lastOperation = this.#lastOperation.then(async () => {
          await document.startViewTransition(render).finished;
        });
      } else {
        this.#lastOperation = this.#lastOperation.then(render);
      }
      return this.#lastOperation;
    }
    get viewTransitionsAvailable() {
      return document.startViewTransition;
    }
  };
  var defaultOptions = {
    action: "advance",
    historyChanged: false,
    visitCachedSnapshot: () => {
    },
    willRender: true,
    updateHistory: true,
    shouldCacheSnapshot: true,
    acceptsStreamResponse: false
  };
  var TimingMetric = {
    visitStart: "visitStart",
    requestStart: "requestStart",
    requestEnd: "requestEnd",
    visitEnd: "visitEnd"
  };
  var VisitState = {
    initialized: "initialized",
    started: "started",
    canceled: "canceled",
    failed: "failed",
    completed: "completed"
  };
  var SystemStatusCode = {
    networkFailure: 0,
    timeoutFailure: -1,
    contentTypeMismatch: -2
  };
  var Direction = {
    advance: "forward",
    restore: "back",
    replace: "none"
  };
  var Visit = class {
    identifier = uuid();
    timingMetrics = {};
    followedRedirect = false;
    historyChanged = false;
    scrolled = false;
    shouldCacheSnapshot = true;
    acceptsStreamResponse = false;
    snapshotCached = false;
    state = VisitState.initialized;
    viewTransitioner = new ViewTransitioner();
    constructor(delegate, location2, restorationIdentifier, options = {}) {
      this.delegate = delegate;
      this.location = location2;
      this.restorationIdentifier = restorationIdentifier || uuid();
      const {
        action,
        historyChanged,
        referrer,
        snapshot,
        snapshotHTML,
        response,
        visitCachedSnapshot,
        willRender,
        updateHistory,
        shouldCacheSnapshot,
        acceptsStreamResponse,
        direction
      } = {
        ...defaultOptions,
        ...options
      };
      this.action = action;
      this.historyChanged = historyChanged;
      this.referrer = referrer;
      this.snapshot = snapshot;
      this.snapshotHTML = snapshotHTML;
      this.response = response;
      this.isSamePage = this.delegate.locationWithActionIsSamePage(this.location, this.action);
      this.isPageRefresh = this.view.isPageRefresh(this);
      this.visitCachedSnapshot = visitCachedSnapshot;
      this.willRender = willRender;
      this.updateHistory = updateHistory;
      this.scrolled = !willRender;
      this.shouldCacheSnapshot = shouldCacheSnapshot;
      this.acceptsStreamResponse = acceptsStreamResponse;
      this.direction = direction || Direction[action];
    }
    get adapter() {
      return this.delegate.adapter;
    }
    get view() {
      return this.delegate.view;
    }
    get history() {
      return this.delegate.history;
    }
    get restorationData() {
      return this.history.getRestorationDataForIdentifier(this.restorationIdentifier);
    }
    get silent() {
      return this.isSamePage;
    }
    start() {
      if (this.state == VisitState.initialized) {
        this.recordTimingMetric(TimingMetric.visitStart);
        this.state = VisitState.started;
        this.adapter.visitStarted(this);
        this.delegate.visitStarted(this);
      }
    }
    cancel() {
      if (this.state == VisitState.started) {
        if (this.request) {
          this.request.cancel();
        }
        this.cancelRender();
        this.state = VisitState.canceled;
      }
    }
    complete() {
      if (this.state == VisitState.started) {
        this.recordTimingMetric(TimingMetric.visitEnd);
        this.adapter.visitCompleted(this);
        this.state = VisitState.completed;
        this.followRedirect();
        if (!this.followedRedirect) {
          this.delegate.visitCompleted(this);
        }
      }
    }
    fail() {
      if (this.state == VisitState.started) {
        this.state = VisitState.failed;
        this.adapter.visitFailed(this);
        this.delegate.visitCompleted(this);
      }
    }
    changeHistory() {
      if (!this.historyChanged && this.updateHistory) {
        const actionForHistory = this.location.href === this.referrer?.href ? "replace" : this.action;
        const method = getHistoryMethodForAction(actionForHistory);
        this.history.update(method, this.location, this.restorationIdentifier);
        this.historyChanged = true;
      }
    }
    issueRequest() {
      if (this.hasPreloadedResponse()) {
        this.simulateRequest();
      } else if (this.shouldIssueRequest() && !this.request) {
        this.request = new FetchRequest(this, FetchMethod.get, this.location);
        this.request.perform();
      }
    }
    simulateRequest() {
      if (this.response) {
        this.startRequest();
        this.recordResponse();
        this.finishRequest();
      }
    }
    startRequest() {
      this.recordTimingMetric(TimingMetric.requestStart);
      this.adapter.visitRequestStarted(this);
    }
    recordResponse(response = this.response) {
      this.response = response;
      if (response) {
        const { statusCode } = response;
        if (isSuccessful(statusCode)) {
          this.adapter.visitRequestCompleted(this);
        } else {
          this.adapter.visitRequestFailedWithStatusCode(this, statusCode);
        }
      }
    }
    finishRequest() {
      this.recordTimingMetric(TimingMetric.requestEnd);
      this.adapter.visitRequestFinished(this);
    }
    loadResponse() {
      if (this.response) {
        const { statusCode, responseHTML } = this.response;
        this.render(async () => {
          if (this.shouldCacheSnapshot)
            this.cacheSnapshot();
          if (this.view.renderPromise)
            await this.view.renderPromise;
          if (isSuccessful(statusCode) && responseHTML != null) {
            const snapshot = PageSnapshot.fromHTMLString(responseHTML);
            await this.renderPageSnapshot(snapshot, false);
            this.adapter.visitRendered(this);
            this.complete();
          } else {
            await this.view.renderError(PageSnapshot.fromHTMLString(responseHTML), this);
            this.adapter.visitRendered(this);
            this.fail();
          }
        });
      }
    }
    getCachedSnapshot() {
      const snapshot = this.view.getCachedSnapshotForLocation(this.location) || this.getPreloadedSnapshot();
      if (snapshot && (!getAnchor(this.location) || snapshot.hasAnchor(getAnchor(this.location)))) {
        if (this.action == "restore" || snapshot.isPreviewable) {
          return snapshot;
        }
      }
    }
    getPreloadedSnapshot() {
      if (this.snapshotHTML) {
        return PageSnapshot.fromHTMLString(this.snapshotHTML);
      }
    }
    hasCachedSnapshot() {
      return this.getCachedSnapshot() != null;
    }
    loadCachedSnapshot() {
      const snapshot = this.getCachedSnapshot();
      if (snapshot) {
        const isPreview = this.shouldIssueRequest();
        this.render(async () => {
          this.cacheSnapshot();
          if (this.isSamePage || this.isPageRefresh) {
            this.adapter.visitRendered(this);
          } else {
            if (this.view.renderPromise)
              await this.view.renderPromise;
            await this.renderPageSnapshot(snapshot, isPreview);
            this.adapter.visitRendered(this);
            if (!isPreview) {
              this.complete();
            }
          }
        });
      }
    }
    followRedirect() {
      if (this.redirectedToLocation && !this.followedRedirect && this.response?.redirected) {
        this.adapter.visitProposedToLocation(this.redirectedToLocation, {
          action: "replace",
          response: this.response,
          shouldCacheSnapshot: false,
          willRender: false
        });
        this.followedRedirect = true;
      }
    }
    goToSamePageAnchor() {
      if (this.isSamePage) {
        this.render(async () => {
          this.cacheSnapshot();
          this.performScroll();
          this.changeHistory();
          this.adapter.visitRendered(this);
        });
      }
    }
    prepareRequest(request) {
      if (this.acceptsStreamResponse) {
        request.acceptResponseType(StreamMessage.contentType);
      }
    }
    requestStarted() {
      this.startRequest();
    }
    requestPreventedHandlingResponse(_request, _response) {
    }
    async requestSucceededWithResponse(request, response) {
      const responseHTML = await response.responseHTML;
      const { redirected, statusCode } = response;
      if (responseHTML == void 0) {
        this.recordResponse({
          statusCode: SystemStatusCode.contentTypeMismatch,
          redirected
        });
      } else {
        this.redirectedToLocation = response.redirected ? response.location : void 0;
        this.recordResponse({ statusCode, responseHTML, redirected });
      }
    }
    async requestFailedWithResponse(request, response) {
      const responseHTML = await response.responseHTML;
      const { redirected, statusCode } = response;
      if (responseHTML == void 0) {
        this.recordResponse({
          statusCode: SystemStatusCode.contentTypeMismatch,
          redirected
        });
      } else {
        this.recordResponse({ statusCode, responseHTML, redirected });
      }
    }
    requestErrored(_request, _error) {
      this.recordResponse({
        statusCode: SystemStatusCode.networkFailure,
        redirected: false
      });
    }
    requestFinished() {
      this.finishRequest();
    }
    performScroll() {
      if (!this.scrolled && !this.view.forceReloaded && !this.view.shouldPreserveScrollPosition(this)) {
        if (this.action == "restore") {
          this.scrollToRestoredPosition() || this.scrollToAnchor() || this.view.scrollToTop();
        } else {
          this.scrollToAnchor() || this.view.scrollToTop();
        }
        if (this.isSamePage) {
          this.delegate.visitScrolledToSamePageLocation(this.view.lastRenderedLocation, this.location);
        }
        this.scrolled = true;
      }
    }
    scrollToRestoredPosition() {
      const { scrollPosition } = this.restorationData;
      if (scrollPosition) {
        this.view.scrollToPosition(scrollPosition);
        return true;
      }
    }
    scrollToAnchor() {
      const anchor = getAnchor(this.location);
      if (anchor != null) {
        this.view.scrollToAnchor(anchor);
        return true;
      }
    }
    recordTimingMetric(metric) {
      this.timingMetrics[metric] = new Date().getTime();
    }
    getTimingMetrics() {
      return { ...this.timingMetrics };
    }
    getHistoryMethodForAction(action) {
      switch (action) {
        case "replace":
          return history.replaceState;
        case "advance":
        case "restore":
          return history.pushState;
      }
    }
    hasPreloadedResponse() {
      return typeof this.response == "object";
    }
    shouldIssueRequest() {
      if (this.isSamePage) {
        return false;
      } else if (this.action == "restore") {
        return !this.hasCachedSnapshot();
      } else {
        return this.willRender;
      }
    }
    cacheSnapshot() {
      if (!this.snapshotCached) {
        this.view.cacheSnapshot(this.snapshot).then((snapshot) => snapshot && this.visitCachedSnapshot(snapshot));
        this.snapshotCached = true;
      }
    }
    async render(callback2) {
      this.cancelRender();
      this.frame = await nextRepaint();
      await callback2();
      delete this.frame;
    }
    async renderPageSnapshot(snapshot, isPreview) {
      await this.viewTransitioner.renderChange(this.view.shouldTransitionTo(snapshot), async () => {
        await this.view.renderPage(snapshot, isPreview, this.willRender, this);
        this.performScroll();
      });
    }
    cancelRender() {
      if (this.frame) {
        cancelAnimationFrame(this.frame);
        delete this.frame;
      }
    }
  };
  function isSuccessful(statusCode) {
    return statusCode >= 200 && statusCode < 300;
  }
  var BrowserAdapter = class {
    progressBar = new ProgressBar();
    constructor(session2) {
      this.session = session2;
    }
    visitProposedToLocation(location2, options) {
      if (locationIsVisitable(location2, this.navigator.rootLocation)) {
        this.navigator.startVisit(location2, options?.restorationIdentifier || uuid(), options);
      } else {
        window.location.href = location2.toString();
      }
    }
    visitStarted(visit2) {
      this.location = visit2.location;
      visit2.loadCachedSnapshot();
      visit2.issueRequest();
      visit2.goToSamePageAnchor();
    }
    visitRequestStarted(visit2) {
      this.progressBar.setValue(0);
      if (visit2.hasCachedSnapshot() || visit2.action != "restore") {
        this.showVisitProgressBarAfterDelay();
      } else {
        this.showProgressBar();
      }
    }
    visitRequestCompleted(visit2) {
      visit2.loadResponse();
    }
    visitRequestFailedWithStatusCode(visit2, statusCode) {
      switch (statusCode) {
        case SystemStatusCode.networkFailure:
        case SystemStatusCode.timeoutFailure:
        case SystemStatusCode.contentTypeMismatch:
          return this.reload({
            reason: "request_failed",
            context: {
              statusCode
            }
          });
        default:
          return visit2.loadResponse();
      }
    }
    visitRequestFinished(_visit) {
    }
    visitCompleted(_visit) {
      this.progressBar.setValue(1);
      this.hideVisitProgressBar();
    }
    pageInvalidated(reason) {
      this.reload(reason);
    }
    visitFailed(_visit) {
      this.progressBar.setValue(1);
      this.hideVisitProgressBar();
    }
    visitRendered(_visit) {
    }
    formSubmissionStarted(_formSubmission) {
      this.progressBar.setValue(0);
      this.showFormProgressBarAfterDelay();
    }
    formSubmissionFinished(_formSubmission) {
      this.progressBar.setValue(1);
      this.hideFormProgressBar();
    }
    showVisitProgressBarAfterDelay() {
      this.visitProgressBarTimeout = window.setTimeout(this.showProgressBar, this.session.progressBarDelay);
    }
    hideVisitProgressBar() {
      this.progressBar.hide();
      if (this.visitProgressBarTimeout != null) {
        window.clearTimeout(this.visitProgressBarTimeout);
        delete this.visitProgressBarTimeout;
      }
    }
    showFormProgressBarAfterDelay() {
      if (this.formProgressBarTimeout == null) {
        this.formProgressBarTimeout = window.setTimeout(this.showProgressBar, this.session.progressBarDelay);
      }
    }
    hideFormProgressBar() {
      this.progressBar.hide();
      if (this.formProgressBarTimeout != null) {
        window.clearTimeout(this.formProgressBarTimeout);
        delete this.formProgressBarTimeout;
      }
    }
    showProgressBar = () => {
      this.progressBar.show();
    };
    reload(reason) {
      dispatch("turbo:reload", { detail: reason });
      window.location.href = this.location?.toString() || window.location.href;
    }
    get navigator() {
      return this.session.navigator;
    }
  };
  var CacheObserver = class {
    selector = "[data-turbo-temporary]";
    deprecatedSelector = "[data-turbo-cache=false]";
    started = false;
    start() {
      if (!this.started) {
        this.started = true;
        addEventListener("turbo:before-cache", this.removeTemporaryElements, false);
      }
    }
    stop() {
      if (this.started) {
        this.started = false;
        removeEventListener("turbo:before-cache", this.removeTemporaryElements, false);
      }
    }
    removeTemporaryElements = (_event) => {
      for (const element of this.temporaryElements) {
        element.remove();
      }
    };
    get temporaryElements() {
      return [...document.querySelectorAll(this.selector), ...this.temporaryElementsWithDeprecation];
    }
    get temporaryElementsWithDeprecation() {
      const elements2 = document.querySelectorAll(this.deprecatedSelector);
      if (elements2.length) {
        console.warn(`The ${this.deprecatedSelector} selector is deprecated and will be removed in a future version. Use ${this.selector} instead.`);
      }
      return [...elements2];
    }
  };
  var FrameRedirector = class {
    constructor(session2, element) {
      this.session = session2;
      this.element = element;
      this.linkInterceptor = new LinkInterceptor(this, element);
      this.formSubmitObserver = new FormSubmitObserver(this, element);
    }
    start() {
      this.linkInterceptor.start();
      this.formSubmitObserver.start();
    }
    stop() {
      this.linkInterceptor.stop();
      this.formSubmitObserver.stop();
    }
    shouldInterceptLinkClick(element, _location, _event) {
      return this.#shouldRedirect(element);
    }
    linkClickIntercepted(element, url, event) {
      const frame = this.#findFrameElement(element);
      if (frame) {
        frame.delegate.linkClickIntercepted(element, url, event);
      }
    }
    willSubmitForm(element, submitter) {
      return element.closest("turbo-frame") == null && this.#shouldSubmit(element, submitter) && this.#shouldRedirect(element, submitter);
    }
    formSubmitted(element, submitter) {
      const frame = this.#findFrameElement(element, submitter);
      if (frame) {
        frame.delegate.formSubmitted(element, submitter);
      }
    }
    #shouldSubmit(form, submitter) {
      const action = getAction$1(form, submitter);
      const meta = this.element.ownerDocument.querySelector(`meta[name="turbo-root"]`);
      const rootLocation = expandURL(meta?.content ?? "/");
      return this.#shouldRedirect(form, submitter) && locationIsVisitable(action, rootLocation);
    }
    #shouldRedirect(element, submitter) {
      const isNavigatable = element instanceof HTMLFormElement ? this.session.submissionIsNavigatable(element, submitter) : this.session.elementIsNavigatable(element);
      if (isNavigatable) {
        const frame = this.#findFrameElement(element, submitter);
        return frame ? frame != element.closest("turbo-frame") : false;
      } else {
        return false;
      }
    }
    #findFrameElement(element, submitter) {
      const id2 = submitter?.getAttribute("data-turbo-frame") || element.getAttribute("data-turbo-frame");
      if (id2 && id2 != "_top") {
        const frame = this.element.querySelector(`#${id2}:not([disabled])`);
        if (frame instanceof FrameElement) {
          return frame;
        }
      }
    }
  };
  var History = class {
    location;
    restorationIdentifier = uuid();
    restorationData = {};
    started = false;
    pageLoaded = false;
    currentIndex = 0;
    constructor(delegate) {
      this.delegate = delegate;
    }
    start() {
      if (!this.started) {
        addEventListener("popstate", this.onPopState, false);
        addEventListener("load", this.onPageLoad, false);
        this.currentIndex = history.state?.turbo?.restorationIndex || 0;
        this.started = true;
        this.replace(new URL(window.location.href));
      }
    }
    stop() {
      if (this.started) {
        removeEventListener("popstate", this.onPopState, false);
        removeEventListener("load", this.onPageLoad, false);
        this.started = false;
      }
    }
    push(location2, restorationIdentifier) {
      this.update(history.pushState, location2, restorationIdentifier);
    }
    replace(location2, restorationIdentifier) {
      this.update(history.replaceState, location2, restorationIdentifier);
    }
    update(method, location2, restorationIdentifier = uuid()) {
      if (method === history.pushState)
        ++this.currentIndex;
      const state = { turbo: { restorationIdentifier, restorationIndex: this.currentIndex } };
      method.call(history, state, "", location2.href);
      this.location = location2;
      this.restorationIdentifier = restorationIdentifier;
    }
    getRestorationDataForIdentifier(restorationIdentifier) {
      return this.restorationData[restorationIdentifier] || {};
    }
    updateRestorationData(additionalData) {
      const { restorationIdentifier } = this;
      const restorationData = this.restorationData[restorationIdentifier];
      this.restorationData[restorationIdentifier] = {
        ...restorationData,
        ...additionalData
      };
    }
    assumeControlOfScrollRestoration() {
      if (!this.previousScrollRestoration) {
        this.previousScrollRestoration = history.scrollRestoration ?? "auto";
        history.scrollRestoration = "manual";
      }
    }
    relinquishControlOfScrollRestoration() {
      if (this.previousScrollRestoration) {
        history.scrollRestoration = this.previousScrollRestoration;
        delete this.previousScrollRestoration;
      }
    }
    onPopState = (event) => {
      if (this.shouldHandlePopState()) {
        const { turbo } = event.state || {};
        if (turbo) {
          this.location = new URL(window.location.href);
          const { restorationIdentifier, restorationIndex } = turbo;
          this.restorationIdentifier = restorationIdentifier;
          const direction = restorationIndex > this.currentIndex ? "forward" : "back";
          this.delegate.historyPoppedToLocationWithRestorationIdentifierAndDirection(this.location, restorationIdentifier, direction);
          this.currentIndex = restorationIndex;
        }
      }
    };
    onPageLoad = async (_event) => {
      await nextMicrotask();
      this.pageLoaded = true;
    };
    shouldHandlePopState() {
      return this.pageIsLoaded();
    }
    pageIsLoaded() {
      return this.pageLoaded || document.readyState == "complete";
    }
  };
  var LinkPrefetchObserver = class {
    started = false;
    #prefetchedLink = null;
    constructor(delegate, eventTarget) {
      this.delegate = delegate;
      this.eventTarget = eventTarget;
    }
    start() {
      if (this.started)
        return;
      if (this.eventTarget.readyState === "loading") {
        this.eventTarget.addEventListener("DOMContentLoaded", this.#enable, { once: true });
      } else {
        this.#enable();
      }
    }
    stop() {
      if (!this.started)
        return;
      this.eventTarget.removeEventListener("mouseenter", this.#tryToPrefetchRequest, {
        capture: true,
        passive: true
      });
      this.eventTarget.removeEventListener("mouseleave", this.#cancelRequestIfObsolete, {
        capture: true,
        passive: true
      });
      this.eventTarget.removeEventListener("turbo:before-fetch-request", this.#tryToUsePrefetchedRequest, true);
      this.started = false;
    }
    #enable = () => {
      this.eventTarget.addEventListener("mouseenter", this.#tryToPrefetchRequest, {
        capture: true,
        passive: true
      });
      this.eventTarget.addEventListener("mouseleave", this.#cancelRequestIfObsolete, {
        capture: true,
        passive: true
      });
      this.eventTarget.addEventListener("turbo:before-fetch-request", this.#tryToUsePrefetchedRequest, true);
      this.started = true;
    };
    #tryToPrefetchRequest = (event) => {
      if (getMetaContent("turbo-prefetch") === "false")
        return;
      const target = event.target;
      const isLink = target.matches && target.matches("a[href]:not([target^=_]):not([download])");
      if (isLink && this.#isPrefetchable(target)) {
        const link = target;
        const location2 = getLocationForLink(link);
        if (this.delegate.canPrefetchRequestToLocation(link, location2)) {
          this.#prefetchedLink = link;
          const fetchRequest = new FetchRequest(this, FetchMethod.get, location2, new URLSearchParams(), target);
          prefetchCache.setLater(location2.toString(), fetchRequest, this.#cacheTtl);
        }
      }
    };
    #cancelRequestIfObsolete = (event) => {
      if (event.target === this.#prefetchedLink)
        this.#cancelPrefetchRequest();
    };
    #cancelPrefetchRequest = () => {
      prefetchCache.clear();
      this.#prefetchedLink = null;
    };
    #tryToUsePrefetchedRequest = (event) => {
      if (event.target.tagName !== "FORM" && event.detail.fetchOptions.method === "get") {
        const cached = prefetchCache.get(event.detail.url.toString());
        if (cached) {
          event.detail.fetchRequest = cached;
        }
        prefetchCache.clear();
      }
    };
    prepareRequest(request) {
      const link = request.target;
      request.headers["X-Sec-Purpose"] = "prefetch";
      const turboFrame = link.closest("turbo-frame");
      const turboFrameTarget = link.getAttribute("data-turbo-frame") || turboFrame?.getAttribute("target") || turboFrame?.id;
      if (turboFrameTarget && turboFrameTarget !== "_top") {
        request.headers["Turbo-Frame"] = turboFrameTarget;
      }
    }
    requestSucceededWithResponse() {
    }
    requestStarted(fetchRequest) {
    }
    requestErrored(fetchRequest) {
    }
    requestFinished(fetchRequest) {
    }
    requestPreventedHandlingResponse(fetchRequest, fetchResponse) {
    }
    requestFailedWithResponse(fetchRequest, fetchResponse) {
    }
    get #cacheTtl() {
      return Number(getMetaContent("turbo-prefetch-cache-time")) || cacheTtl;
    }
    #isPrefetchable(link) {
      const href = link.getAttribute("href");
      if (!href)
        return false;
      if (unfetchableLink(link))
        return false;
      if (linkToTheSamePage(link))
        return false;
      if (linkOptsOut(link))
        return false;
      if (nonSafeLink(link))
        return false;
      if (eventPrevented(link))
        return false;
      return true;
    }
  };
  var unfetchableLink = (link) => {
    return link.origin !== document.location.origin || !["http:", "https:"].includes(link.protocol) || link.hasAttribute("target");
  };
  var linkToTheSamePage = (link) => {
    return link.pathname + link.search === document.location.pathname + document.location.search || link.href.startsWith("#");
  };
  var linkOptsOut = (link) => {
    if (link.getAttribute("data-turbo-prefetch") === "false")
      return true;
    if (link.getAttribute("data-turbo") === "false")
      return true;
    const turboPrefetchParent = findClosestRecursively(link, "[data-turbo-prefetch]");
    if (turboPrefetchParent && turboPrefetchParent.getAttribute("data-turbo-prefetch") === "false")
      return true;
    return false;
  };
  var nonSafeLink = (link) => {
    const turboMethod = link.getAttribute("data-turbo-method");
    if (turboMethod && turboMethod.toLowerCase() !== "get")
      return true;
    if (isUJS(link))
      return true;
    if (link.hasAttribute("data-turbo-confirm"))
      return true;
    if (link.hasAttribute("data-turbo-stream"))
      return true;
    return false;
  };
  var isUJS = (link) => {
    return link.hasAttribute("data-remote") || link.hasAttribute("data-behavior") || link.hasAttribute("data-confirm") || link.hasAttribute("data-method");
  };
  var eventPrevented = (link) => {
    const event = dispatch("turbo:before-prefetch", { target: link, cancelable: true });
    return event.defaultPrevented;
  };
  var Navigator = class {
    constructor(delegate) {
      this.delegate = delegate;
    }
    proposeVisit(location2, options = {}) {
      if (this.delegate.allowsVisitingLocationWithAction(location2, options.action)) {
        this.delegate.visitProposedToLocation(location2, options);
      }
    }
    startVisit(locatable, restorationIdentifier, options = {}) {
      this.stop();
      this.currentVisit = new Visit(this, expandURL(locatable), restorationIdentifier, {
        referrer: this.location,
        ...options
      });
      this.currentVisit.start();
    }
    submitForm(form, submitter) {
      this.stop();
      this.formSubmission = new FormSubmission(this, form, submitter, true);
      this.formSubmission.start();
    }
    stop() {
      if (this.formSubmission) {
        this.formSubmission.stop();
        delete this.formSubmission;
      }
      if (this.currentVisit) {
        this.currentVisit.cancel();
        delete this.currentVisit;
      }
    }
    get adapter() {
      return this.delegate.adapter;
    }
    get view() {
      return this.delegate.view;
    }
    get rootLocation() {
      return this.view.snapshot.rootLocation;
    }
    get history() {
      return this.delegate.history;
    }
    formSubmissionStarted(formSubmission) {
      if (typeof this.adapter.formSubmissionStarted === "function") {
        this.adapter.formSubmissionStarted(formSubmission);
      }
    }
    async formSubmissionSucceededWithResponse(formSubmission, fetchResponse) {
      if (formSubmission == this.formSubmission) {
        const responseHTML = await fetchResponse.responseHTML;
        if (responseHTML) {
          const shouldCacheSnapshot = formSubmission.isSafe;
          if (!shouldCacheSnapshot) {
            this.view.clearSnapshotCache();
          }
          const { statusCode, redirected } = fetchResponse;
          const action = this.#getActionForFormSubmission(formSubmission, fetchResponse);
          const visitOptions = {
            action,
            shouldCacheSnapshot,
            response: { statusCode, responseHTML, redirected }
          };
          this.proposeVisit(fetchResponse.location, visitOptions);
        }
      }
    }
    async formSubmissionFailedWithResponse(formSubmission, fetchResponse) {
      const responseHTML = await fetchResponse.responseHTML;
      if (responseHTML) {
        const snapshot = PageSnapshot.fromHTMLString(responseHTML);
        if (fetchResponse.serverError) {
          await this.view.renderError(snapshot, this.currentVisit);
        } else {
          await this.view.renderPage(snapshot, false, true, this.currentVisit);
        }
        if (!snapshot.shouldPreserveScrollPosition) {
          this.view.scrollToTop();
        }
        this.view.clearSnapshotCache();
      }
    }
    formSubmissionErrored(formSubmission, error3) {
      console.error(error3);
    }
    formSubmissionFinished(formSubmission) {
      if (typeof this.adapter.formSubmissionFinished === "function") {
        this.adapter.formSubmissionFinished(formSubmission);
      }
    }
    visitStarted(visit2) {
      this.delegate.visitStarted(visit2);
    }
    visitCompleted(visit2) {
      this.delegate.visitCompleted(visit2);
    }
    locationWithActionIsSamePage(location2, action) {
      const anchor = getAnchor(location2);
      const currentAnchor = getAnchor(this.view.lastRenderedLocation);
      const isRestorationToTop = action === "restore" && typeof anchor === "undefined";
      return action !== "replace" && getRequestURL(location2) === getRequestURL(this.view.lastRenderedLocation) && (isRestorationToTop || anchor != null && anchor !== currentAnchor);
    }
    visitScrolledToSamePageLocation(oldURL, newURL) {
      this.delegate.visitScrolledToSamePageLocation(oldURL, newURL);
    }
    get location() {
      return this.history.location;
    }
    get restorationIdentifier() {
      return this.history.restorationIdentifier;
    }
    #getActionForFormSubmission(formSubmission, fetchResponse) {
      const { submitter, formElement } = formSubmission;
      return getVisitAction(submitter, formElement) || this.#getDefaultAction(fetchResponse);
    }
    #getDefaultAction(fetchResponse) {
      const sameLocationRedirect = fetchResponse.redirected && fetchResponse.location.href === this.location?.href;
      return sameLocationRedirect ? "replace" : "advance";
    }
  };
  var PageStage = {
    initial: 0,
    loading: 1,
    interactive: 2,
    complete: 3
  };
  var PageObserver = class {
    stage = PageStage.initial;
    started = false;
    constructor(delegate) {
      this.delegate = delegate;
    }
    start() {
      if (!this.started) {
        if (this.stage == PageStage.initial) {
          this.stage = PageStage.loading;
        }
        document.addEventListener("readystatechange", this.interpretReadyState, false);
        addEventListener("pagehide", this.pageWillUnload, false);
        this.started = true;
      }
    }
    stop() {
      if (this.started) {
        document.removeEventListener("readystatechange", this.interpretReadyState, false);
        removeEventListener("pagehide", this.pageWillUnload, false);
        this.started = false;
      }
    }
    interpretReadyState = () => {
      const { readyState } = this;
      if (readyState == "interactive") {
        this.pageIsInteractive();
      } else if (readyState == "complete") {
        this.pageIsComplete();
      }
    };
    pageIsInteractive() {
      if (this.stage == PageStage.loading) {
        this.stage = PageStage.interactive;
        this.delegate.pageBecameInteractive();
      }
    }
    pageIsComplete() {
      this.pageIsInteractive();
      if (this.stage == PageStage.interactive) {
        this.stage = PageStage.complete;
        this.delegate.pageLoaded();
      }
    }
    pageWillUnload = () => {
      this.delegate.pageWillUnload();
    };
    get readyState() {
      return document.readyState;
    }
  };
  var ScrollObserver = class {
    started = false;
    constructor(delegate) {
      this.delegate = delegate;
    }
    start() {
      if (!this.started) {
        addEventListener("scroll", this.onScroll, false);
        this.onScroll();
        this.started = true;
      }
    }
    stop() {
      if (this.started) {
        removeEventListener("scroll", this.onScroll, false);
        this.started = false;
      }
    }
    onScroll = () => {
      this.updatePosition({ x: window.pageXOffset, y: window.pageYOffset });
    };
    updatePosition(position) {
      this.delegate.scrollPositionChanged(position);
    }
  };
  var StreamMessageRenderer = class {
    render({ fragment }) {
      Bardo.preservingPermanentElements(this, getPermanentElementMapForFragment(fragment), () => {
        withAutofocusFromFragment(fragment, () => {
          withPreservedFocus(() => {
            document.documentElement.appendChild(fragment);
          });
        });
      });
    }
    enteringBardo(currentPermanentElement, newPermanentElement) {
      newPermanentElement.replaceWith(currentPermanentElement.cloneNode(true));
    }
    leavingBardo() {
    }
  };
  function getPermanentElementMapForFragment(fragment) {
    const permanentElementsInDocument = queryPermanentElementsAll(document.documentElement);
    const permanentElementMap = {};
    for (const permanentElementInDocument of permanentElementsInDocument) {
      const { id: id2 } = permanentElementInDocument;
      for (const streamElement of fragment.querySelectorAll("turbo-stream")) {
        const elementInStream = getPermanentElementById(streamElement.templateElement.content, id2);
        if (elementInStream) {
          permanentElementMap[id2] = [permanentElementInDocument, elementInStream];
        }
      }
    }
    return permanentElementMap;
  }
  async function withAutofocusFromFragment(fragment, callback2) {
    const generatedID = `turbo-stream-autofocus-${uuid()}`;
    const turboStreams = fragment.querySelectorAll("turbo-stream");
    const elementWithAutofocus = firstAutofocusableElementInStreams(turboStreams);
    let willAutofocusId = null;
    if (elementWithAutofocus) {
      if (elementWithAutofocus.id) {
        willAutofocusId = elementWithAutofocus.id;
      } else {
        willAutofocusId = generatedID;
      }
      elementWithAutofocus.id = willAutofocusId;
    }
    callback2();
    await nextRepaint();
    const hasNoActiveElement = document.activeElement == null || document.activeElement == document.body;
    if (hasNoActiveElement && willAutofocusId) {
      const elementToAutofocus = document.getElementById(willAutofocusId);
      if (elementIsFocusable(elementToAutofocus)) {
        elementToAutofocus.focus();
      }
      if (elementToAutofocus && elementToAutofocus.id == generatedID) {
        elementToAutofocus.removeAttribute("id");
      }
    }
  }
  async function withPreservedFocus(callback2) {
    const [activeElementBeforeRender, activeElementAfterRender] = await around(callback2, () => document.activeElement);
    const restoreFocusTo = activeElementBeforeRender && activeElementBeforeRender.id;
    if (restoreFocusTo) {
      const elementToFocus = document.getElementById(restoreFocusTo);
      if (elementIsFocusable(elementToFocus) && elementToFocus != activeElementAfterRender) {
        elementToFocus.focus();
      }
    }
  }
  function firstAutofocusableElementInStreams(nodeListOfStreamElements) {
    for (const streamElement of nodeListOfStreamElements) {
      const elementWithAutofocus = queryAutofocusableElement(streamElement.templateElement.content);
      if (elementWithAutofocus)
        return elementWithAutofocus;
    }
    return null;
  }
  var StreamObserver = class {
    sources = /* @__PURE__ */ new Set();
    #started = false;
    constructor(delegate) {
      this.delegate = delegate;
    }
    start() {
      if (!this.#started) {
        this.#started = true;
        addEventListener("turbo:before-fetch-response", this.inspectFetchResponse, false);
      }
    }
    stop() {
      if (this.#started) {
        this.#started = false;
        removeEventListener("turbo:before-fetch-response", this.inspectFetchResponse, false);
      }
    }
    connectStreamSource(source) {
      if (!this.streamSourceIsConnected(source)) {
        this.sources.add(source);
        source.addEventListener("message", this.receiveMessageEvent, false);
      }
    }
    disconnectStreamSource(source) {
      if (this.streamSourceIsConnected(source)) {
        this.sources.delete(source);
        source.removeEventListener("message", this.receiveMessageEvent, false);
      }
    }
    streamSourceIsConnected(source) {
      return this.sources.has(source);
    }
    inspectFetchResponse = (event) => {
      const response = fetchResponseFromEvent(event);
      if (response && fetchResponseIsStream(response)) {
        event.preventDefault();
        this.receiveMessageResponse(response);
      }
    };
    receiveMessageEvent = (event) => {
      if (this.#started && typeof event.data == "string") {
        this.receiveMessageHTML(event.data);
      }
    };
    async receiveMessageResponse(response) {
      const html = await response.responseHTML;
      if (html) {
        this.receiveMessageHTML(html);
      }
    }
    receiveMessageHTML(html) {
      this.delegate.receivedMessageFromStream(StreamMessage.wrap(html));
    }
  };
  function fetchResponseFromEvent(event) {
    const fetchResponse = event.detail?.fetchResponse;
    if (fetchResponse instanceof FetchResponse) {
      return fetchResponse;
    }
  }
  function fetchResponseIsStream(response) {
    const contentType = response.contentType ?? "";
    return contentType.startsWith(StreamMessage.contentType);
  }
  var ErrorRenderer = class extends Renderer {
    static renderElement(currentElement, newElement) {
      const { documentElement, body } = document;
      documentElement.replaceChild(newElement, body);
    }
    async render() {
      this.replaceHeadAndBody();
      this.activateScriptElements();
    }
    replaceHeadAndBody() {
      const { documentElement, head } = document;
      documentElement.replaceChild(this.newHead, head);
      this.renderElement(this.currentElement, this.newElement);
    }
    activateScriptElements() {
      for (const replaceableElement of this.scriptElements) {
        const parentNode = replaceableElement.parentNode;
        if (parentNode) {
          const element = activateScriptElement(replaceableElement);
          parentNode.replaceChild(element, replaceableElement);
        }
      }
    }
    get newHead() {
      return this.newSnapshot.headSnapshot.element;
    }
    get scriptElements() {
      return document.documentElement.querySelectorAll("script");
    }
  };
  var Idiomorph = function() {
    let EMPTY_SET = /* @__PURE__ */ new Set();
    let defaults2 = {
      morphStyle: "outerHTML",
      callbacks: {
        beforeNodeAdded: noOp,
        afterNodeAdded: noOp,
        beforeNodeMorphed: noOp,
        afterNodeMorphed: noOp,
        beforeNodeRemoved: noOp,
        afterNodeRemoved: noOp,
        beforeAttributeUpdated: noOp
      },
      head: {
        style: "merge",
        shouldPreserve: function(elt) {
          return elt.getAttribute("im-preserve") === "true";
        },
        shouldReAppend: function(elt) {
          return elt.getAttribute("im-re-append") === "true";
        },
        shouldRemove: noOp,
        afterHeadMorphed: noOp
      }
    };
    function morph(oldNode, newContent, config = {}) {
      if (oldNode instanceof Document) {
        oldNode = oldNode.documentElement;
      }
      if (typeof newContent === "string") {
        newContent = parseContent(newContent);
      }
      let normalizedContent = normalizeContent(newContent);
      let ctx = createMorphContext(oldNode, normalizedContent, config);
      return morphNormalizedContent(oldNode, normalizedContent, ctx);
    }
    function morphNormalizedContent(oldNode, normalizedNewContent, ctx) {
      if (ctx.head.block) {
        let oldHead = oldNode.querySelector("head");
        let newHead = normalizedNewContent.querySelector("head");
        if (oldHead && newHead) {
          let promises = handleHeadElement(newHead, oldHead, ctx);
          Promise.all(promises).then(function() {
            morphNormalizedContent(oldNode, normalizedNewContent, Object.assign(ctx, {
              head: {
                block: false,
                ignore: true
              }
            }));
          });
          return;
        }
      }
      if (ctx.morphStyle === "innerHTML") {
        morphChildren(normalizedNewContent, oldNode, ctx);
        return oldNode.children;
      } else if (ctx.morphStyle === "outerHTML" || ctx.morphStyle == null) {
        let bestMatch = findBestNodeMatch(normalizedNewContent, oldNode, ctx);
        let previousSibling = bestMatch?.previousSibling;
        let nextSibling = bestMatch?.nextSibling;
        let morphedNode = morphOldNodeTo(oldNode, bestMatch, ctx);
        if (bestMatch) {
          return insertSiblings(previousSibling, morphedNode, nextSibling);
        } else {
          return [];
        }
      } else {
        throw "Do not understand how to morph style " + ctx.morphStyle;
      }
    }
    function ignoreValueOfActiveElement(possibleActiveElement, ctx) {
      return ctx.ignoreActiveValue && possibleActiveElement === document.activeElement && possibleActiveElement !== document.body;
    }
    function morphOldNodeTo(oldNode, newContent, ctx) {
      if (ctx.ignoreActive && oldNode === document.activeElement)
        ;
      else if (newContent == null) {
        if (ctx.callbacks.beforeNodeRemoved(oldNode) === false)
          return oldNode;
        oldNode.remove();
        ctx.callbacks.afterNodeRemoved(oldNode);
        return null;
      } else if (!isSoftMatch(oldNode, newContent)) {
        if (ctx.callbacks.beforeNodeRemoved(oldNode) === false)
          return oldNode;
        if (ctx.callbacks.beforeNodeAdded(newContent) === false)
          return oldNode;
        oldNode.parentElement.replaceChild(newContent, oldNode);
        ctx.callbacks.afterNodeAdded(newContent);
        ctx.callbacks.afterNodeRemoved(oldNode);
        return newContent;
      } else {
        if (ctx.callbacks.beforeNodeMorphed(oldNode, newContent) === false)
          return oldNode;
        if (oldNode instanceof HTMLHeadElement && ctx.head.ignore)
          ;
        else if (oldNode instanceof HTMLHeadElement && ctx.head.style !== "morph") {
          handleHeadElement(newContent, oldNode, ctx);
        } else {
          syncNodeFrom(newContent, oldNode, ctx);
          if (!ignoreValueOfActiveElement(oldNode, ctx)) {
            morphChildren(newContent, oldNode, ctx);
          }
        }
        ctx.callbacks.afterNodeMorphed(oldNode, newContent);
        return oldNode;
      }
    }
    function morphChildren(newParent, oldParent, ctx) {
      let nextNewChild = newParent.firstChild;
      let insertionPoint = oldParent.firstChild;
      let newChild;
      while (nextNewChild) {
        newChild = nextNewChild;
        nextNewChild = newChild.nextSibling;
        if (insertionPoint == null) {
          if (ctx.callbacks.beforeNodeAdded(newChild) === false)
            return;
          oldParent.appendChild(newChild);
          ctx.callbacks.afterNodeAdded(newChild);
          removeIdsFromConsideration(ctx, newChild);
          continue;
        }
        if (isIdSetMatch(newChild, insertionPoint, ctx)) {
          morphOldNodeTo(insertionPoint, newChild, ctx);
          insertionPoint = insertionPoint.nextSibling;
          removeIdsFromConsideration(ctx, newChild);
          continue;
        }
        let idSetMatch = findIdSetMatch(newParent, oldParent, newChild, insertionPoint, ctx);
        if (idSetMatch) {
          insertionPoint = removeNodesBetween(insertionPoint, idSetMatch, ctx);
          morphOldNodeTo(idSetMatch, newChild, ctx);
          removeIdsFromConsideration(ctx, newChild);
          continue;
        }
        let softMatch = findSoftMatch(newParent, oldParent, newChild, insertionPoint, ctx);
        if (softMatch) {
          insertionPoint = removeNodesBetween(insertionPoint, softMatch, ctx);
          morphOldNodeTo(softMatch, newChild, ctx);
          removeIdsFromConsideration(ctx, newChild);
          continue;
        }
        if (ctx.callbacks.beforeNodeAdded(newChild) === false)
          return;
        oldParent.insertBefore(newChild, insertionPoint);
        ctx.callbacks.afterNodeAdded(newChild);
        removeIdsFromConsideration(ctx, newChild);
      }
      while (insertionPoint !== null) {
        let tempNode = insertionPoint;
        insertionPoint = insertionPoint.nextSibling;
        removeNode(tempNode, ctx);
      }
    }
    function ignoreAttribute(attr, to, updateType, ctx) {
      if (attr === "value" && ctx.ignoreActiveValue && to === document.activeElement) {
        return true;
      }
      return ctx.callbacks.beforeAttributeUpdated(attr, to, updateType) === false;
    }
    function syncNodeFrom(from, to, ctx) {
      let type = from.nodeType;
      if (type === 1) {
        const fromAttributes = from.attributes;
        const toAttributes = to.attributes;
        for (const fromAttribute of fromAttributes) {
          if (ignoreAttribute(fromAttribute.name, to, "update", ctx)) {
            continue;
          }
          if (to.getAttribute(fromAttribute.name) !== fromAttribute.value) {
            to.setAttribute(fromAttribute.name, fromAttribute.value);
          }
        }
        for (let i2 = toAttributes.length - 1; 0 <= i2; i2--) {
          const toAttribute = toAttributes[i2];
          if (ignoreAttribute(toAttribute.name, to, "remove", ctx)) {
            continue;
          }
          if (!from.hasAttribute(toAttribute.name)) {
            to.removeAttribute(toAttribute.name);
          }
        }
      }
      if (type === 8 || type === 3) {
        if (to.nodeValue !== from.nodeValue) {
          to.nodeValue = from.nodeValue;
        }
      }
      if (!ignoreValueOfActiveElement(to, ctx)) {
        syncInputValue(from, to, ctx);
      }
    }
    function syncBooleanAttribute(from, to, attributeName, ctx) {
      if (from[attributeName] !== to[attributeName]) {
        let ignoreUpdate = ignoreAttribute(attributeName, to, "update", ctx);
        if (!ignoreUpdate) {
          to[attributeName] = from[attributeName];
        }
        if (from[attributeName]) {
          if (!ignoreUpdate) {
            to.setAttribute(attributeName, from[attributeName]);
          }
        } else {
          if (!ignoreAttribute(attributeName, to, "remove", ctx)) {
            to.removeAttribute(attributeName);
          }
        }
      }
    }
    function syncInputValue(from, to, ctx) {
      if (from instanceof HTMLInputElement && to instanceof HTMLInputElement && from.type !== "file") {
        let fromValue = from.value;
        let toValue = to.value;
        syncBooleanAttribute(from, to, "checked", ctx);
        syncBooleanAttribute(from, to, "disabled", ctx);
        if (!from.hasAttribute("value")) {
          if (!ignoreAttribute("value", to, "remove", ctx)) {
            to.value = "";
            to.removeAttribute("value");
          }
        } else if (fromValue !== toValue) {
          if (!ignoreAttribute("value", to, "update", ctx)) {
            to.setAttribute("value", fromValue);
            to.value = fromValue;
          }
        }
      } else if (from instanceof HTMLOptionElement) {
        syncBooleanAttribute(from, to, "selected", ctx);
      } else if (from instanceof HTMLTextAreaElement && to instanceof HTMLTextAreaElement) {
        let fromValue = from.value;
        let toValue = to.value;
        if (ignoreAttribute("value", to, "update", ctx)) {
          return;
        }
        if (fromValue !== toValue) {
          to.value = fromValue;
        }
        if (to.firstChild && to.firstChild.nodeValue !== fromValue) {
          to.firstChild.nodeValue = fromValue;
        }
      }
    }
    function handleHeadElement(newHeadTag, currentHead, ctx) {
      let added = [];
      let removed = [];
      let preserved = [];
      let nodesToAppend = [];
      let headMergeStyle = ctx.head.style;
      let srcToNewHeadNodes = /* @__PURE__ */ new Map();
      for (const newHeadChild of newHeadTag.children) {
        srcToNewHeadNodes.set(newHeadChild.outerHTML, newHeadChild);
      }
      for (const currentHeadElt of currentHead.children) {
        let inNewContent = srcToNewHeadNodes.has(currentHeadElt.outerHTML);
        let isReAppended = ctx.head.shouldReAppend(currentHeadElt);
        let isPreserved = ctx.head.shouldPreserve(currentHeadElt);
        if (inNewContent || isPreserved) {
          if (isReAppended) {
            removed.push(currentHeadElt);
          } else {
            srcToNewHeadNodes.delete(currentHeadElt.outerHTML);
            preserved.push(currentHeadElt);
          }
        } else {
          if (headMergeStyle === "append") {
            if (isReAppended) {
              removed.push(currentHeadElt);
              nodesToAppend.push(currentHeadElt);
            }
          } else {
            if (ctx.head.shouldRemove(currentHeadElt) !== false) {
              removed.push(currentHeadElt);
            }
          }
        }
      }
      nodesToAppend.push(...srcToNewHeadNodes.values());
      let promises = [];
      for (const newNode of nodesToAppend) {
        let newElt = document.createRange().createContextualFragment(newNode.outerHTML).firstChild;
        if (ctx.callbacks.beforeNodeAdded(newElt) !== false) {
          if (newElt.href || newElt.src) {
            let resolve2 = null;
            let promise = new Promise(function(_resolve2) {
              resolve2 = _resolve2;
            });
            newElt.addEventListener("load", function() {
              resolve2();
            });
            promises.push(promise);
          }
          currentHead.appendChild(newElt);
          ctx.callbacks.afterNodeAdded(newElt);
          added.push(newElt);
        }
      }
      for (const removedElement of removed) {
        if (ctx.callbacks.beforeNodeRemoved(removedElement) !== false) {
          currentHead.removeChild(removedElement);
          ctx.callbacks.afterNodeRemoved(removedElement);
        }
      }
      ctx.head.afterHeadMorphed(currentHead, { added, kept: preserved, removed });
      return promises;
    }
    function noOp() {
    }
    function mergeDefaults(config) {
      let finalConfig = {};
      Object.assign(finalConfig, defaults2);
      Object.assign(finalConfig, config);
      finalConfig.callbacks = {};
      Object.assign(finalConfig.callbacks, defaults2.callbacks);
      Object.assign(finalConfig.callbacks, config.callbacks);
      finalConfig.head = {};
      Object.assign(finalConfig.head, defaults2.head);
      Object.assign(finalConfig.head, config.head);
      return finalConfig;
    }
    function createMorphContext(oldNode, newContent, config) {
      config = mergeDefaults(config);
      return {
        target: oldNode,
        newContent,
        config,
        morphStyle: config.morphStyle,
        ignoreActive: config.ignoreActive,
        ignoreActiveValue: config.ignoreActiveValue,
        idMap: createIdMap(oldNode, newContent),
        deadIds: /* @__PURE__ */ new Set(),
        callbacks: config.callbacks,
        head: config.head
      };
    }
    function isIdSetMatch(node1, node2, ctx) {
      if (node1 == null || node2 == null) {
        return false;
      }
      if (node1.nodeType === node2.nodeType && node1.tagName === node2.tagName) {
        if (node1.id !== "" && node1.id === node2.id) {
          return true;
        } else {
          return getIdIntersectionCount(ctx, node1, node2) > 0;
        }
      }
      return false;
    }
    function isSoftMatch(node1, node2) {
      if (node1 == null || node2 == null) {
        return false;
      }
      return node1.nodeType === node2.nodeType && node1.tagName === node2.tagName;
    }
    function removeNodesBetween(startInclusive, endExclusive, ctx) {
      while (startInclusive !== endExclusive) {
        let tempNode = startInclusive;
        startInclusive = startInclusive.nextSibling;
        removeNode(tempNode, ctx);
      }
      removeIdsFromConsideration(ctx, endExclusive);
      return endExclusive.nextSibling;
    }
    function findIdSetMatch(newContent, oldParent, newChild, insertionPoint, ctx) {
      let newChildPotentialIdCount = getIdIntersectionCount(ctx, newChild, oldParent);
      let potentialMatch = null;
      if (newChildPotentialIdCount > 0) {
        let potentialMatch2 = insertionPoint;
        let otherMatchCount = 0;
        while (potentialMatch2 != null) {
          if (isIdSetMatch(newChild, potentialMatch2, ctx)) {
            return potentialMatch2;
          }
          otherMatchCount += getIdIntersectionCount(ctx, potentialMatch2, newContent);
          if (otherMatchCount > newChildPotentialIdCount) {
            return null;
          }
          potentialMatch2 = potentialMatch2.nextSibling;
        }
      }
      return potentialMatch;
    }
    function findSoftMatch(newContent, oldParent, newChild, insertionPoint, ctx) {
      let potentialSoftMatch = insertionPoint;
      let nextSibling = newChild.nextSibling;
      let siblingSoftMatchCount = 0;
      while (potentialSoftMatch != null) {
        if (getIdIntersectionCount(ctx, potentialSoftMatch, newContent) > 0) {
          return null;
        }
        if (isSoftMatch(newChild, potentialSoftMatch)) {
          return potentialSoftMatch;
        }
        if (isSoftMatch(nextSibling, potentialSoftMatch)) {
          siblingSoftMatchCount++;
          nextSibling = nextSibling.nextSibling;
          if (siblingSoftMatchCount >= 2) {
            return null;
          }
        }
        potentialSoftMatch = potentialSoftMatch.nextSibling;
      }
      return potentialSoftMatch;
    }
    function parseContent(newContent) {
      let parser = new DOMParser();
      let contentWithSvgsRemoved = newContent.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim, "");
      if (contentWithSvgsRemoved.match(/<\/html>/) || contentWithSvgsRemoved.match(/<\/head>/) || contentWithSvgsRemoved.match(/<\/body>/)) {
        let content = parser.parseFromString(newContent, "text/html");
        if (contentWithSvgsRemoved.match(/<\/html>/)) {
          content.generatedByIdiomorph = true;
          return content;
        } else {
          let htmlElement = content.firstChild;
          if (htmlElement) {
            htmlElement.generatedByIdiomorph = true;
            return htmlElement;
          } else {
            return null;
          }
        }
      } else {
        let responseDoc = parser.parseFromString("<body><template>" + newContent + "</template></body>", "text/html");
        let content = responseDoc.body.querySelector("template").content;
        content.generatedByIdiomorph = true;
        return content;
      }
    }
    function normalizeContent(newContent) {
      if (newContent == null) {
        const dummyParent = document.createElement("div");
        return dummyParent;
      } else if (newContent.generatedByIdiomorph) {
        return newContent;
      } else if (newContent instanceof Node) {
        const dummyParent = document.createElement("div");
        dummyParent.append(newContent);
        return dummyParent;
      } else {
        const dummyParent = document.createElement("div");
        for (const elt of [...newContent]) {
          dummyParent.append(elt);
        }
        return dummyParent;
      }
    }
    function insertSiblings(previousSibling, morphedNode, nextSibling) {
      let stack = [];
      let added = [];
      while (previousSibling != null) {
        stack.push(previousSibling);
        previousSibling = previousSibling.previousSibling;
      }
      while (stack.length > 0) {
        let node = stack.pop();
        added.push(node);
        morphedNode.parentElement.insertBefore(node, morphedNode);
      }
      added.push(morphedNode);
      while (nextSibling != null) {
        stack.push(nextSibling);
        added.push(nextSibling);
        nextSibling = nextSibling.nextSibling;
      }
      while (stack.length > 0) {
        morphedNode.parentElement.insertBefore(stack.pop(), morphedNode.nextSibling);
      }
      return added;
    }
    function findBestNodeMatch(newContent, oldNode, ctx) {
      let currentElement;
      currentElement = newContent.firstChild;
      let bestElement = currentElement;
      let score = 0;
      while (currentElement) {
        let newScore = scoreElement(currentElement, oldNode, ctx);
        if (newScore > score) {
          bestElement = currentElement;
          score = newScore;
        }
        currentElement = currentElement.nextSibling;
      }
      return bestElement;
    }
    function scoreElement(node1, node2, ctx) {
      if (isSoftMatch(node1, node2)) {
        return 0.5 + getIdIntersectionCount(ctx, node1, node2);
      }
      return 0;
    }
    function removeNode(tempNode, ctx) {
      removeIdsFromConsideration(ctx, tempNode);
      if (ctx.callbacks.beforeNodeRemoved(tempNode) === false)
        return;
      tempNode.remove();
      ctx.callbacks.afterNodeRemoved(tempNode);
    }
    function isIdInConsideration(ctx, id2) {
      return !ctx.deadIds.has(id2);
    }
    function idIsWithinNode(ctx, id2, targetNode) {
      let idSet = ctx.idMap.get(targetNode) || EMPTY_SET;
      return idSet.has(id2);
    }
    function removeIdsFromConsideration(ctx, node) {
      let idSet = ctx.idMap.get(node) || EMPTY_SET;
      for (const id2 of idSet) {
        ctx.deadIds.add(id2);
      }
    }
    function getIdIntersectionCount(ctx, node1, node2) {
      let sourceSet = ctx.idMap.get(node1) || EMPTY_SET;
      let matchCount = 0;
      for (const id2 of sourceSet) {
        if (isIdInConsideration(ctx, id2) && idIsWithinNode(ctx, id2, node2)) {
          ++matchCount;
        }
      }
      return matchCount;
    }
    function populateIdMapForNode(node, idMap) {
      let nodeParent = node.parentElement;
      let idElements = node.querySelectorAll("[id]");
      for (const elt of idElements) {
        let current = elt;
        while (current !== nodeParent && current != null) {
          let idSet = idMap.get(current);
          if (idSet == null) {
            idSet = /* @__PURE__ */ new Set();
            idMap.set(current, idSet);
          }
          idSet.add(elt.id);
          current = current.parentElement;
        }
      }
    }
    function createIdMap(oldContent, newContent) {
      let idMap = /* @__PURE__ */ new Map();
      populateIdMapForNode(oldContent, idMap);
      populateIdMapForNode(newContent, idMap);
      return idMap;
    }
    return {
      morph,
      defaults: defaults2
    };
  }();
  var PageRenderer = class extends Renderer {
    static renderElement(currentElement, newElement) {
      if (document.body && newElement instanceof HTMLBodyElement) {
        document.body.replaceWith(newElement);
      } else {
        document.documentElement.appendChild(newElement);
      }
    }
    get shouldRender() {
      return this.newSnapshot.isVisitable && this.trackedElementsAreIdentical;
    }
    get reloadReason() {
      if (!this.newSnapshot.isVisitable) {
        return {
          reason: "turbo_visit_control_is_reload"
        };
      }
      if (!this.trackedElementsAreIdentical) {
        return {
          reason: "tracked_element_mismatch"
        };
      }
    }
    async prepareToRender() {
      this.#setLanguage();
      await this.mergeHead();
    }
    async render() {
      if (this.willRender) {
        await this.replaceBody();
      }
    }
    finishRendering() {
      super.finishRendering();
      if (!this.isPreview) {
        this.focusFirstAutofocusableElement();
      }
    }
    get currentHeadSnapshot() {
      return this.currentSnapshot.headSnapshot;
    }
    get newHeadSnapshot() {
      return this.newSnapshot.headSnapshot;
    }
    get newElement() {
      return this.newSnapshot.element;
    }
    #setLanguage() {
      const { documentElement } = this.currentSnapshot;
      const { lang } = this.newSnapshot;
      if (lang) {
        documentElement.setAttribute("lang", lang);
      } else {
        documentElement.removeAttribute("lang");
      }
    }
    async mergeHead() {
      const mergedHeadElements = this.mergeProvisionalElements();
      const newStylesheetElements = this.copyNewHeadStylesheetElements();
      this.copyNewHeadScriptElements();
      await mergedHeadElements;
      await newStylesheetElements;
      if (this.willRender) {
        this.removeUnusedDynamicStylesheetElements();
      }
    }
    async replaceBody() {
      await this.preservingPermanentElements(async () => {
        this.activateNewBody();
        await this.assignNewBody();
      });
    }
    get trackedElementsAreIdentical() {
      return this.currentHeadSnapshot.trackedElementSignature == this.newHeadSnapshot.trackedElementSignature;
    }
    async copyNewHeadStylesheetElements() {
      const loadingElements = [];
      for (const element of this.newHeadStylesheetElements) {
        loadingElements.push(waitForLoad(element));
        document.head.appendChild(element);
      }
      await Promise.all(loadingElements);
    }
    copyNewHeadScriptElements() {
      for (const element of this.newHeadScriptElements) {
        document.head.appendChild(activateScriptElement(element));
      }
    }
    removeUnusedDynamicStylesheetElements() {
      for (const element of this.unusedDynamicStylesheetElements) {
        document.head.removeChild(element);
      }
    }
    async mergeProvisionalElements() {
      const newHeadElements = [...this.newHeadProvisionalElements];
      for (const element of this.currentHeadProvisionalElements) {
        if (!this.isCurrentElementInElementList(element, newHeadElements)) {
          document.head.removeChild(element);
        }
      }
      for (const element of newHeadElements) {
        document.head.appendChild(element);
      }
    }
    isCurrentElementInElementList(element, elementList) {
      for (const [index, newElement] of elementList.entries()) {
        if (element.tagName == "TITLE") {
          if (newElement.tagName != "TITLE") {
            continue;
          }
          if (element.innerHTML == newElement.innerHTML) {
            elementList.splice(index, 1);
            return true;
          }
        }
        if (newElement.isEqualNode(element)) {
          elementList.splice(index, 1);
          return true;
        }
      }
      return false;
    }
    removeCurrentHeadProvisionalElements() {
      for (const element of this.currentHeadProvisionalElements) {
        document.head.removeChild(element);
      }
    }
    copyNewHeadProvisionalElements() {
      for (const element of this.newHeadProvisionalElements) {
        document.head.appendChild(element);
      }
    }
    activateNewBody() {
      document.adoptNode(this.newElement);
      this.activateNewBodyScriptElements();
    }
    activateNewBodyScriptElements() {
      for (const inertScriptElement of this.newBodyScriptElements) {
        const activatedScriptElement = activateScriptElement(inertScriptElement);
        inertScriptElement.replaceWith(activatedScriptElement);
      }
    }
    async assignNewBody() {
      await this.renderElement(this.currentElement, this.newElement);
    }
    get unusedDynamicStylesheetElements() {
      return this.oldHeadStylesheetElements.filter((element) => {
        return element.getAttribute("data-turbo-track") === "dynamic";
      });
    }
    get oldHeadStylesheetElements() {
      return this.currentHeadSnapshot.getStylesheetElementsNotInSnapshot(this.newHeadSnapshot);
    }
    get newHeadStylesheetElements() {
      return this.newHeadSnapshot.getStylesheetElementsNotInSnapshot(this.currentHeadSnapshot);
    }
    get newHeadScriptElements() {
      return this.newHeadSnapshot.getScriptElementsNotInSnapshot(this.currentHeadSnapshot);
    }
    get currentHeadProvisionalElements() {
      return this.currentHeadSnapshot.provisionalElements;
    }
    get newHeadProvisionalElements() {
      return this.newHeadSnapshot.provisionalElements;
    }
    get newBodyScriptElements() {
      return this.newElement.querySelectorAll("script");
    }
  };
  var MorphRenderer = class extends PageRenderer {
    async render() {
      if (this.willRender)
        await this.#morphBody();
    }
    get renderMethod() {
      return "morph";
    }
    async #morphBody() {
      this.#morphElements(this.currentElement, this.newElement);
      this.#reloadRemoteFrames();
      dispatch("turbo:morph", {
        detail: {
          currentElement: this.currentElement,
          newElement: this.newElement
        }
      });
    }
    #morphElements(currentElement, newElement, morphStyle = "outerHTML") {
      this.isMorphingTurboFrame = this.#isFrameReloadedWithMorph(currentElement);
      Idiomorph.morph(currentElement, newElement, {
        morphStyle,
        callbacks: {
          beforeNodeAdded: this.#shouldAddElement,
          beforeNodeMorphed: this.#shouldMorphElement,
          beforeAttributeUpdated: this.#shouldUpdateAttribute,
          beforeNodeRemoved: this.#shouldRemoveElement,
          afterNodeMorphed: this.#didMorphElement
        }
      });
    }
    #shouldAddElement = (node) => {
      return !(node.id && node.hasAttribute("data-turbo-permanent") && document.getElementById(node.id));
    };
    #shouldMorphElement = (oldNode, newNode) => {
      if (oldNode instanceof HTMLElement) {
        if (!oldNode.hasAttribute("data-turbo-permanent") && (this.isMorphingTurboFrame || !this.#isFrameReloadedWithMorph(oldNode))) {
          const event = dispatch("turbo:before-morph-element", {
            cancelable: true,
            target: oldNode,
            detail: {
              newElement: newNode
            }
          });
          return !event.defaultPrevented;
        } else {
          return false;
        }
      }
    };
    #shouldUpdateAttribute = (attributeName, target, mutationType) => {
      const event = dispatch("turbo:before-morph-attribute", { cancelable: true, target, detail: { attributeName, mutationType } });
      return !event.defaultPrevented;
    };
    #didMorphElement = (oldNode, newNode) => {
      if (newNode instanceof HTMLElement) {
        dispatch("turbo:morph-element", {
          target: oldNode,
          detail: {
            newElement: newNode
          }
        });
      }
    };
    #shouldRemoveElement = (node) => {
      return this.#shouldMorphElement(node);
    };
    #reloadRemoteFrames() {
      this.#remoteFrames().forEach((frame) => {
        if (this.#isFrameReloadedWithMorph(frame)) {
          this.#renderFrameWithMorph(frame);
          frame.reload();
        }
      });
    }
    #renderFrameWithMorph(frame) {
      frame.addEventListener("turbo:before-frame-render", (event) => {
        event.detail.render = this.#morphFrameUpdate;
      }, { once: true });
    }
    #morphFrameUpdate = (currentElement, newElement) => {
      dispatch("turbo:before-frame-morph", {
        target: currentElement,
        detail: { currentElement, newElement }
      });
      this.#morphElements(currentElement, newElement.children, "innerHTML");
    };
    #isFrameReloadedWithMorph(element) {
      return element.src && element.refresh === "morph";
    }
    #remoteFrames() {
      return Array.from(document.querySelectorAll("turbo-frame[src]")).filter((frame) => {
        return !frame.closest("[data-turbo-permanent]");
      });
    }
  };
  var SnapshotCache = class {
    keys = [];
    snapshots = {};
    constructor(size) {
      this.size = size;
    }
    has(location2) {
      return toCacheKey(location2) in this.snapshots;
    }
    get(location2) {
      if (this.has(location2)) {
        const snapshot = this.read(location2);
        this.touch(location2);
        return snapshot;
      }
    }
    put(location2, snapshot) {
      this.write(location2, snapshot);
      this.touch(location2);
      return snapshot;
    }
    clear() {
      this.snapshots = {};
    }
    read(location2) {
      return this.snapshots[toCacheKey(location2)];
    }
    write(location2, snapshot) {
      this.snapshots[toCacheKey(location2)] = snapshot;
    }
    touch(location2) {
      const key = toCacheKey(location2);
      const index = this.keys.indexOf(key);
      if (index > -1)
        this.keys.splice(index, 1);
      this.keys.unshift(key);
      this.trim();
    }
    trim() {
      for (const key of this.keys.splice(this.size)) {
        delete this.snapshots[key];
      }
    }
  };
  var PageView = class extends View {
    snapshotCache = new SnapshotCache(10);
    lastRenderedLocation = new URL(location.href);
    forceReloaded = false;
    shouldTransitionTo(newSnapshot) {
      return this.snapshot.prefersViewTransitions && newSnapshot.prefersViewTransitions;
    }
    renderPage(snapshot, isPreview = false, willRender = true, visit2) {
      const shouldMorphPage = this.isPageRefresh(visit2) && this.snapshot.shouldMorphPage;
      const rendererClass = shouldMorphPage ? MorphRenderer : PageRenderer;
      const renderer = new rendererClass(this.snapshot, snapshot, PageRenderer.renderElement, isPreview, willRender);
      if (!renderer.shouldRender) {
        this.forceReloaded = true;
      } else {
        visit2?.changeHistory();
      }
      return this.render(renderer);
    }
    renderError(snapshot, visit2) {
      visit2?.changeHistory();
      const renderer = new ErrorRenderer(this.snapshot, snapshot, ErrorRenderer.renderElement, false);
      return this.render(renderer);
    }
    clearSnapshotCache() {
      this.snapshotCache.clear();
    }
    async cacheSnapshot(snapshot = this.snapshot) {
      if (snapshot.isCacheable) {
        this.delegate.viewWillCacheSnapshot();
        const { lastRenderedLocation: location2 } = this;
        await nextEventLoopTick();
        const cachedSnapshot = snapshot.clone();
        this.snapshotCache.put(location2, cachedSnapshot);
        return cachedSnapshot;
      }
    }
    getCachedSnapshotForLocation(location2) {
      return this.snapshotCache.get(location2);
    }
    isPageRefresh(visit2) {
      return !visit2 || this.lastRenderedLocation.pathname === visit2.location.pathname && visit2.action === "replace";
    }
    shouldPreserveScrollPosition(visit2) {
      return this.isPageRefresh(visit2) && this.snapshot.shouldPreserveScrollPosition;
    }
    get snapshot() {
      return PageSnapshot.fromElement(this.element);
    }
  };
  var Preloader = class {
    selector = "a[data-turbo-preload]";
    constructor(delegate, snapshotCache) {
      this.delegate = delegate;
      this.snapshotCache = snapshotCache;
    }
    start() {
      if (document.readyState === "loading") {
        document.addEventListener("DOMContentLoaded", this.#preloadAll);
      } else {
        this.preloadOnLoadLinksForView(document.body);
      }
    }
    stop() {
      document.removeEventListener("DOMContentLoaded", this.#preloadAll);
    }
    preloadOnLoadLinksForView(element) {
      for (const link of element.querySelectorAll(this.selector)) {
        if (this.delegate.shouldPreloadLink(link)) {
          this.preloadURL(link);
        }
      }
    }
    async preloadURL(link) {
      const location2 = new URL(link.href);
      if (this.snapshotCache.has(location2)) {
        return;
      }
      const fetchRequest = new FetchRequest(this, FetchMethod.get, location2, new URLSearchParams(), link);
      await fetchRequest.perform();
    }
    prepareRequest(fetchRequest) {
      fetchRequest.headers["X-Sec-Purpose"] = "prefetch";
    }
    async requestSucceededWithResponse(fetchRequest, fetchResponse) {
      try {
        const responseHTML = await fetchResponse.responseHTML;
        const snapshot = PageSnapshot.fromHTMLString(responseHTML);
        this.snapshotCache.put(fetchRequest.url, snapshot);
      } catch (_2) {
      }
    }
    requestStarted(fetchRequest) {
    }
    requestErrored(fetchRequest) {
    }
    requestFinished(fetchRequest) {
    }
    requestPreventedHandlingResponse(fetchRequest, fetchResponse) {
    }
    requestFailedWithResponse(fetchRequest, fetchResponse) {
    }
    #preloadAll = () => {
      this.preloadOnLoadLinksForView(document.body);
    };
  };
  var Cache = class {
    constructor(session2) {
      this.session = session2;
    }
    clear() {
      this.session.clearCache();
    }
    resetCacheControl() {
      this.#setCacheControl("");
    }
    exemptPageFromCache() {
      this.#setCacheControl("no-cache");
    }
    exemptPageFromPreview() {
      this.#setCacheControl("no-preview");
    }
    #setCacheControl(value) {
      setMetaContent("turbo-cache-control", value);
    }
  };
  var Session = class {
    navigator = new Navigator(this);
    history = new History(this);
    view = new PageView(this, document.documentElement);
    adapter = new BrowserAdapter(this);
    pageObserver = new PageObserver(this);
    cacheObserver = new CacheObserver();
    linkPrefetchObserver = new LinkPrefetchObserver(this, document);
    linkClickObserver = new LinkClickObserver(this, window);
    formSubmitObserver = new FormSubmitObserver(this, document);
    scrollObserver = new ScrollObserver(this);
    streamObserver = new StreamObserver(this);
    formLinkClickObserver = new FormLinkClickObserver(this, document.documentElement);
    frameRedirector = new FrameRedirector(this, document.documentElement);
    streamMessageRenderer = new StreamMessageRenderer();
    cache = new Cache(this);
    drive = true;
    enabled = true;
    progressBarDelay = 500;
    started = false;
    formMode = "on";
    #pageRefreshDebouncePeriod = 150;
    constructor(recentRequests2) {
      this.recentRequests = recentRequests2;
      this.preloader = new Preloader(this, this.view.snapshotCache);
      this.debouncedRefresh = this.refresh;
      this.pageRefreshDebouncePeriod = this.pageRefreshDebouncePeriod;
    }
    start() {
      if (!this.started) {
        this.pageObserver.start();
        this.cacheObserver.start();
        this.linkPrefetchObserver.start();
        this.formLinkClickObserver.start();
        this.linkClickObserver.start();
        this.formSubmitObserver.start();
        this.scrollObserver.start();
        this.streamObserver.start();
        this.frameRedirector.start();
        this.history.start();
        this.preloader.start();
        this.started = true;
        this.enabled = true;
      }
    }
    disable() {
      this.enabled = false;
    }
    stop() {
      if (this.started) {
        this.pageObserver.stop();
        this.cacheObserver.stop();
        this.linkPrefetchObserver.stop();
        this.formLinkClickObserver.stop();
        this.linkClickObserver.stop();
        this.formSubmitObserver.stop();
        this.scrollObserver.stop();
        this.streamObserver.stop();
        this.frameRedirector.stop();
        this.history.stop();
        this.preloader.stop();
        this.started = false;
      }
    }
    registerAdapter(adapter) {
      this.adapter = adapter;
    }
    visit(location2, options = {}) {
      const frameElement = options.frame ? document.getElementById(options.frame) : null;
      if (frameElement instanceof FrameElement) {
        const action = options.action || getVisitAction(frameElement);
        frameElement.delegate.proposeVisitIfNavigatedWithAction(frameElement, action);
        frameElement.src = location2.toString();
      } else {
        this.navigator.proposeVisit(expandURL(location2), options);
      }
    }
    refresh(url, requestId) {
      const isRecentRequest = requestId && this.recentRequests.has(requestId);
      if (!isRecentRequest) {
        this.visit(url, { action: "replace", shouldCacheSnapshot: false });
      }
    }
    connectStreamSource(source) {
      this.streamObserver.connectStreamSource(source);
    }
    disconnectStreamSource(source) {
      this.streamObserver.disconnectStreamSource(source);
    }
    renderStreamMessage(message) {
      this.streamMessageRenderer.render(StreamMessage.wrap(message));
    }
    clearCache() {
      this.view.clearSnapshotCache();
    }
    setProgressBarDelay(delay) {
      this.progressBarDelay = delay;
    }
    setFormMode(mode) {
      this.formMode = mode;
    }
    get location() {
      return this.history.location;
    }
    get restorationIdentifier() {
      return this.history.restorationIdentifier;
    }
    get pageRefreshDebouncePeriod() {
      return this.#pageRefreshDebouncePeriod;
    }
    set pageRefreshDebouncePeriod(value) {
      this.refresh = debounce(this.debouncedRefresh.bind(this), value);
      this.#pageRefreshDebouncePeriod = value;
    }
    shouldPreloadLink(element) {
      const isUnsafe = element.hasAttribute("data-turbo-method");
      const isStream = element.hasAttribute("data-turbo-stream");
      const frameTarget = element.getAttribute("data-turbo-frame");
      const frame = frameTarget == "_top" ? null : document.getElementById(frameTarget) || findClosestRecursively(element, "turbo-frame:not([disabled])");
      if (isUnsafe || isStream || frame instanceof FrameElement) {
        return false;
      } else {
        const location2 = new URL(element.href);
        return this.elementIsNavigatable(element) && locationIsVisitable(location2, this.snapshot.rootLocation);
      }
    }
    historyPoppedToLocationWithRestorationIdentifierAndDirection(location2, restorationIdentifier, direction) {
      if (this.enabled) {
        this.navigator.startVisit(location2, restorationIdentifier, {
          action: "restore",
          historyChanged: true,
          direction
        });
      } else {
        this.adapter.pageInvalidated({
          reason: "turbo_disabled"
        });
      }
    }
    scrollPositionChanged(position) {
      this.history.updateRestorationData({ scrollPosition: position });
    }
    willSubmitFormLinkToLocation(link, location2) {
      return this.elementIsNavigatable(link) && locationIsVisitable(location2, this.snapshot.rootLocation);
    }
    submittedFormLinkToLocation() {
    }
    canPrefetchRequestToLocation(link, location2) {
      return this.elementIsNavigatable(link) && locationIsVisitable(location2, this.snapshot.rootLocation);
    }
    willFollowLinkToLocation(link, location2, event) {
      return this.elementIsNavigatable(link) && locationIsVisitable(location2, this.snapshot.rootLocation) && this.applicationAllowsFollowingLinkToLocation(link, location2, event);
    }
    followedLinkToLocation(link, location2) {
      const action = this.getActionForLink(link);
      const acceptsStreamResponse = link.hasAttribute("data-turbo-stream");
      this.visit(location2.href, { action, acceptsStreamResponse });
    }
    allowsVisitingLocationWithAction(location2, action) {
      return this.locationWithActionIsSamePage(location2, action) || this.applicationAllowsVisitingLocation(location2);
    }
    visitProposedToLocation(location2, options) {
      extendURLWithDeprecatedProperties(location2);
      this.adapter.visitProposedToLocation(location2, options);
    }
    visitStarted(visit2) {
      if (!visit2.acceptsStreamResponse) {
        markAsBusy(document.documentElement);
        this.view.markVisitDirection(visit2.direction);
      }
      extendURLWithDeprecatedProperties(visit2.location);
      if (!visit2.silent) {
        this.notifyApplicationAfterVisitingLocation(visit2.location, visit2.action);
      }
    }
    visitCompleted(visit2) {
      this.view.unmarkVisitDirection();
      clearBusyState(document.documentElement);
      this.notifyApplicationAfterPageLoad(visit2.getTimingMetrics());
    }
    locationWithActionIsSamePage(location2, action) {
      return this.navigator.locationWithActionIsSamePage(location2, action);
    }
    visitScrolledToSamePageLocation(oldURL, newURL) {
      this.notifyApplicationAfterVisitingSamePageLocation(oldURL, newURL);
    }
    willSubmitForm(form, submitter) {
      const action = getAction$1(form, submitter);
      return this.submissionIsNavigatable(form, submitter) && locationIsVisitable(expandURL(action), this.snapshot.rootLocation);
    }
    formSubmitted(form, submitter) {
      this.navigator.submitForm(form, submitter);
    }
    pageBecameInteractive() {
      this.view.lastRenderedLocation = this.location;
      this.notifyApplicationAfterPageLoad();
    }
    pageLoaded() {
      this.history.assumeControlOfScrollRestoration();
    }
    pageWillUnload() {
      this.history.relinquishControlOfScrollRestoration();
    }
    receivedMessageFromStream(message) {
      this.renderStreamMessage(message);
    }
    viewWillCacheSnapshot() {
      if (!this.navigator.currentVisit?.silent) {
        this.notifyApplicationBeforeCachingSnapshot();
      }
    }
    allowsImmediateRender({ element }, options) {
      const event = this.notifyApplicationBeforeRender(element, options);
      const {
        defaultPrevented,
        detail: { render }
      } = event;
      if (this.view.renderer && render) {
        this.view.renderer.renderElement = render;
      }
      return !defaultPrevented;
    }
    viewRenderedSnapshot(_snapshot, _isPreview, renderMethod) {
      this.view.lastRenderedLocation = this.history.location;
      this.notifyApplicationAfterRender(renderMethod);
    }
    preloadOnLoadLinksForView(element) {
      this.preloader.preloadOnLoadLinksForView(element);
    }
    viewInvalidated(reason) {
      this.adapter.pageInvalidated(reason);
    }
    frameLoaded(frame) {
      this.notifyApplicationAfterFrameLoad(frame);
    }
    frameRendered(fetchResponse, frame) {
      this.notifyApplicationAfterFrameRender(fetchResponse, frame);
    }
    applicationAllowsFollowingLinkToLocation(link, location2, ev) {
      const event = this.notifyApplicationAfterClickingLinkToLocation(link, location2, ev);
      return !event.defaultPrevented;
    }
    applicationAllowsVisitingLocation(location2) {
      const event = this.notifyApplicationBeforeVisitingLocation(location2);
      return !event.defaultPrevented;
    }
    notifyApplicationAfterClickingLinkToLocation(link, location2, event) {
      return dispatch("turbo:click", {
        target: link,
        detail: { url: location2.href, originalEvent: event },
        cancelable: true
      });
    }
    notifyApplicationBeforeVisitingLocation(location2) {
      return dispatch("turbo:before-visit", {
        detail: { url: location2.href },
        cancelable: true
      });
    }
    notifyApplicationAfterVisitingLocation(location2, action) {
      return dispatch("turbo:visit", { detail: { url: location2.href, action } });
    }
    notifyApplicationBeforeCachingSnapshot() {
      return dispatch("turbo:before-cache");
    }
    notifyApplicationBeforeRender(newBody, options) {
      return dispatch("turbo:before-render", {
        detail: { newBody, ...options },
        cancelable: true
      });
    }
    notifyApplicationAfterRender(renderMethod) {
      return dispatch("turbo:render", { detail: { renderMethod } });
    }
    notifyApplicationAfterPageLoad(timing = {}) {
      return dispatch("turbo:load", {
        detail: { url: this.location.href, timing }
      });
    }
    notifyApplicationAfterVisitingSamePageLocation(oldURL, newURL) {
      dispatchEvent(new HashChangeEvent("hashchange", {
        oldURL: oldURL.toString(),
        newURL: newURL.toString()
      }));
    }
    notifyApplicationAfterFrameLoad(frame) {
      return dispatch("turbo:frame-load", { target: frame });
    }
    notifyApplicationAfterFrameRender(fetchResponse, frame) {
      return dispatch("turbo:frame-render", {
        detail: { fetchResponse },
        target: frame,
        cancelable: true
      });
    }
    submissionIsNavigatable(form, submitter) {
      if (this.formMode == "off") {
        return false;
      } else {
        const submitterIsNavigatable = submitter ? this.elementIsNavigatable(submitter) : true;
        if (this.formMode == "optin") {
          return submitterIsNavigatable && form.closest('[data-turbo="true"]') != null;
        } else {
          return submitterIsNavigatable && this.elementIsNavigatable(form);
        }
      }
    }
    elementIsNavigatable(element) {
      const container = findClosestRecursively(element, "[data-turbo]");
      const withinFrame = findClosestRecursively(element, "turbo-frame");
      if (this.drive || withinFrame) {
        if (container) {
          return container.getAttribute("data-turbo") != "false";
        } else {
          return true;
        }
      } else {
        if (container) {
          return container.getAttribute("data-turbo") == "true";
        } else {
          return false;
        }
      }
    }
    getActionForLink(link) {
      return getVisitAction(link) || "advance";
    }
    get snapshot() {
      return this.view.snapshot;
    }
  };
  function extendURLWithDeprecatedProperties(url) {
    Object.defineProperties(url, deprecatedLocationPropertyDescriptors);
  }
  var deprecatedLocationPropertyDescriptors = {
    absoluteURL: {
      get() {
        return this.toString();
      }
    }
  };
  var session = new Session(recentRequests);
  var { cache, navigator: navigator$1 } = session;
  function start() {
    session.start();
  }
  function registerAdapter(adapter) {
    session.registerAdapter(adapter);
  }
  function visit(location2, options) {
    session.visit(location2, options);
  }
  function connectStreamSource(source) {
    session.connectStreamSource(source);
  }
  function disconnectStreamSource(source) {
    session.disconnectStreamSource(source);
  }
  function renderStreamMessage(message) {
    session.renderStreamMessage(message);
  }
  function clearCache() {
    console.warn("Please replace `Turbo.clearCache()` with `Turbo.cache.clear()`. The top-level function is deprecated and will be removed in a future version of Turbo.`");
    session.clearCache();
  }
  function setProgressBarDelay(delay) {
    session.setProgressBarDelay(delay);
  }
  function setConfirmMethod(confirmMethod) {
    FormSubmission.confirmMethod = confirmMethod;
  }
  function setFormMode(mode) {
    session.setFormMode(mode);
  }
  var Turbo2 = /* @__PURE__ */ Object.freeze({
    __proto__: null,
    navigator: navigator$1,
    session,
    cache,
    PageRenderer,
    PageSnapshot,
    FrameRenderer,
    fetch: fetchWithTurboHeaders,
    start,
    registerAdapter,
    visit,
    connectStreamSource,
    disconnectStreamSource,
    renderStreamMessage,
    clearCache,
    setProgressBarDelay,
    setConfirmMethod,
    setFormMode
  });
  var TurboFrameMissingError = class extends Error {
  };
  var FrameController = class {
    fetchResponseLoaded = (_fetchResponse) => Promise.resolve();
    #currentFetchRequest = null;
    #resolveVisitPromise = () => {
    };
    #connected = false;
    #hasBeenLoaded = false;
    #ignoredAttributes = /* @__PURE__ */ new Set();
    action = null;
    constructor(element) {
      this.element = element;
      this.view = new FrameView(this, this.element);
      this.appearanceObserver = new AppearanceObserver(this, this.element);
      this.formLinkClickObserver = new FormLinkClickObserver(this, this.element);
      this.linkInterceptor = new LinkInterceptor(this, this.element);
      this.restorationIdentifier = uuid();
      this.formSubmitObserver = new FormSubmitObserver(this, this.element);
    }
    connect() {
      if (!this.#connected) {
        this.#connected = true;
        if (this.loadingStyle == FrameLoadingStyle.lazy) {
          this.appearanceObserver.start();
        } else {
          this.#loadSourceURL();
        }
        this.formLinkClickObserver.start();
        this.linkInterceptor.start();
        this.formSubmitObserver.start();
      }
    }
    disconnect() {
      if (this.#connected) {
        this.#connected = false;
        this.appearanceObserver.stop();
        this.formLinkClickObserver.stop();
        this.linkInterceptor.stop();
        this.formSubmitObserver.stop();
      }
    }
    disabledChanged() {
      if (this.loadingStyle == FrameLoadingStyle.eager) {
        this.#loadSourceURL();
      }
    }
    sourceURLChanged() {
      if (this.#isIgnoringChangesTo("src"))
        return;
      if (this.element.isConnected) {
        this.complete = false;
      }
      if (this.loadingStyle == FrameLoadingStyle.eager || this.#hasBeenLoaded) {
        this.#loadSourceURL();
      }
    }
    sourceURLReloaded() {
      const { src } = this.element;
      this.#ignoringChangesToAttribute("complete", () => {
        this.element.removeAttribute("complete");
      });
      this.element.src = null;
      this.element.src = src;
      return this.element.loaded;
    }
    completeChanged() {
      if (this.#isIgnoringChangesTo("complete"))
        return;
      this.#loadSourceURL();
    }
    loadingStyleChanged() {
      if (this.loadingStyle == FrameLoadingStyle.lazy) {
        this.appearanceObserver.start();
      } else {
        this.appearanceObserver.stop();
        this.#loadSourceURL();
      }
    }
    async #loadSourceURL() {
      if (this.enabled && this.isActive && !this.complete && this.sourceURL) {
        this.element.loaded = this.#visit(expandURL(this.sourceURL));
        this.appearanceObserver.stop();
        await this.element.loaded;
        this.#hasBeenLoaded = true;
      }
    }
    async loadResponse(fetchResponse) {
      if (fetchResponse.redirected || fetchResponse.succeeded && fetchResponse.isHTML) {
        this.sourceURL = fetchResponse.response.url;
      }
      try {
        const html = await fetchResponse.responseHTML;
        if (html) {
          const document2 = parseHTMLDocument(html);
          const pageSnapshot = PageSnapshot.fromDocument(document2);
          if (pageSnapshot.isVisitable) {
            await this.#loadFrameResponse(fetchResponse, document2);
          } else {
            await this.#handleUnvisitableFrameResponse(fetchResponse);
          }
        }
      } finally {
        this.fetchResponseLoaded = () => Promise.resolve();
      }
    }
    elementAppearedInViewport(element) {
      this.proposeVisitIfNavigatedWithAction(element, getVisitAction(element));
      this.#loadSourceURL();
    }
    willSubmitFormLinkToLocation(link) {
      return this.#shouldInterceptNavigation(link);
    }
    submittedFormLinkToLocation(link, _location, form) {
      const frame = this.#findFrameElement(link);
      if (frame)
        form.setAttribute("data-turbo-frame", frame.id);
    }
    shouldInterceptLinkClick(element, _location, _event) {
      return this.#shouldInterceptNavigation(element);
    }
    linkClickIntercepted(element, location2) {
      this.#navigateFrame(element, location2);
    }
    willSubmitForm(element, submitter) {
      return element.closest("turbo-frame") == this.element && this.#shouldInterceptNavigation(element, submitter);
    }
    formSubmitted(element, submitter) {
      if (this.formSubmission) {
        this.formSubmission.stop();
      }
      this.formSubmission = new FormSubmission(this, element, submitter);
      const { fetchRequest } = this.formSubmission;
      this.prepareRequest(fetchRequest);
      this.formSubmission.start();
    }
    prepareRequest(request) {
      request.headers["Turbo-Frame"] = this.id;
      if (this.currentNavigationElement?.hasAttribute("data-turbo-stream")) {
        request.acceptResponseType(StreamMessage.contentType);
      }
    }
    requestStarted(_request) {
      markAsBusy(this.element);
    }
    requestPreventedHandlingResponse(_request, _response) {
      this.#resolveVisitPromise();
    }
    async requestSucceededWithResponse(request, response) {
      await this.loadResponse(response);
      this.#resolveVisitPromise();
    }
    async requestFailedWithResponse(request, response) {
      await this.loadResponse(response);
      this.#resolveVisitPromise();
    }
    requestErrored(request, error3) {
      console.error(error3);
      this.#resolveVisitPromise();
    }
    requestFinished(_request) {
      clearBusyState(this.element);
    }
    formSubmissionStarted({ formElement }) {
      markAsBusy(formElement, this.#findFrameElement(formElement));
    }
    formSubmissionSucceededWithResponse(formSubmission, response) {
      const frame = this.#findFrameElement(formSubmission.formElement, formSubmission.submitter);
      frame.delegate.proposeVisitIfNavigatedWithAction(frame, getVisitAction(formSubmission.submitter, formSubmission.formElement, frame));
      frame.delegate.loadResponse(response);
      if (!formSubmission.isSafe) {
        session.clearCache();
      }
    }
    formSubmissionFailedWithResponse(formSubmission, fetchResponse) {
      this.element.delegate.loadResponse(fetchResponse);
      session.clearCache();
    }
    formSubmissionErrored(formSubmission, error3) {
      console.error(error3);
    }
    formSubmissionFinished({ formElement }) {
      clearBusyState(formElement, this.#findFrameElement(formElement));
    }
    allowsImmediateRender({ element: newFrame }, options) {
      const event = dispatch("turbo:before-frame-render", {
        target: this.element,
        detail: { newFrame, ...options },
        cancelable: true
      });
      const {
        defaultPrevented,
        detail: { render }
      } = event;
      if (this.view.renderer && render) {
        this.view.renderer.renderElement = render;
      }
      return !defaultPrevented;
    }
    viewRenderedSnapshot(_snapshot, _isPreview, _renderMethod) {
    }
    preloadOnLoadLinksForView(element) {
      session.preloadOnLoadLinksForView(element);
    }
    viewInvalidated() {
    }
    willRenderFrame(currentElement, _newElement) {
      this.previousFrameElement = currentElement.cloneNode(true);
    }
    visitCachedSnapshot = ({ element }) => {
      const frame = element.querySelector("#" + this.element.id);
      if (frame && this.previousFrameElement) {
        frame.replaceChildren(...this.previousFrameElement.children);
      }
      delete this.previousFrameElement;
    };
    async #loadFrameResponse(fetchResponse, document2) {
      const newFrameElement = await this.extractForeignFrameElement(document2.body);
      if (newFrameElement) {
        const snapshot = new Snapshot(newFrameElement);
        const renderer = new FrameRenderer(this, this.view.snapshot, snapshot, FrameRenderer.renderElement, false, false);
        if (this.view.renderPromise)
          await this.view.renderPromise;
        this.changeHistory();
        await this.view.render(renderer);
        this.complete = true;
        session.frameRendered(fetchResponse, this.element);
        session.frameLoaded(this.element);
        await this.fetchResponseLoaded(fetchResponse);
      } else if (this.#willHandleFrameMissingFromResponse(fetchResponse)) {
        this.#handleFrameMissingFromResponse(fetchResponse);
      }
    }
    async #visit(url) {
      const request = new FetchRequest(this, FetchMethod.get, url, new URLSearchParams(), this.element);
      this.#currentFetchRequest?.cancel();
      this.#currentFetchRequest = request;
      return new Promise((resolve2) => {
        this.#resolveVisitPromise = () => {
          this.#resolveVisitPromise = () => {
          };
          this.#currentFetchRequest = null;
          resolve2();
        };
        request.perform();
      });
    }
    #navigateFrame(element, url, submitter) {
      const frame = this.#findFrameElement(element, submitter);
      frame.delegate.proposeVisitIfNavigatedWithAction(frame, getVisitAction(submitter, element, frame));
      this.#withCurrentNavigationElement(element, () => {
        frame.src = url;
      });
    }
    proposeVisitIfNavigatedWithAction(frame, action = null) {
      this.action = action;
      if (this.action) {
        const pageSnapshot = PageSnapshot.fromElement(frame).clone();
        const { visitCachedSnapshot } = frame.delegate;
        frame.delegate.fetchResponseLoaded = async (fetchResponse) => {
          if (frame.src) {
            const { statusCode, redirected } = fetchResponse;
            const responseHTML = await fetchResponse.responseHTML;
            const response = { statusCode, redirected, responseHTML };
            const options = {
              response,
              visitCachedSnapshot,
              willRender: false,
              updateHistory: false,
              restorationIdentifier: this.restorationIdentifier,
              snapshot: pageSnapshot
            };
            if (this.action)
              options.action = this.action;
            session.visit(frame.src, options);
          }
        };
      }
    }
    changeHistory() {
      if (this.action) {
        const method = getHistoryMethodForAction(this.action);
        session.history.update(method, expandURL(this.element.src || ""), this.restorationIdentifier);
      }
    }
    async #handleUnvisitableFrameResponse(fetchResponse) {
      console.warn(`The response (${fetchResponse.statusCode}) from <turbo-frame id="${this.element.id}"> is performing a full page visit due to turbo-visit-control.`);
      await this.#visitResponse(fetchResponse.response);
    }
    #willHandleFrameMissingFromResponse(fetchResponse) {
      this.element.setAttribute("complete", "");
      const response = fetchResponse.response;
      const visit2 = async (url, options) => {
        if (url instanceof Response) {
          this.#visitResponse(url);
        } else {
          session.visit(url, options);
        }
      };
      const event = dispatch("turbo:frame-missing", {
        target: this.element,
        detail: { response, visit: visit2 },
        cancelable: true
      });
      return !event.defaultPrevented;
    }
    #handleFrameMissingFromResponse(fetchResponse) {
      this.view.missing();
      this.#throwFrameMissingError(fetchResponse);
    }
    #throwFrameMissingError(fetchResponse) {
      const message = `The response (${fetchResponse.statusCode}) did not contain the expected <turbo-frame id="${this.element.id}"> and will be ignored. To perform a full page visit instead, set turbo-visit-control to reload.`;
      throw new TurboFrameMissingError(message);
    }
    async #visitResponse(response) {
      const wrapped = new FetchResponse(response);
      const responseHTML = await wrapped.responseHTML;
      const { location: location2, redirected, statusCode } = wrapped;
      return session.visit(location2, { response: { redirected, statusCode, responseHTML } });
    }
    #findFrameElement(element, submitter) {
      const id2 = getAttribute("data-turbo-frame", submitter, element) || this.element.getAttribute("target");
      return getFrameElementById(id2) ?? this.element;
    }
    async extractForeignFrameElement(container) {
      let element;
      const id2 = CSS.escape(this.id);
      try {
        element = activateElement(container.querySelector(`turbo-frame#${id2}`), this.sourceURL);
        if (element) {
          return element;
        }
        element = activateElement(container.querySelector(`turbo-frame[src][recurse~=${id2}]`), this.sourceURL);
        if (element) {
          await element.loaded;
          return await this.extractForeignFrameElement(element);
        }
      } catch (error3) {
        console.error(error3);
        return new FrameElement();
      }
      return null;
    }
    #formActionIsVisitable(form, submitter) {
      const action = getAction$1(form, submitter);
      return locationIsVisitable(expandURL(action), this.rootLocation);
    }
    #shouldInterceptNavigation(element, submitter) {
      const id2 = getAttribute("data-turbo-frame", submitter, element) || this.element.getAttribute("target");
      if (element instanceof HTMLFormElement && !this.#formActionIsVisitable(element, submitter)) {
        return false;
      }
      if (!this.enabled || id2 == "_top") {
        return false;
      }
      if (id2) {
        const frameElement = getFrameElementById(id2);
        if (frameElement) {
          return !frameElement.disabled;
        }
      }
      if (!session.elementIsNavigatable(element)) {
        return false;
      }
      if (submitter && !session.elementIsNavigatable(submitter)) {
        return false;
      }
      return true;
    }
    get id() {
      return this.element.id;
    }
    get enabled() {
      return !this.element.disabled;
    }
    get sourceURL() {
      if (this.element.src) {
        return this.element.src;
      }
    }
    set sourceURL(sourceURL) {
      this.#ignoringChangesToAttribute("src", () => {
        this.element.src = sourceURL ?? null;
      });
    }
    get loadingStyle() {
      return this.element.loading;
    }
    get isLoading() {
      return this.formSubmission !== void 0 || this.#resolveVisitPromise() !== void 0;
    }
    get complete() {
      return this.element.hasAttribute("complete");
    }
    set complete(value) {
      this.#ignoringChangesToAttribute("complete", () => {
        if (value) {
          this.element.setAttribute("complete", "");
        } else {
          this.element.removeAttribute("complete");
        }
      });
    }
    get isActive() {
      return this.element.isActive && this.#connected;
    }
    get rootLocation() {
      const meta = this.element.ownerDocument.querySelector(`meta[name="turbo-root"]`);
      const root = meta?.content ?? "/";
      return expandURL(root);
    }
    #isIgnoringChangesTo(attributeName) {
      return this.#ignoredAttributes.has(attributeName);
    }
    #ignoringChangesToAttribute(attributeName, callback2) {
      this.#ignoredAttributes.add(attributeName);
      callback2();
      this.#ignoredAttributes.delete(attributeName);
    }
    #withCurrentNavigationElement(element, callback2) {
      this.currentNavigationElement = element;
      callback2();
      delete this.currentNavigationElement;
    }
  };
  function getFrameElementById(id2) {
    if (id2 != null) {
      const element = document.getElementById(id2);
      if (element instanceof FrameElement) {
        return element;
      }
    }
  }
  function activateElement(element, currentURL) {
    if (element) {
      const src = element.getAttribute("src");
      if (src != null && currentURL != null && urlsAreEqual(src, currentURL)) {
        throw new Error(`Matching <turbo-frame id="${element.id}"> element has a source URL which references itself`);
      }
      if (element.ownerDocument !== document) {
        element = document.importNode(element, true);
      }
      if (element instanceof FrameElement) {
        element.connectedCallback();
        element.disconnectedCallback();
        return element;
      }
    }
  }
  var StreamActions = {
    after() {
      this.targetElements.forEach((e2) => e2.parentElement?.insertBefore(this.templateContent, e2.nextSibling));
    },
    append() {
      this.removeDuplicateTargetChildren();
      this.targetElements.forEach((e2) => e2.append(this.templateContent));
    },
    before() {
      this.targetElements.forEach((e2) => e2.parentElement?.insertBefore(this.templateContent, e2));
    },
    prepend() {
      this.removeDuplicateTargetChildren();
      this.targetElements.forEach((e2) => e2.prepend(this.templateContent));
    },
    remove() {
      this.targetElements.forEach((e2) => e2.remove());
    },
    replace() {
      this.targetElements.forEach((e2) => e2.replaceWith(this.templateContent));
    },
    update() {
      this.targetElements.forEach((targetElement) => {
        targetElement.innerHTML = "";
        targetElement.append(this.templateContent);
      });
    },
    refresh() {
      session.refresh(this.baseURI, this.requestId);
    }
  };
  var StreamElement = class extends HTMLElement {
    static async renderElement(newElement) {
      await newElement.performAction();
    }
    async connectedCallback() {
      try {
        await this.render();
      } catch (error3) {
        console.error(error3);
      } finally {
        this.disconnect();
      }
    }
    async render() {
      return this.renderPromise ??= (async () => {
        const event = this.beforeRenderEvent;
        if (this.dispatchEvent(event)) {
          await nextRepaint();
          await event.detail.render(this);
        }
      })();
    }
    disconnect() {
      try {
        this.remove();
      } catch {
      }
    }
    removeDuplicateTargetChildren() {
      this.duplicateChildren.forEach((c2) => c2.remove());
    }
    get duplicateChildren() {
      const existingChildren = this.targetElements.flatMap((e2) => [...e2.children]).filter((c2) => !!c2.id);
      const newChildrenIds = [...this.templateContent?.children || []].filter((c2) => !!c2.id).map((c2) => c2.id);
      return existingChildren.filter((c2) => newChildrenIds.includes(c2.id));
    }
    get performAction() {
      if (this.action) {
        const actionFunction = StreamActions[this.action];
        if (actionFunction) {
          return actionFunction;
        }
        this.#raise("unknown action");
      }
      this.#raise("action attribute is missing");
    }
    get targetElements() {
      if (this.target) {
        return this.targetElementsById;
      } else if (this.targets) {
        return this.targetElementsByQuery;
      } else {
        this.#raise("target or targets attribute is missing");
      }
    }
    get templateContent() {
      return this.templateElement.content.cloneNode(true);
    }
    get templateElement() {
      if (this.firstElementChild === null) {
        const template = this.ownerDocument.createElement("template");
        this.appendChild(template);
        return template;
      } else if (this.firstElementChild instanceof HTMLTemplateElement) {
        return this.firstElementChild;
      }
      this.#raise("first child element must be a <template> element");
    }
    get action() {
      return this.getAttribute("action");
    }
    get target() {
      return this.getAttribute("target");
    }
    get targets() {
      return this.getAttribute("targets");
    }
    get requestId() {
      return this.getAttribute("request-id");
    }
    #raise(message) {
      throw new Error(`${this.description}: ${message}`);
    }
    get description() {
      return (this.outerHTML.match(/<[^>]+>/) ?? [])[0] ?? "<turbo-stream>";
    }
    get beforeRenderEvent() {
      return new CustomEvent("turbo:before-stream-render", {
        bubbles: true,
        cancelable: true,
        detail: { newStream: this, render: StreamElement.renderElement }
      });
    }
    get targetElementsById() {
      const element = this.ownerDocument?.getElementById(this.target);
      if (element !== null) {
        return [element];
      } else {
        return [];
      }
    }
    get targetElementsByQuery() {
      const elements2 = this.ownerDocument?.querySelectorAll(this.targets);
      if (elements2.length !== 0) {
        return Array.prototype.slice.call(elements2);
      } else {
        return [];
      }
    }
  };
  var StreamSourceElement = class extends HTMLElement {
    streamSource = null;
    connectedCallback() {
      this.streamSource = this.src.match(/^ws{1,2}:/) ? new WebSocket(this.src) : new EventSource(this.src);
      connectStreamSource(this.streamSource);
    }
    disconnectedCallback() {
      if (this.streamSource) {
        this.streamSource.close();
        disconnectStreamSource(this.streamSource);
      }
    }
    get src() {
      return this.getAttribute("src") || "";
    }
  };
  FrameElement.delegateConstructor = FrameController;
  if (customElements.get("turbo-frame") === void 0) {
    customElements.define("turbo-frame", FrameElement);
  }
  if (customElements.get("turbo-stream") === void 0) {
    customElements.define("turbo-stream", StreamElement);
  }
  if (customElements.get("turbo-stream-source") === void 0) {
    customElements.define("turbo-stream-source", StreamSourceElement);
  }
  (() => {
    let element = document.currentScript;
    if (!element)
      return;
    if (element.hasAttribute("data-turbo-suppress-warning"))
      return;
    element = element.parentElement;
    while (element) {
      if (element == document.body) {
        return console.warn(unindent`
        You are loading Turbo from a <script> element inside the <body> element. This is probably not what you meant to do!

        Load your application’s JavaScript bundle inside the <head> element instead. <script> elements in <body> are evaluated with each page change.

        For more information, see: https://turbo.hotwired.dev/handbook/building#working-with-script-elements

        ——
        Suppress this warning by adding a "data-turbo-suppress-warning" attribute to: %s
      `, element.outerHTML);
      }
      element = element.parentElement;
    }
  })();
  window.Turbo = { ...Turbo2, StreamActions };
  start();

  // ../../node_modules/@hotwired/turbo-rails/app/javascript/turbo/cable.js
  var consumer;
  async function getConsumer() {
    return consumer || setConsumer(createConsumer2().then(setConsumer));
  }
  function setConsumer(newConsumer) {
    return consumer = newConsumer;
  }
  async function createConsumer2() {
    const { createConsumer: createConsumer3 } = await Promise.resolve().then(() => (init_src(), src_exports));
    return createConsumer3();
  }
  async function subscribeTo(channel, mixin) {
    const { subscriptions } = await getConsumer();
    return subscriptions.create(channel, mixin);
  }

  // ../../node_modules/@hotwired/turbo-rails/app/javascript/turbo/snakeize.js
  function walk(obj) {
    if (!obj || typeof obj !== "object")
      return obj;
    if (obj instanceof Date || obj instanceof RegExp)
      return obj;
    if (Array.isArray(obj))
      return obj.map(walk);
    return Object.keys(obj).reduce(function(acc, key) {
      var camel = key[0].toLowerCase() + key.slice(1).replace(/([A-Z]+)/g, function(m2, x2) {
        return "_" + x2.toLowerCase();
      });
      acc[camel] = walk(obj[key]);
      return acc;
    }, {});
  }

  // ../../node_modules/@hotwired/turbo-rails/app/javascript/turbo/cable_stream_source_element.js
  var TurboCableStreamSourceElement = class extends HTMLElement {
    async connectedCallback() {
      connectStreamSource(this);
      this.subscription = await subscribeTo(this.channel, {
        received: this.dispatchMessageEvent.bind(this),
        connected: this.subscriptionConnected.bind(this),
        disconnected: this.subscriptionDisconnected.bind(this)
      });
    }
    disconnectedCallback() {
      disconnectStreamSource(this);
      if (this.subscription)
        this.subscription.unsubscribe();
    }
    dispatchMessageEvent(data) {
      const event = new MessageEvent("message", { data });
      return this.dispatchEvent(event);
    }
    subscriptionConnected() {
      this.setAttribute("connected", "");
    }
    subscriptionDisconnected() {
      this.removeAttribute("connected");
    }
    get channel() {
      const channel = this.getAttribute("channel");
      const signed_stream_name = this.getAttribute("signed-stream-name");
      return { channel, signed_stream_name, ...walk({ ...this.dataset }) };
    }
  };
  if (customElements.get("turbo-cable-stream-source") === void 0) {
    customElements.define("turbo-cable-stream-source", TurboCableStreamSourceElement);
  }

  // ../../node_modules/@hotwired/turbo-rails/app/javascript/turbo/fetch_requests.js
  function encodeMethodIntoRequestBody(event) {
    if (event.target instanceof HTMLFormElement) {
      const { target: form, detail: { fetchOptions } } = event;
      form.addEventListener("turbo:submit-start", ({ detail: { formSubmission: { submitter } } }) => {
        const body = isBodyInit(fetchOptions.body) ? fetchOptions.body : new URLSearchParams();
        const method = determineFetchMethod(submitter, body, form);
        if (!/get/i.test(method)) {
          if (/post/i.test(method)) {
            body.delete("_method");
          } else {
            body.set("_method", method);
          }
          fetchOptions.method = "post";
        }
      }, { once: true });
    }
  }
  function determineFetchMethod(submitter, body, form) {
    const formMethod = determineFormMethod(submitter);
    const overrideMethod = body.get("_method");
    const method = form.getAttribute("method") || "get";
    if (typeof formMethod == "string") {
      return formMethod;
    } else if (typeof overrideMethod == "string") {
      return overrideMethod;
    } else {
      return method;
    }
  }
  function determineFormMethod(submitter) {
    if (submitter instanceof HTMLButtonElement || submitter instanceof HTMLInputElement) {
      if (submitter.name === "_method") {
        return submitter.value;
      } else if (submitter.hasAttribute("formmethod")) {
        return submitter.formMethod;
      } else {
        return null;
      }
    } else {
      return null;
    }
  }
  function isBodyInit(body) {
    return body instanceof FormData || body instanceof URLSearchParams;
  }

  // ../../node_modules/@hotwired/turbo-rails/app/javascript/turbo/index.js
  window.Turbo = turbo_es2017_esm_exports;
  addEventListener("turbo:before-fetch-request", encodeMethodIntoRequestBody);

  // ../../node_modules/@hotwired/stimulus/dist/stimulus.js
  var EventListener = class {
    constructor(eventTarget, eventName, eventOptions) {
      this.eventTarget = eventTarget;
      this.eventName = eventName;
      this.eventOptions = eventOptions;
      this.unorderedBindings = /* @__PURE__ */ new Set();
    }
    connect() {
      this.eventTarget.addEventListener(this.eventName, this, this.eventOptions);
    }
    disconnect() {
      this.eventTarget.removeEventListener(this.eventName, this, this.eventOptions);
    }
    bindingConnected(binding) {
      this.unorderedBindings.add(binding);
    }
    bindingDisconnected(binding) {
      this.unorderedBindings.delete(binding);
    }
    handleEvent(event) {
      const extendedEvent = extendEvent(event);
      for (const binding of this.bindings) {
        if (extendedEvent.immediatePropagationStopped) {
          break;
        } else {
          binding.handleEvent(extendedEvent);
        }
      }
    }
    hasBindings() {
      return this.unorderedBindings.size > 0;
    }
    get bindings() {
      return Array.from(this.unorderedBindings).sort((left2, right2) => {
        const leftIndex = left2.index, rightIndex = right2.index;
        return leftIndex < rightIndex ? -1 : leftIndex > rightIndex ? 1 : 0;
      });
    }
  };
  function extendEvent(event) {
    if ("immediatePropagationStopped" in event) {
      return event;
    } else {
      const { stopImmediatePropagation } = event;
      return Object.assign(event, {
        immediatePropagationStopped: false,
        stopImmediatePropagation() {
          this.immediatePropagationStopped = true;
          stopImmediatePropagation.call(this);
        }
      });
    }
  }
  var Dispatcher = class {
    constructor(application2) {
      this.application = application2;
      this.eventListenerMaps = /* @__PURE__ */ new Map();
      this.started = false;
    }
    start() {
      if (!this.started) {
        this.started = true;
        this.eventListeners.forEach((eventListener) => eventListener.connect());
      }
    }
    stop() {
      if (this.started) {
        this.started = false;
        this.eventListeners.forEach((eventListener) => eventListener.disconnect());
      }
    }
    get eventListeners() {
      return Array.from(this.eventListenerMaps.values()).reduce((listeners, map3) => listeners.concat(Array.from(map3.values())), []);
    }
    bindingConnected(binding) {
      this.fetchEventListenerForBinding(binding).bindingConnected(binding);
    }
    bindingDisconnected(binding, clearEventListeners = false) {
      this.fetchEventListenerForBinding(binding).bindingDisconnected(binding);
      if (clearEventListeners)
        this.clearEventListenersForBinding(binding);
    }
    handleError(error3, message, detail = {}) {
      this.application.handleError(error3, `Error ${message}`, detail);
    }
    clearEventListenersForBinding(binding) {
      const eventListener = this.fetchEventListenerForBinding(binding);
      if (!eventListener.hasBindings()) {
        eventListener.disconnect();
        this.removeMappedEventListenerFor(binding);
      }
    }
    removeMappedEventListenerFor(binding) {
      const { eventTarget, eventName, eventOptions } = binding;
      const eventListenerMap = this.fetchEventListenerMapForEventTarget(eventTarget);
      const cacheKey = this.cacheKey(eventName, eventOptions);
      eventListenerMap.delete(cacheKey);
      if (eventListenerMap.size == 0)
        this.eventListenerMaps.delete(eventTarget);
    }
    fetchEventListenerForBinding(binding) {
      const { eventTarget, eventName, eventOptions } = binding;
      return this.fetchEventListener(eventTarget, eventName, eventOptions);
    }
    fetchEventListener(eventTarget, eventName, eventOptions) {
      const eventListenerMap = this.fetchEventListenerMapForEventTarget(eventTarget);
      const cacheKey = this.cacheKey(eventName, eventOptions);
      let eventListener = eventListenerMap.get(cacheKey);
      if (!eventListener) {
        eventListener = this.createEventListener(eventTarget, eventName, eventOptions);
        eventListenerMap.set(cacheKey, eventListener);
      }
      return eventListener;
    }
    createEventListener(eventTarget, eventName, eventOptions) {
      const eventListener = new EventListener(eventTarget, eventName, eventOptions);
      if (this.started) {
        eventListener.connect();
      }
      return eventListener;
    }
    fetchEventListenerMapForEventTarget(eventTarget) {
      let eventListenerMap = this.eventListenerMaps.get(eventTarget);
      if (!eventListenerMap) {
        eventListenerMap = /* @__PURE__ */ new Map();
        this.eventListenerMaps.set(eventTarget, eventListenerMap);
      }
      return eventListenerMap;
    }
    cacheKey(eventName, eventOptions) {
      const parts = [eventName];
      Object.keys(eventOptions).sort().forEach((key) => {
        parts.push(`${eventOptions[key] ? "" : "!"}${key}`);
      });
      return parts.join(":");
    }
  };
  var defaultActionDescriptorFilters = {
    stop({ event, value }) {
      if (value)
        event.stopPropagation();
      return true;
    },
    prevent({ event, value }) {
      if (value)
        event.preventDefault();
      return true;
    },
    self({ event, value, element }) {
      if (value) {
        return element === event.target;
      } else {
        return true;
      }
    }
  };
  var descriptorPattern = /^(?:(?:([^.]+?)\+)?(.+?)(?:\.(.+?))?(?:@(window|document))?->)?(.+?)(?:#([^:]+?))(?::(.+))?$/;
  function parseActionDescriptorString(descriptorString) {
    const source = descriptorString.trim();
    const matches = source.match(descriptorPattern) || [];
    let eventName = matches[2];
    let keyFilter = matches[3];
    if (keyFilter && !["keydown", "keyup", "keypress"].includes(eventName)) {
      eventName += `.${keyFilter}`;
      keyFilter = "";
    }
    return {
      eventTarget: parseEventTarget(matches[4]),
      eventName,
      eventOptions: matches[7] ? parseEventOptions(matches[7]) : {},
      identifier: matches[5],
      methodName: matches[6],
      keyFilter: matches[1] || keyFilter
    };
  }
  function parseEventTarget(eventTargetName) {
    if (eventTargetName == "window") {
      return window;
    } else if (eventTargetName == "document") {
      return document;
    }
  }
  function parseEventOptions(eventOptions) {
    return eventOptions.split(":").reduce((options, token) => Object.assign(options, { [token.replace(/^!/, "")]: !/^!/.test(token) }), {});
  }
  function stringifyEventTarget(eventTarget) {
    if (eventTarget == window) {
      return "window";
    } else if (eventTarget == document) {
      return "document";
    }
  }
  function camelize(value) {
    return value.replace(/(?:[_-])([a-z0-9])/g, (_2, char) => char.toUpperCase());
  }
  function namespaceCamelize(value) {
    return camelize(value.replace(/--/g, "-").replace(/__/g, "_"));
  }
  function capitalize(value) {
    return value.charAt(0).toUpperCase() + value.slice(1);
  }
  function dasherize(value) {
    return value.replace(/([A-Z])/g, (_2, char) => `-${char.toLowerCase()}`);
  }
  function tokenize(value) {
    return value.match(/[^\s]+/g) || [];
  }
  function isSomething(object) {
    return object !== null && object !== void 0;
  }
  function hasProperty(object, property) {
    return Object.prototype.hasOwnProperty.call(object, property);
  }
  var allModifiers = ["meta", "ctrl", "alt", "shift"];
  var Action = class {
    constructor(element, index, descriptor, schema) {
      this.element = element;
      this.index = index;
      this.eventTarget = descriptor.eventTarget || element;
      this.eventName = descriptor.eventName || getDefaultEventNameForElement(element) || error("missing event name");
      this.eventOptions = descriptor.eventOptions || {};
      this.identifier = descriptor.identifier || error("missing identifier");
      this.methodName = descriptor.methodName || error("missing method name");
      this.keyFilter = descriptor.keyFilter || "";
      this.schema = schema;
    }
    static forToken(token, schema) {
      return new this(token.element, token.index, parseActionDescriptorString(token.content), schema);
    }
    toString() {
      const eventFilter = this.keyFilter ? `.${this.keyFilter}` : "";
      const eventTarget = this.eventTargetName ? `@${this.eventTargetName}` : "";
      return `${this.eventName}${eventFilter}${eventTarget}->${this.identifier}#${this.methodName}`;
    }
    shouldIgnoreKeyboardEvent(event) {
      if (!this.keyFilter) {
        return false;
      }
      const filters = this.keyFilter.split("+");
      if (this.keyFilterDissatisfied(event, filters)) {
        return true;
      }
      const standardFilter = filters.filter((key) => !allModifiers.includes(key))[0];
      if (!standardFilter) {
        return false;
      }
      if (!hasProperty(this.keyMappings, standardFilter)) {
        error(`contains unknown key filter: ${this.keyFilter}`);
      }
      return this.keyMappings[standardFilter].toLowerCase() !== event.key.toLowerCase();
    }
    shouldIgnoreMouseEvent(event) {
      if (!this.keyFilter) {
        return false;
      }
      const filters = [this.keyFilter];
      if (this.keyFilterDissatisfied(event, filters)) {
        return true;
      }
      return false;
    }
    get params() {
      const params = {};
      const pattern = new RegExp(`^data-${this.identifier}-(.+)-param$`, "i");
      for (const { name, value } of Array.from(this.element.attributes)) {
        const match2 = name.match(pattern);
        const key = match2 && match2[1];
        if (key) {
          params[camelize(key)] = typecast(value);
        }
      }
      return params;
    }
    get eventTargetName() {
      return stringifyEventTarget(this.eventTarget);
    }
    get keyMappings() {
      return this.schema.keyMappings;
    }
    keyFilterDissatisfied(event, filters) {
      const [meta, ctrl, alt, shift] = allModifiers.map((modifier) => filters.includes(modifier));
      return event.metaKey !== meta || event.ctrlKey !== ctrl || event.altKey !== alt || event.shiftKey !== shift;
    }
  };
  var defaultEventNames = {
    a: () => "click",
    button: () => "click",
    form: () => "submit",
    details: () => "toggle",
    input: (e2) => e2.getAttribute("type") == "submit" ? "click" : "input",
    select: () => "change",
    textarea: () => "input"
  };
  function getDefaultEventNameForElement(element) {
    const tagName = element.tagName.toLowerCase();
    if (tagName in defaultEventNames) {
      return defaultEventNames[tagName](element);
    }
  }
  function error(message) {
    throw new Error(message);
  }
  function typecast(value) {
    try {
      return JSON.parse(value);
    } catch (o_O) {
      return value;
    }
  }
  var Binding = class {
    constructor(context, action) {
      this.context = context;
      this.action = action;
    }
    get index() {
      return this.action.index;
    }
    get eventTarget() {
      return this.action.eventTarget;
    }
    get eventOptions() {
      return this.action.eventOptions;
    }
    get identifier() {
      return this.context.identifier;
    }
    handleEvent(event) {
      const actionEvent = this.prepareActionEvent(event);
      if (this.willBeInvokedByEvent(event) && this.applyEventModifiers(actionEvent)) {
        this.invokeWithEvent(actionEvent);
      }
    }
    get eventName() {
      return this.action.eventName;
    }
    get method() {
      const method = this.controller[this.methodName];
      if (typeof method == "function") {
        return method;
      }
      throw new Error(`Action "${this.action}" references undefined method "${this.methodName}"`);
    }
    applyEventModifiers(event) {
      const { element } = this.action;
      const { actionDescriptorFilters } = this.context.application;
      const { controller } = this.context;
      let passes = true;
      for (const [name, value] of Object.entries(this.eventOptions)) {
        if (name in actionDescriptorFilters) {
          const filter = actionDescriptorFilters[name];
          passes = passes && filter({ name, value, event, element, controller });
        } else {
          continue;
        }
      }
      return passes;
    }
    prepareActionEvent(event) {
      return Object.assign(event, { params: this.action.params });
    }
    invokeWithEvent(event) {
      const { target, currentTarget } = event;
      try {
        this.method.call(this.controller, event);
        this.context.logDebugActivity(this.methodName, { event, target, currentTarget, action: this.methodName });
      } catch (error3) {
        const { identifier, controller, element, index } = this;
        const detail = { identifier, controller, element, index, event };
        this.context.handleError(error3, `invoking action "${this.action}"`, detail);
      }
    }
    willBeInvokedByEvent(event) {
      const eventTarget = event.target;
      if (event instanceof KeyboardEvent && this.action.shouldIgnoreKeyboardEvent(event)) {
        return false;
      }
      if (event instanceof MouseEvent && this.action.shouldIgnoreMouseEvent(event)) {
        return false;
      }
      if (this.element === eventTarget) {
        return true;
      } else if (eventTarget instanceof Element && this.element.contains(eventTarget)) {
        return this.scope.containsElement(eventTarget);
      } else {
        return this.scope.containsElement(this.action.element);
      }
    }
    get controller() {
      return this.context.controller;
    }
    get methodName() {
      return this.action.methodName;
    }
    get element() {
      return this.scope.element;
    }
    get scope() {
      return this.context.scope;
    }
  };
  var ElementObserver = class {
    constructor(element, delegate) {
      this.mutationObserverInit = { attributes: true, childList: true, subtree: true };
      this.element = element;
      this.started = false;
      this.delegate = delegate;
      this.elements = /* @__PURE__ */ new Set();
      this.mutationObserver = new MutationObserver((mutations) => this.processMutations(mutations));
    }
    start() {
      if (!this.started) {
        this.started = true;
        this.mutationObserver.observe(this.element, this.mutationObserverInit);
        this.refresh();
      }
    }
    pause(callback2) {
      if (this.started) {
        this.mutationObserver.disconnect();
        this.started = false;
      }
      callback2();
      if (!this.started) {
        this.mutationObserver.observe(this.element, this.mutationObserverInit);
        this.started = true;
      }
    }
    stop() {
      if (this.started) {
        this.mutationObserver.takeRecords();
        this.mutationObserver.disconnect();
        this.started = false;
      }
    }
    refresh() {
      if (this.started) {
        const matches = new Set(this.matchElementsInTree());
        for (const element of Array.from(this.elements)) {
          if (!matches.has(element)) {
            this.removeElement(element);
          }
        }
        for (const element of Array.from(matches)) {
          this.addElement(element);
        }
      }
    }
    processMutations(mutations) {
      if (this.started) {
        for (const mutation of mutations) {
          this.processMutation(mutation);
        }
      }
    }
    processMutation(mutation) {
      if (mutation.type == "attributes") {
        this.processAttributeChange(mutation.target, mutation.attributeName);
      } else if (mutation.type == "childList") {
        this.processRemovedNodes(mutation.removedNodes);
        this.processAddedNodes(mutation.addedNodes);
      }
    }
    processAttributeChange(element, attributeName) {
      if (this.elements.has(element)) {
        if (this.delegate.elementAttributeChanged && this.matchElement(element)) {
          this.delegate.elementAttributeChanged(element, attributeName);
        } else {
          this.removeElement(element);
        }
      } else if (this.matchElement(element)) {
        this.addElement(element);
      }
    }
    processRemovedNodes(nodes) {
      for (const node of Array.from(nodes)) {
        const element = this.elementFromNode(node);
        if (element) {
          this.processTree(element, this.removeElement);
        }
      }
    }
    processAddedNodes(nodes) {
      for (const node of Array.from(nodes)) {
        const element = this.elementFromNode(node);
        if (element && this.elementIsActive(element)) {
          this.processTree(element, this.addElement);
        }
      }
    }
    matchElement(element) {
      return this.delegate.matchElement(element);
    }
    matchElementsInTree(tree = this.element) {
      return this.delegate.matchElementsInTree(tree);
    }
    processTree(tree, processor) {
      for (const element of this.matchElementsInTree(tree)) {
        processor.call(this, element);
      }
    }
    elementFromNode(node) {
      if (node.nodeType == Node.ELEMENT_NODE) {
        return node;
      }
    }
    elementIsActive(element) {
      if (element.isConnected != this.element.isConnected) {
        return false;
      } else {
        return this.element.contains(element);
      }
    }
    addElement(element) {
      if (!this.elements.has(element)) {
        if (this.elementIsActive(element)) {
          this.elements.add(element);
          if (this.delegate.elementMatched) {
            this.delegate.elementMatched(element);
          }
        }
      }
    }
    removeElement(element) {
      if (this.elements.has(element)) {
        this.elements.delete(element);
        if (this.delegate.elementUnmatched) {
          this.delegate.elementUnmatched(element);
        }
      }
    }
  };
  var AttributeObserver = class {
    constructor(element, attributeName, delegate) {
      this.attributeName = attributeName;
      this.delegate = delegate;
      this.elementObserver = new ElementObserver(element, this);
    }
    get element() {
      return this.elementObserver.element;
    }
    get selector() {
      return `[${this.attributeName}]`;
    }
    start() {
      this.elementObserver.start();
    }
    pause(callback2) {
      this.elementObserver.pause(callback2);
    }
    stop() {
      this.elementObserver.stop();
    }
    refresh() {
      this.elementObserver.refresh();
    }
    get started() {
      return this.elementObserver.started;
    }
    matchElement(element) {
      return element.hasAttribute(this.attributeName);
    }
    matchElementsInTree(tree) {
      const match2 = this.matchElement(tree) ? [tree] : [];
      const matches = Array.from(tree.querySelectorAll(this.selector));
      return match2.concat(matches);
    }
    elementMatched(element) {
      if (this.delegate.elementMatchedAttribute) {
        this.delegate.elementMatchedAttribute(element, this.attributeName);
      }
    }
    elementUnmatched(element) {
      if (this.delegate.elementUnmatchedAttribute) {
        this.delegate.elementUnmatchedAttribute(element, this.attributeName);
      }
    }
    elementAttributeChanged(element, attributeName) {
      if (this.delegate.elementAttributeValueChanged && this.attributeName == attributeName) {
        this.delegate.elementAttributeValueChanged(element, attributeName);
      }
    }
  };
  function add(map3, key, value) {
    fetch2(map3, key).add(value);
  }
  function del(map3, key, value) {
    fetch2(map3, key).delete(value);
    prune(map3, key);
  }
  function fetch2(map3, key) {
    let values = map3.get(key);
    if (!values) {
      values = /* @__PURE__ */ new Set();
      map3.set(key, values);
    }
    return values;
  }
  function prune(map3, key) {
    const values = map3.get(key);
    if (values != null && values.size == 0) {
      map3.delete(key);
    }
  }
  var Multimap = class {
    constructor() {
      this.valuesByKey = /* @__PURE__ */ new Map();
    }
    get keys() {
      return Array.from(this.valuesByKey.keys());
    }
    get values() {
      const sets = Array.from(this.valuesByKey.values());
      return sets.reduce((values, set2) => values.concat(Array.from(set2)), []);
    }
    get size() {
      const sets = Array.from(this.valuesByKey.values());
      return sets.reduce((size, set2) => size + set2.size, 0);
    }
    add(key, value) {
      add(this.valuesByKey, key, value);
    }
    delete(key, value) {
      del(this.valuesByKey, key, value);
    }
    has(key, value) {
      const values = this.valuesByKey.get(key);
      return values != null && values.has(value);
    }
    hasKey(key) {
      return this.valuesByKey.has(key);
    }
    hasValue(value) {
      const sets = Array.from(this.valuesByKey.values());
      return sets.some((set2) => set2.has(value));
    }
    getValuesForKey(key) {
      const values = this.valuesByKey.get(key);
      return values ? Array.from(values) : [];
    }
    getKeysForValue(value) {
      return Array.from(this.valuesByKey).filter(([_key, values]) => values.has(value)).map(([key, _values]) => key);
    }
  };
  var SelectorObserver = class {
    constructor(element, selector, delegate, details) {
      this._selector = selector;
      this.details = details;
      this.elementObserver = new ElementObserver(element, this);
      this.delegate = delegate;
      this.matchesByElement = new Multimap();
    }
    get started() {
      return this.elementObserver.started;
    }
    get selector() {
      return this._selector;
    }
    set selector(selector) {
      this._selector = selector;
      this.refresh();
    }
    start() {
      this.elementObserver.start();
    }
    pause(callback2) {
      this.elementObserver.pause(callback2);
    }
    stop() {
      this.elementObserver.stop();
    }
    refresh() {
      this.elementObserver.refresh();
    }
    get element() {
      return this.elementObserver.element;
    }
    matchElement(element) {
      const { selector } = this;
      if (selector) {
        const matches = element.matches(selector);
        if (this.delegate.selectorMatchElement) {
          return matches && this.delegate.selectorMatchElement(element, this.details);
        }
        return matches;
      } else {
        return false;
      }
    }
    matchElementsInTree(tree) {
      const { selector } = this;
      if (selector) {
        const match2 = this.matchElement(tree) ? [tree] : [];
        const matches = Array.from(tree.querySelectorAll(selector)).filter((match3) => this.matchElement(match3));
        return match2.concat(matches);
      } else {
        return [];
      }
    }
    elementMatched(element) {
      const { selector } = this;
      if (selector) {
        this.selectorMatched(element, selector);
      }
    }
    elementUnmatched(element) {
      const selectors = this.matchesByElement.getKeysForValue(element);
      for (const selector of selectors) {
        this.selectorUnmatched(element, selector);
      }
    }
    elementAttributeChanged(element, _attributeName) {
      const { selector } = this;
      if (selector) {
        const matches = this.matchElement(element);
        const matchedBefore = this.matchesByElement.has(selector, element);
        if (matches && !matchedBefore) {
          this.selectorMatched(element, selector);
        } else if (!matches && matchedBefore) {
          this.selectorUnmatched(element, selector);
        }
      }
    }
    selectorMatched(element, selector) {
      this.delegate.selectorMatched(element, selector, this.details);
      this.matchesByElement.add(selector, element);
    }
    selectorUnmatched(element, selector) {
      this.delegate.selectorUnmatched(element, selector, this.details);
      this.matchesByElement.delete(selector, element);
    }
  };
  var StringMapObserver = class {
    constructor(element, delegate) {
      this.element = element;
      this.delegate = delegate;
      this.started = false;
      this.stringMap = /* @__PURE__ */ new Map();
      this.mutationObserver = new MutationObserver((mutations) => this.processMutations(mutations));
    }
    start() {
      if (!this.started) {
        this.started = true;
        this.mutationObserver.observe(this.element, { attributes: true, attributeOldValue: true });
        this.refresh();
      }
    }
    stop() {
      if (this.started) {
        this.mutationObserver.takeRecords();
        this.mutationObserver.disconnect();
        this.started = false;
      }
    }
    refresh() {
      if (this.started) {
        for (const attributeName of this.knownAttributeNames) {
          this.refreshAttribute(attributeName, null);
        }
      }
    }
    processMutations(mutations) {
      if (this.started) {
        for (const mutation of mutations) {
          this.processMutation(mutation);
        }
      }
    }
    processMutation(mutation) {
      const attributeName = mutation.attributeName;
      if (attributeName) {
        this.refreshAttribute(attributeName, mutation.oldValue);
      }
    }
    refreshAttribute(attributeName, oldValue) {
      const key = this.delegate.getStringMapKeyForAttribute(attributeName);
      if (key != null) {
        if (!this.stringMap.has(attributeName)) {
          this.stringMapKeyAdded(key, attributeName);
        }
        const value = this.element.getAttribute(attributeName);
        if (this.stringMap.get(attributeName) != value) {
          this.stringMapValueChanged(value, key, oldValue);
        }
        if (value == null) {
          const oldValue2 = this.stringMap.get(attributeName);
          this.stringMap.delete(attributeName);
          if (oldValue2)
            this.stringMapKeyRemoved(key, attributeName, oldValue2);
        } else {
          this.stringMap.set(attributeName, value);
        }
      }
    }
    stringMapKeyAdded(key, attributeName) {
      if (this.delegate.stringMapKeyAdded) {
        this.delegate.stringMapKeyAdded(key, attributeName);
      }
    }
    stringMapValueChanged(value, key, oldValue) {
      if (this.delegate.stringMapValueChanged) {
        this.delegate.stringMapValueChanged(value, key, oldValue);
      }
    }
    stringMapKeyRemoved(key, attributeName, oldValue) {
      if (this.delegate.stringMapKeyRemoved) {
        this.delegate.stringMapKeyRemoved(key, attributeName, oldValue);
      }
    }
    get knownAttributeNames() {
      return Array.from(new Set(this.currentAttributeNames.concat(this.recordedAttributeNames)));
    }
    get currentAttributeNames() {
      return Array.from(this.element.attributes).map((attribute) => attribute.name);
    }
    get recordedAttributeNames() {
      return Array.from(this.stringMap.keys());
    }
  };
  var TokenListObserver = class {
    constructor(element, attributeName, delegate) {
      this.attributeObserver = new AttributeObserver(element, attributeName, this);
      this.delegate = delegate;
      this.tokensByElement = new Multimap();
    }
    get started() {
      return this.attributeObserver.started;
    }
    start() {
      this.attributeObserver.start();
    }
    pause(callback2) {
      this.attributeObserver.pause(callback2);
    }
    stop() {
      this.attributeObserver.stop();
    }
    refresh() {
      this.attributeObserver.refresh();
    }
    get element() {
      return this.attributeObserver.element;
    }
    get attributeName() {
      return this.attributeObserver.attributeName;
    }
    elementMatchedAttribute(element) {
      this.tokensMatched(this.readTokensForElement(element));
    }
    elementAttributeValueChanged(element) {
      const [unmatchedTokens, matchedTokens] = this.refreshTokensForElement(element);
      this.tokensUnmatched(unmatchedTokens);
      this.tokensMatched(matchedTokens);
    }
    elementUnmatchedAttribute(element) {
      this.tokensUnmatched(this.tokensByElement.getValuesForKey(element));
    }
    tokensMatched(tokens) {
      tokens.forEach((token) => this.tokenMatched(token));
    }
    tokensUnmatched(tokens) {
      tokens.forEach((token) => this.tokenUnmatched(token));
    }
    tokenMatched(token) {
      this.delegate.tokenMatched(token);
      this.tokensByElement.add(token.element, token);
    }
    tokenUnmatched(token) {
      this.delegate.tokenUnmatched(token);
      this.tokensByElement.delete(token.element, token);
    }
    refreshTokensForElement(element) {
      const previousTokens = this.tokensByElement.getValuesForKey(element);
      const currentTokens = this.readTokensForElement(element);
      const firstDifferingIndex = zip(previousTokens, currentTokens).findIndex(([previousToken, currentToken]) => !tokensAreEqual(previousToken, currentToken));
      if (firstDifferingIndex == -1) {
        return [[], []];
      } else {
        return [previousTokens.slice(firstDifferingIndex), currentTokens.slice(firstDifferingIndex)];
      }
    }
    readTokensForElement(element) {
      const attributeName = this.attributeName;
      const tokenString = element.getAttribute(attributeName) || "";
      return parseTokenString(tokenString, element, attributeName);
    }
  };
  function parseTokenString(tokenString, element, attributeName) {
    return tokenString.trim().split(/\s+/).filter((content) => content.length).map((content, index) => ({ element, attributeName, content, index }));
  }
  function zip(left2, right2) {
    const length = Math.max(left2.length, right2.length);
    return Array.from({ length }, (_2, index) => [left2[index], right2[index]]);
  }
  function tokensAreEqual(left2, right2) {
    return left2 && right2 && left2.index == right2.index && left2.content == right2.content;
  }
  var ValueListObserver = class {
    constructor(element, attributeName, delegate) {
      this.tokenListObserver = new TokenListObserver(element, attributeName, this);
      this.delegate = delegate;
      this.parseResultsByToken = /* @__PURE__ */ new WeakMap();
      this.valuesByTokenByElement = /* @__PURE__ */ new WeakMap();
    }
    get started() {
      return this.tokenListObserver.started;
    }
    start() {
      this.tokenListObserver.start();
    }
    stop() {
      this.tokenListObserver.stop();
    }
    refresh() {
      this.tokenListObserver.refresh();
    }
    get element() {
      return this.tokenListObserver.element;
    }
    get attributeName() {
      return this.tokenListObserver.attributeName;
    }
    tokenMatched(token) {
      const { element } = token;
      const { value } = this.fetchParseResultForToken(token);
      if (value) {
        this.fetchValuesByTokenForElement(element).set(token, value);
        this.delegate.elementMatchedValue(element, value);
      }
    }
    tokenUnmatched(token) {
      const { element } = token;
      const { value } = this.fetchParseResultForToken(token);
      if (value) {
        this.fetchValuesByTokenForElement(element).delete(token);
        this.delegate.elementUnmatchedValue(element, value);
      }
    }
    fetchParseResultForToken(token) {
      let parseResult = this.parseResultsByToken.get(token);
      if (!parseResult) {
        parseResult = this.parseToken(token);
        this.parseResultsByToken.set(token, parseResult);
      }
      return parseResult;
    }
    fetchValuesByTokenForElement(element) {
      let valuesByToken = this.valuesByTokenByElement.get(element);
      if (!valuesByToken) {
        valuesByToken = /* @__PURE__ */ new Map();
        this.valuesByTokenByElement.set(element, valuesByToken);
      }
      return valuesByToken;
    }
    parseToken(token) {
      try {
        const value = this.delegate.parseValueForToken(token);
        return { value };
      } catch (error3) {
        return { error: error3 };
      }
    }
  };
  var BindingObserver = class {
    constructor(context, delegate) {
      this.context = context;
      this.delegate = delegate;
      this.bindingsByAction = /* @__PURE__ */ new Map();
    }
    start() {
      if (!this.valueListObserver) {
        this.valueListObserver = new ValueListObserver(this.element, this.actionAttribute, this);
        this.valueListObserver.start();
      }
    }
    stop() {
      if (this.valueListObserver) {
        this.valueListObserver.stop();
        delete this.valueListObserver;
        this.disconnectAllActions();
      }
    }
    get element() {
      return this.context.element;
    }
    get identifier() {
      return this.context.identifier;
    }
    get actionAttribute() {
      return this.schema.actionAttribute;
    }
    get schema() {
      return this.context.schema;
    }
    get bindings() {
      return Array.from(this.bindingsByAction.values());
    }
    connectAction(action) {
      const binding = new Binding(this.context, action);
      this.bindingsByAction.set(action, binding);
      this.delegate.bindingConnected(binding);
    }
    disconnectAction(action) {
      const binding = this.bindingsByAction.get(action);
      if (binding) {
        this.bindingsByAction.delete(action);
        this.delegate.bindingDisconnected(binding);
      }
    }
    disconnectAllActions() {
      this.bindings.forEach((binding) => this.delegate.bindingDisconnected(binding, true));
      this.bindingsByAction.clear();
    }
    parseValueForToken(token) {
      const action = Action.forToken(token, this.schema);
      if (action.identifier == this.identifier) {
        return action;
      }
    }
    elementMatchedValue(element, action) {
      this.connectAction(action);
    }
    elementUnmatchedValue(element, action) {
      this.disconnectAction(action);
    }
  };
  var ValueObserver = class {
    constructor(context, receiver) {
      this.context = context;
      this.receiver = receiver;
      this.stringMapObserver = new StringMapObserver(this.element, this);
      this.valueDescriptorMap = this.controller.valueDescriptorMap;
    }
    start() {
      this.stringMapObserver.start();
      this.invokeChangedCallbacksForDefaultValues();
    }
    stop() {
      this.stringMapObserver.stop();
    }
    get element() {
      return this.context.element;
    }
    get controller() {
      return this.context.controller;
    }
    getStringMapKeyForAttribute(attributeName) {
      if (attributeName in this.valueDescriptorMap) {
        return this.valueDescriptorMap[attributeName].name;
      }
    }
    stringMapKeyAdded(key, attributeName) {
      const descriptor = this.valueDescriptorMap[attributeName];
      if (!this.hasValue(key)) {
        this.invokeChangedCallback(key, descriptor.writer(this.receiver[key]), descriptor.writer(descriptor.defaultValue));
      }
    }
    stringMapValueChanged(value, name, oldValue) {
      const descriptor = this.valueDescriptorNameMap[name];
      if (value === null)
        return;
      if (oldValue === null) {
        oldValue = descriptor.writer(descriptor.defaultValue);
      }
      this.invokeChangedCallback(name, value, oldValue);
    }
    stringMapKeyRemoved(key, attributeName, oldValue) {
      const descriptor = this.valueDescriptorNameMap[key];
      if (this.hasValue(key)) {
        this.invokeChangedCallback(key, descriptor.writer(this.receiver[key]), oldValue);
      } else {
        this.invokeChangedCallback(key, descriptor.writer(descriptor.defaultValue), oldValue);
      }
    }
    invokeChangedCallbacksForDefaultValues() {
      for (const { key, name, defaultValue, writer } of this.valueDescriptors) {
        if (defaultValue != void 0 && !this.controller.data.has(key)) {
          this.invokeChangedCallback(name, writer(defaultValue), void 0);
        }
      }
    }
    invokeChangedCallback(name, rawValue, rawOldValue) {
      const changedMethodName = `${name}Changed`;
      const changedMethod = this.receiver[changedMethodName];
      if (typeof changedMethod == "function") {
        const descriptor = this.valueDescriptorNameMap[name];
        try {
          const value = descriptor.reader(rawValue);
          let oldValue = rawOldValue;
          if (rawOldValue) {
            oldValue = descriptor.reader(rawOldValue);
          }
          changedMethod.call(this.receiver, value, oldValue);
        } catch (error3) {
          if (error3 instanceof TypeError) {
            error3.message = `Stimulus Value "${this.context.identifier}.${descriptor.name}" - ${error3.message}`;
          }
          throw error3;
        }
      }
    }
    get valueDescriptors() {
      const { valueDescriptorMap } = this;
      return Object.keys(valueDescriptorMap).map((key) => valueDescriptorMap[key]);
    }
    get valueDescriptorNameMap() {
      const descriptors2 = {};
      Object.keys(this.valueDescriptorMap).forEach((key) => {
        const descriptor = this.valueDescriptorMap[key];
        descriptors2[descriptor.name] = descriptor;
      });
      return descriptors2;
    }
    hasValue(attributeName) {
      const descriptor = this.valueDescriptorNameMap[attributeName];
      const hasMethodName = `has${capitalize(descriptor.name)}`;
      return this.receiver[hasMethodName];
    }
  };
  var TargetObserver = class {
    constructor(context, delegate) {
      this.context = context;
      this.delegate = delegate;
      this.targetsByName = new Multimap();
    }
    start() {
      if (!this.tokenListObserver) {
        this.tokenListObserver = new TokenListObserver(this.element, this.attributeName, this);
        this.tokenListObserver.start();
      }
    }
    stop() {
      if (this.tokenListObserver) {
        this.disconnectAllTargets();
        this.tokenListObserver.stop();
        delete this.tokenListObserver;
      }
    }
    tokenMatched({ element, content: name }) {
      if (this.scope.containsElement(element)) {
        this.connectTarget(element, name);
      }
    }
    tokenUnmatched({ element, content: name }) {
      this.disconnectTarget(element, name);
    }
    connectTarget(element, name) {
      var _a;
      if (!this.targetsByName.has(name, element)) {
        this.targetsByName.add(name, element);
        (_a = this.tokenListObserver) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.targetConnected(element, name));
      }
    }
    disconnectTarget(element, name) {
      var _a;
      if (this.targetsByName.has(name, element)) {
        this.targetsByName.delete(name, element);
        (_a = this.tokenListObserver) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.targetDisconnected(element, name));
      }
    }
    disconnectAllTargets() {
      for (const name of this.targetsByName.keys) {
        for (const element of this.targetsByName.getValuesForKey(name)) {
          this.disconnectTarget(element, name);
        }
      }
    }
    get attributeName() {
      return `data-${this.context.identifier}-target`;
    }
    get element() {
      return this.context.element;
    }
    get scope() {
      return this.context.scope;
    }
  };
  function readInheritableStaticArrayValues(constructor, propertyName) {
    const ancestors = getAncestorsForConstructor(constructor);
    return Array.from(ancestors.reduce((values, constructor2) => {
      getOwnStaticArrayValues(constructor2, propertyName).forEach((name) => values.add(name));
      return values;
    }, /* @__PURE__ */ new Set()));
  }
  function readInheritableStaticObjectPairs(constructor, propertyName) {
    const ancestors = getAncestorsForConstructor(constructor);
    return ancestors.reduce((pairs, constructor2) => {
      pairs.push(...getOwnStaticObjectPairs(constructor2, propertyName));
      return pairs;
    }, []);
  }
  function getAncestorsForConstructor(constructor) {
    const ancestors = [];
    while (constructor) {
      ancestors.push(constructor);
      constructor = Object.getPrototypeOf(constructor);
    }
    return ancestors.reverse();
  }
  function getOwnStaticArrayValues(constructor, propertyName) {
    const definition = constructor[propertyName];
    return Array.isArray(definition) ? definition : [];
  }
  function getOwnStaticObjectPairs(constructor, propertyName) {
    const definition = constructor[propertyName];
    return definition ? Object.keys(definition).map((key) => [key, definition[key]]) : [];
  }
  var OutletObserver = class {
    constructor(context, delegate) {
      this.started = false;
      this.context = context;
      this.delegate = delegate;
      this.outletsByName = new Multimap();
      this.outletElementsByName = new Multimap();
      this.selectorObserverMap = /* @__PURE__ */ new Map();
      this.attributeObserverMap = /* @__PURE__ */ new Map();
    }
    start() {
      if (!this.started) {
        this.outletDefinitions.forEach((outletName) => {
          this.setupSelectorObserverForOutlet(outletName);
          this.setupAttributeObserverForOutlet(outletName);
        });
        this.started = true;
        this.dependentContexts.forEach((context) => context.refresh());
      }
    }
    refresh() {
      this.selectorObserverMap.forEach((observer) => observer.refresh());
      this.attributeObserverMap.forEach((observer) => observer.refresh());
    }
    stop() {
      if (this.started) {
        this.started = false;
        this.disconnectAllOutlets();
        this.stopSelectorObservers();
        this.stopAttributeObservers();
      }
    }
    stopSelectorObservers() {
      if (this.selectorObserverMap.size > 0) {
        this.selectorObserverMap.forEach((observer) => observer.stop());
        this.selectorObserverMap.clear();
      }
    }
    stopAttributeObservers() {
      if (this.attributeObserverMap.size > 0) {
        this.attributeObserverMap.forEach((observer) => observer.stop());
        this.attributeObserverMap.clear();
      }
    }
    selectorMatched(element, _selector, { outletName }) {
      const outlet = this.getOutlet(element, outletName);
      if (outlet) {
        this.connectOutlet(outlet, element, outletName);
      }
    }
    selectorUnmatched(element, _selector, { outletName }) {
      const outlet = this.getOutletFromMap(element, outletName);
      if (outlet) {
        this.disconnectOutlet(outlet, element, outletName);
      }
    }
    selectorMatchElement(element, { outletName }) {
      const selector = this.selector(outletName);
      const hasOutlet = this.hasOutlet(element, outletName);
      const hasOutletController = element.matches(`[${this.schema.controllerAttribute}~=${outletName}]`);
      if (selector) {
        return hasOutlet && hasOutletController && element.matches(selector);
      } else {
        return false;
      }
    }
    elementMatchedAttribute(_element, attributeName) {
      const outletName = this.getOutletNameFromOutletAttributeName(attributeName);
      if (outletName) {
        this.updateSelectorObserverForOutlet(outletName);
      }
    }
    elementAttributeValueChanged(_element, attributeName) {
      const outletName = this.getOutletNameFromOutletAttributeName(attributeName);
      if (outletName) {
        this.updateSelectorObserverForOutlet(outletName);
      }
    }
    elementUnmatchedAttribute(_element, attributeName) {
      const outletName = this.getOutletNameFromOutletAttributeName(attributeName);
      if (outletName) {
        this.updateSelectorObserverForOutlet(outletName);
      }
    }
    connectOutlet(outlet, element, outletName) {
      var _a;
      if (!this.outletElementsByName.has(outletName, element)) {
        this.outletsByName.add(outletName, outlet);
        this.outletElementsByName.add(outletName, element);
        (_a = this.selectorObserverMap.get(outletName)) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.outletConnected(outlet, element, outletName));
      }
    }
    disconnectOutlet(outlet, element, outletName) {
      var _a;
      if (this.outletElementsByName.has(outletName, element)) {
        this.outletsByName.delete(outletName, outlet);
        this.outletElementsByName.delete(outletName, element);
        (_a = this.selectorObserverMap.get(outletName)) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.outletDisconnected(outlet, element, outletName));
      }
    }
    disconnectAllOutlets() {
      for (const outletName of this.outletElementsByName.keys) {
        for (const element of this.outletElementsByName.getValuesForKey(outletName)) {
          for (const outlet of this.outletsByName.getValuesForKey(outletName)) {
            this.disconnectOutlet(outlet, element, outletName);
          }
        }
      }
    }
    updateSelectorObserverForOutlet(outletName) {
      const observer = this.selectorObserverMap.get(outletName);
      if (observer) {
        observer.selector = this.selector(outletName);
      }
    }
    setupSelectorObserverForOutlet(outletName) {
      const selector = this.selector(outletName);
      const selectorObserver = new SelectorObserver(document.body, selector, this, { outletName });
      this.selectorObserverMap.set(outletName, selectorObserver);
      selectorObserver.start();
    }
    setupAttributeObserverForOutlet(outletName) {
      const attributeName = this.attributeNameForOutletName(outletName);
      const attributeObserver = new AttributeObserver(this.scope.element, attributeName, this);
      this.attributeObserverMap.set(outletName, attributeObserver);
      attributeObserver.start();
    }
    selector(outletName) {
      return this.scope.outlets.getSelectorForOutletName(outletName);
    }
    attributeNameForOutletName(outletName) {
      return this.scope.schema.outletAttributeForScope(this.identifier, outletName);
    }
    getOutletNameFromOutletAttributeName(attributeName) {
      return this.outletDefinitions.find((outletName) => this.attributeNameForOutletName(outletName) === attributeName);
    }
    get outletDependencies() {
      const dependencies = new Multimap();
      this.router.modules.forEach((module) => {
        const constructor = module.definition.controllerConstructor;
        const outlets = readInheritableStaticArrayValues(constructor, "outlets");
        outlets.forEach((outlet) => dependencies.add(outlet, module.identifier));
      });
      return dependencies;
    }
    get outletDefinitions() {
      return this.outletDependencies.getKeysForValue(this.identifier);
    }
    get dependentControllerIdentifiers() {
      return this.outletDependencies.getValuesForKey(this.identifier);
    }
    get dependentContexts() {
      const identifiers = this.dependentControllerIdentifiers;
      return this.router.contexts.filter((context) => identifiers.includes(context.identifier));
    }
    hasOutlet(element, outletName) {
      return !!this.getOutlet(element, outletName) || !!this.getOutletFromMap(element, outletName);
    }
    getOutlet(element, outletName) {
      return this.application.getControllerForElementAndIdentifier(element, outletName);
    }
    getOutletFromMap(element, outletName) {
      return this.outletsByName.getValuesForKey(outletName).find((outlet) => outlet.element === element);
    }
    get scope() {
      return this.context.scope;
    }
    get schema() {
      return this.context.schema;
    }
    get identifier() {
      return this.context.identifier;
    }
    get application() {
      return this.context.application;
    }
    get router() {
      return this.application.router;
    }
  };
  var Context = class {
    constructor(module, scope) {
      this.logDebugActivity = (functionName, detail = {}) => {
        const { identifier, controller, element } = this;
        detail = Object.assign({ identifier, controller, element }, detail);
        this.application.logDebugActivity(this.identifier, functionName, detail);
      };
      this.module = module;
      this.scope = scope;
      this.controller = new module.controllerConstructor(this);
      this.bindingObserver = new BindingObserver(this, this.dispatcher);
      this.valueObserver = new ValueObserver(this, this.controller);
      this.targetObserver = new TargetObserver(this, this);
      this.outletObserver = new OutletObserver(this, this);
      try {
        this.controller.initialize();
        this.logDebugActivity("initialize");
      } catch (error3) {
        this.handleError(error3, "initializing controller");
      }
    }
    connect() {
      this.bindingObserver.start();
      this.valueObserver.start();
      this.targetObserver.start();
      this.outletObserver.start();
      try {
        this.controller.connect();
        this.logDebugActivity("connect");
      } catch (error3) {
        this.handleError(error3, "connecting controller");
      }
    }
    refresh() {
      this.outletObserver.refresh();
    }
    disconnect() {
      try {
        this.controller.disconnect();
        this.logDebugActivity("disconnect");
      } catch (error3) {
        this.handleError(error3, "disconnecting controller");
      }
      this.outletObserver.stop();
      this.targetObserver.stop();
      this.valueObserver.stop();
      this.bindingObserver.stop();
    }
    get application() {
      return this.module.application;
    }
    get identifier() {
      return this.module.identifier;
    }
    get schema() {
      return this.application.schema;
    }
    get dispatcher() {
      return this.application.dispatcher;
    }
    get element() {
      return this.scope.element;
    }
    get parentElement() {
      return this.element.parentElement;
    }
    handleError(error3, message, detail = {}) {
      const { identifier, controller, element } = this;
      detail = Object.assign({ identifier, controller, element }, detail);
      this.application.handleError(error3, `Error ${message}`, detail);
    }
    targetConnected(element, name) {
      this.invokeControllerMethod(`${name}TargetConnected`, element);
    }
    targetDisconnected(element, name) {
      this.invokeControllerMethod(`${name}TargetDisconnected`, element);
    }
    outletConnected(outlet, element, name) {
      this.invokeControllerMethod(`${namespaceCamelize(name)}OutletConnected`, outlet, element);
    }
    outletDisconnected(outlet, element, name) {
      this.invokeControllerMethod(`${namespaceCamelize(name)}OutletDisconnected`, outlet, element);
    }
    invokeControllerMethod(methodName, ...args) {
      const controller = this.controller;
      if (typeof controller[methodName] == "function") {
        controller[methodName](...args);
      }
    }
  };
  function bless(constructor) {
    return shadow(constructor, getBlessedProperties(constructor));
  }
  function shadow(constructor, properties) {
    const shadowConstructor = extend2(constructor);
    const shadowProperties = getShadowProperties(constructor.prototype, properties);
    Object.defineProperties(shadowConstructor.prototype, shadowProperties);
    return shadowConstructor;
  }
  function getBlessedProperties(constructor) {
    const blessings = readInheritableStaticArrayValues(constructor, "blessings");
    return blessings.reduce((blessedProperties, blessing) => {
      const properties = blessing(constructor);
      for (const key in properties) {
        const descriptor = blessedProperties[key] || {};
        blessedProperties[key] = Object.assign(descriptor, properties[key]);
      }
      return blessedProperties;
    }, {});
  }
  function getShadowProperties(prototype, properties) {
    return getOwnKeys(properties).reduce((shadowProperties, key) => {
      const descriptor = getShadowedDescriptor(prototype, properties, key);
      if (descriptor) {
        Object.assign(shadowProperties, { [key]: descriptor });
      }
      return shadowProperties;
    }, {});
  }
  function getShadowedDescriptor(prototype, properties, key) {
    const shadowingDescriptor = Object.getOwnPropertyDescriptor(prototype, key);
    const shadowedByValue = shadowingDescriptor && "value" in shadowingDescriptor;
    if (!shadowedByValue) {
      const descriptor = Object.getOwnPropertyDescriptor(properties, key).value;
      if (shadowingDescriptor) {
        descriptor.get = shadowingDescriptor.get || descriptor.get;
        descriptor.set = shadowingDescriptor.set || descriptor.set;
      }
      return descriptor;
    }
  }
  var getOwnKeys = (() => {
    if (typeof Object.getOwnPropertySymbols == "function") {
      return (object) => [...Object.getOwnPropertyNames(object), ...Object.getOwnPropertySymbols(object)];
    } else {
      return Object.getOwnPropertyNames;
    }
  })();
  var extend2 = (() => {
    function extendWithReflect(constructor) {
      function extended() {
        return Reflect.construct(constructor, arguments, new.target);
      }
      extended.prototype = Object.create(constructor.prototype, {
        constructor: { value: extended }
      });
      Reflect.setPrototypeOf(extended, constructor);
      return extended;
    }
    function testReflectExtension() {
      const a2 = function() {
        this.a.call(this);
      };
      const b2 = extendWithReflect(a2);
      b2.prototype.a = function() {
      };
      return new b2();
    }
    try {
      testReflectExtension();
      return extendWithReflect;
    } catch (error3) {
      return (constructor) => class extended extends constructor {
      };
    }
  })();
  function blessDefinition(definition) {
    return {
      identifier: definition.identifier,
      controllerConstructor: bless(definition.controllerConstructor)
    };
  }
  var Module = class {
    constructor(application2, definition) {
      this.application = application2;
      this.definition = blessDefinition(definition);
      this.contextsByScope = /* @__PURE__ */ new WeakMap();
      this.connectedContexts = /* @__PURE__ */ new Set();
    }
    get identifier() {
      return this.definition.identifier;
    }
    get controllerConstructor() {
      return this.definition.controllerConstructor;
    }
    get contexts() {
      return Array.from(this.connectedContexts);
    }
    connectContextForScope(scope) {
      const context = this.fetchContextForScope(scope);
      this.connectedContexts.add(context);
      context.connect();
    }
    disconnectContextForScope(scope) {
      const context = this.contextsByScope.get(scope);
      if (context) {
        this.connectedContexts.delete(context);
        context.disconnect();
      }
    }
    fetchContextForScope(scope) {
      let context = this.contextsByScope.get(scope);
      if (!context) {
        context = new Context(this, scope);
        this.contextsByScope.set(scope, context);
      }
      return context;
    }
  };
  var ClassMap = class {
    constructor(scope) {
      this.scope = scope;
    }
    has(name) {
      return this.data.has(this.getDataKey(name));
    }
    get(name) {
      return this.getAll(name)[0];
    }
    getAll(name) {
      const tokenString = this.data.get(this.getDataKey(name)) || "";
      return tokenize(tokenString);
    }
    getAttributeName(name) {
      return this.data.getAttributeNameForKey(this.getDataKey(name));
    }
    getDataKey(name) {
      return `${name}-class`;
    }
    get data() {
      return this.scope.data;
    }
  };
  var DataMap = class {
    constructor(scope) {
      this.scope = scope;
    }
    get element() {
      return this.scope.element;
    }
    get identifier() {
      return this.scope.identifier;
    }
    get(key) {
      const name = this.getAttributeNameForKey(key);
      return this.element.getAttribute(name);
    }
    set(key, value) {
      const name = this.getAttributeNameForKey(key);
      this.element.setAttribute(name, value);
      return this.get(key);
    }
    has(key) {
      const name = this.getAttributeNameForKey(key);
      return this.element.hasAttribute(name);
    }
    delete(key) {
      if (this.has(key)) {
        const name = this.getAttributeNameForKey(key);
        this.element.removeAttribute(name);
        return true;
      } else {
        return false;
      }
    }
    getAttributeNameForKey(key) {
      return `data-${this.identifier}-${dasherize(key)}`;
    }
  };
  var Guide = class {
    constructor(logger) {
      this.warnedKeysByObject = /* @__PURE__ */ new WeakMap();
      this.logger = logger;
    }
    warn(object, key, message) {
      let warnedKeys = this.warnedKeysByObject.get(object);
      if (!warnedKeys) {
        warnedKeys = /* @__PURE__ */ new Set();
        this.warnedKeysByObject.set(object, warnedKeys);
      }
      if (!warnedKeys.has(key)) {
        warnedKeys.add(key);
        this.logger.warn(message, object);
      }
    }
  };
  function attributeValueContainsToken(attributeName, token) {
    return `[${attributeName}~="${token}"]`;
  }
  var TargetSet = class {
    constructor(scope) {
      this.scope = scope;
    }
    get element() {
      return this.scope.element;
    }
    get identifier() {
      return this.scope.identifier;
    }
    get schema() {
      return this.scope.schema;
    }
    has(targetName) {
      return this.find(targetName) != null;
    }
    find(...targetNames) {
      return targetNames.reduce((target, targetName) => target || this.findTarget(targetName) || this.findLegacyTarget(targetName), void 0);
    }
    findAll(...targetNames) {
      return targetNames.reduce((targets, targetName) => [
        ...targets,
        ...this.findAllTargets(targetName),
        ...this.findAllLegacyTargets(targetName)
      ], []);
    }
    findTarget(targetName) {
      const selector = this.getSelectorForTargetName(targetName);
      return this.scope.findElement(selector);
    }
    findAllTargets(targetName) {
      const selector = this.getSelectorForTargetName(targetName);
      return this.scope.findAllElements(selector);
    }
    getSelectorForTargetName(targetName) {
      const attributeName = this.schema.targetAttributeForScope(this.identifier);
      return attributeValueContainsToken(attributeName, targetName);
    }
    findLegacyTarget(targetName) {
      const selector = this.getLegacySelectorForTargetName(targetName);
      return this.deprecate(this.scope.findElement(selector), targetName);
    }
    findAllLegacyTargets(targetName) {
      const selector = this.getLegacySelectorForTargetName(targetName);
      return this.scope.findAllElements(selector).map((element) => this.deprecate(element, targetName));
    }
    getLegacySelectorForTargetName(targetName) {
      const targetDescriptor = `${this.identifier}.${targetName}`;
      return attributeValueContainsToken(this.schema.targetAttribute, targetDescriptor);
    }
    deprecate(element, targetName) {
      if (element) {
        const { identifier } = this;
        const attributeName = this.schema.targetAttribute;
        const revisedAttributeName = this.schema.targetAttributeForScope(identifier);
        this.guide.warn(element, `target:${targetName}`, `Please replace ${attributeName}="${identifier}.${targetName}" with ${revisedAttributeName}="${targetName}". The ${attributeName} attribute is deprecated and will be removed in a future version of Stimulus.`);
      }
      return element;
    }
    get guide() {
      return this.scope.guide;
    }
  };
  var OutletSet = class {
    constructor(scope, controllerElement) {
      this.scope = scope;
      this.controllerElement = controllerElement;
    }
    get element() {
      return this.scope.element;
    }
    get identifier() {
      return this.scope.identifier;
    }
    get schema() {
      return this.scope.schema;
    }
    has(outletName) {
      return this.find(outletName) != null;
    }
    find(...outletNames) {
      return outletNames.reduce((outlet, outletName) => outlet || this.findOutlet(outletName), void 0);
    }
    findAll(...outletNames) {
      return outletNames.reduce((outlets, outletName) => [...outlets, ...this.findAllOutlets(outletName)], []);
    }
    getSelectorForOutletName(outletName) {
      const attributeName = this.schema.outletAttributeForScope(this.identifier, outletName);
      return this.controllerElement.getAttribute(attributeName);
    }
    findOutlet(outletName) {
      const selector = this.getSelectorForOutletName(outletName);
      if (selector)
        return this.findElement(selector, outletName);
    }
    findAllOutlets(outletName) {
      const selector = this.getSelectorForOutletName(outletName);
      return selector ? this.findAllElements(selector, outletName) : [];
    }
    findElement(selector, outletName) {
      const elements2 = this.scope.queryElements(selector);
      return elements2.filter((element) => this.matchesElement(element, selector, outletName))[0];
    }
    findAllElements(selector, outletName) {
      const elements2 = this.scope.queryElements(selector);
      return elements2.filter((element) => this.matchesElement(element, selector, outletName));
    }
    matchesElement(element, selector, outletName) {
      const controllerAttribute = element.getAttribute(this.scope.schema.controllerAttribute) || "";
      return element.matches(selector) && controllerAttribute.split(" ").includes(outletName);
    }
  };
  var Scope = class {
    constructor(schema, element, identifier, logger) {
      this.targets = new TargetSet(this);
      this.classes = new ClassMap(this);
      this.data = new DataMap(this);
      this.containsElement = (element2) => {
        return element2.closest(this.controllerSelector) === this.element;
      };
      this.schema = schema;
      this.element = element;
      this.identifier = identifier;
      this.guide = new Guide(logger);
      this.outlets = new OutletSet(this.documentScope, element);
    }
    findElement(selector) {
      return this.element.matches(selector) ? this.element : this.queryElements(selector).find(this.containsElement);
    }
    findAllElements(selector) {
      return [
        ...this.element.matches(selector) ? [this.element] : [],
        ...this.queryElements(selector).filter(this.containsElement)
      ];
    }
    queryElements(selector) {
      return Array.from(this.element.querySelectorAll(selector));
    }
    get controllerSelector() {
      return attributeValueContainsToken(this.schema.controllerAttribute, this.identifier);
    }
    get isDocumentScope() {
      return this.element === document.documentElement;
    }
    get documentScope() {
      return this.isDocumentScope ? this : new Scope(this.schema, document.documentElement, this.identifier, this.guide.logger);
    }
  };
  var ScopeObserver = class {
    constructor(element, schema, delegate) {
      this.element = element;
      this.schema = schema;
      this.delegate = delegate;
      this.valueListObserver = new ValueListObserver(this.element, this.controllerAttribute, this);
      this.scopesByIdentifierByElement = /* @__PURE__ */ new WeakMap();
      this.scopeReferenceCounts = /* @__PURE__ */ new WeakMap();
    }
    start() {
      this.valueListObserver.start();
    }
    stop() {
      this.valueListObserver.stop();
    }
    get controllerAttribute() {
      return this.schema.controllerAttribute;
    }
    parseValueForToken(token) {
      const { element, content: identifier } = token;
      return this.parseValueForElementAndIdentifier(element, identifier);
    }
    parseValueForElementAndIdentifier(element, identifier) {
      const scopesByIdentifier = this.fetchScopesByIdentifierForElement(element);
      let scope = scopesByIdentifier.get(identifier);
      if (!scope) {
        scope = this.delegate.createScopeForElementAndIdentifier(element, identifier);
        scopesByIdentifier.set(identifier, scope);
      }
      return scope;
    }
    elementMatchedValue(element, value) {
      const referenceCount = (this.scopeReferenceCounts.get(value) || 0) + 1;
      this.scopeReferenceCounts.set(value, referenceCount);
      if (referenceCount == 1) {
        this.delegate.scopeConnected(value);
      }
    }
    elementUnmatchedValue(element, value) {
      const referenceCount = this.scopeReferenceCounts.get(value);
      if (referenceCount) {
        this.scopeReferenceCounts.set(value, referenceCount - 1);
        if (referenceCount == 1) {
          this.delegate.scopeDisconnected(value);
        }
      }
    }
    fetchScopesByIdentifierForElement(element) {
      let scopesByIdentifier = this.scopesByIdentifierByElement.get(element);
      if (!scopesByIdentifier) {
        scopesByIdentifier = /* @__PURE__ */ new Map();
        this.scopesByIdentifierByElement.set(element, scopesByIdentifier);
      }
      return scopesByIdentifier;
    }
  };
  var Router = class {
    constructor(application2) {
      this.application = application2;
      this.scopeObserver = new ScopeObserver(this.element, this.schema, this);
      this.scopesByIdentifier = new Multimap();
      this.modulesByIdentifier = /* @__PURE__ */ new Map();
    }
    get element() {
      return this.application.element;
    }
    get schema() {
      return this.application.schema;
    }
    get logger() {
      return this.application.logger;
    }
    get controllerAttribute() {
      return this.schema.controllerAttribute;
    }
    get modules() {
      return Array.from(this.modulesByIdentifier.values());
    }
    get contexts() {
      return this.modules.reduce((contexts, module) => contexts.concat(module.contexts), []);
    }
    start() {
      this.scopeObserver.start();
    }
    stop() {
      this.scopeObserver.stop();
    }
    loadDefinition(definition) {
      this.unloadIdentifier(definition.identifier);
      const module = new Module(this.application, definition);
      this.connectModule(module);
      const afterLoad = definition.controllerConstructor.afterLoad;
      if (afterLoad) {
        afterLoad.call(definition.controllerConstructor, definition.identifier, this.application);
      }
    }
    unloadIdentifier(identifier) {
      const module = this.modulesByIdentifier.get(identifier);
      if (module) {
        this.disconnectModule(module);
      }
    }
    getContextForElementAndIdentifier(element, identifier) {
      const module = this.modulesByIdentifier.get(identifier);
      if (module) {
        return module.contexts.find((context) => context.element == element);
      }
    }
    proposeToConnectScopeForElementAndIdentifier(element, identifier) {
      const scope = this.scopeObserver.parseValueForElementAndIdentifier(element, identifier);
      if (scope) {
        this.scopeObserver.elementMatchedValue(scope.element, scope);
      } else {
        console.error(`Couldn't find or create scope for identifier: "${identifier}" and element:`, element);
      }
    }
    handleError(error3, message, detail) {
      this.application.handleError(error3, message, detail);
    }
    createScopeForElementAndIdentifier(element, identifier) {
      return new Scope(this.schema, element, identifier, this.logger);
    }
    scopeConnected(scope) {
      this.scopesByIdentifier.add(scope.identifier, scope);
      const module = this.modulesByIdentifier.get(scope.identifier);
      if (module) {
        module.connectContextForScope(scope);
      }
    }
    scopeDisconnected(scope) {
      this.scopesByIdentifier.delete(scope.identifier, scope);
      const module = this.modulesByIdentifier.get(scope.identifier);
      if (module) {
        module.disconnectContextForScope(scope);
      }
    }
    connectModule(module) {
      this.modulesByIdentifier.set(module.identifier, module);
      const scopes = this.scopesByIdentifier.getValuesForKey(module.identifier);
      scopes.forEach((scope) => module.connectContextForScope(scope));
    }
    disconnectModule(module) {
      this.modulesByIdentifier.delete(module.identifier);
      const scopes = this.scopesByIdentifier.getValuesForKey(module.identifier);
      scopes.forEach((scope) => module.disconnectContextForScope(scope));
    }
  };
  var defaultSchema = {
    controllerAttribute: "data-controller",
    actionAttribute: "data-action",
    targetAttribute: "data-target",
    targetAttributeForScope: (identifier) => `data-${identifier}-target`,
    outletAttributeForScope: (identifier, outlet) => `data-${identifier}-${outlet}-outlet`,
    keyMappings: Object.assign(Object.assign({ enter: "Enter", tab: "Tab", esc: "Escape", space: " ", up: "ArrowUp", down: "ArrowDown", left: "ArrowLeft", right: "ArrowRight", home: "Home", end: "End", page_up: "PageUp", page_down: "PageDown" }, objectFromEntries("abcdefghijklmnopqrstuvwxyz".split("").map((c2) => [c2, c2]))), objectFromEntries("0123456789".split("").map((n2) => [n2, n2])))
  };
  function objectFromEntries(array) {
    return array.reduce((memo, [k2, v2]) => Object.assign(Object.assign({}, memo), { [k2]: v2 }), {});
  }
  var Application = class {
    constructor(element = document.documentElement, schema = defaultSchema) {
      this.logger = console;
      this.debug = false;
      this.logDebugActivity = (identifier, functionName, detail = {}) => {
        if (this.debug) {
          this.logFormattedMessage(identifier, functionName, detail);
        }
      };
      this.element = element;
      this.schema = schema;
      this.dispatcher = new Dispatcher(this);
      this.router = new Router(this);
      this.actionDescriptorFilters = Object.assign({}, defaultActionDescriptorFilters);
    }
    static start(element, schema) {
      const application2 = new this(element, schema);
      application2.start();
      return application2;
    }
    async start() {
      await domReady();
      this.logDebugActivity("application", "starting");
      this.dispatcher.start();
      this.router.start();
      this.logDebugActivity("application", "start");
    }
    stop() {
      this.logDebugActivity("application", "stopping");
      this.dispatcher.stop();
      this.router.stop();
      this.logDebugActivity("application", "stop");
    }
    register(identifier, controllerConstructor) {
      this.load({ identifier, controllerConstructor });
    }
    registerActionOption(name, filter) {
      this.actionDescriptorFilters[name] = filter;
    }
    load(head, ...rest) {
      const definitions = Array.isArray(head) ? head : [head, ...rest];
      definitions.forEach((definition) => {
        if (definition.controllerConstructor.shouldLoad) {
          this.router.loadDefinition(definition);
        }
      });
    }
    unload(head, ...rest) {
      const identifiers = Array.isArray(head) ? head : [head, ...rest];
      identifiers.forEach((identifier) => this.router.unloadIdentifier(identifier));
    }
    get controllers() {
      return this.router.contexts.map((context) => context.controller);
    }
    getControllerForElementAndIdentifier(element, identifier) {
      const context = this.router.getContextForElementAndIdentifier(element, identifier);
      return context ? context.controller : null;
    }
    handleError(error3, message, detail) {
      var _a;
      this.logger.error(`%s

%o

%o`, message, error3, detail);
      (_a = window.onerror) === null || _a === void 0 ? void 0 : _a.call(window, message, "", 0, 0, error3);
    }
    logFormattedMessage(identifier, functionName, detail = {}) {
      detail = Object.assign({ application: this }, detail);
      this.logger.groupCollapsed(`${identifier} #${functionName}`);
      this.logger.log("details:", Object.assign({}, detail));
      this.logger.groupEnd();
    }
  };
  function domReady() {
    return new Promise((resolve2) => {
      if (document.readyState == "loading") {
        document.addEventListener("DOMContentLoaded", () => resolve2());
      } else {
        resolve2();
      }
    });
  }
  function ClassPropertiesBlessing(constructor) {
    const classes = readInheritableStaticArrayValues(constructor, "classes");
    return classes.reduce((properties, classDefinition) => {
      return Object.assign(properties, propertiesForClassDefinition(classDefinition));
    }, {});
  }
  function propertiesForClassDefinition(key) {
    return {
      [`${key}Class`]: {
        get() {
          const { classes } = this;
          if (classes.has(key)) {
            return classes.get(key);
          } else {
            const attribute = classes.getAttributeName(key);
            throw new Error(`Missing attribute "${attribute}"`);
          }
        }
      },
      [`${key}Classes`]: {
        get() {
          return this.classes.getAll(key);
        }
      },
      [`has${capitalize(key)}Class`]: {
        get() {
          return this.classes.has(key);
        }
      }
    };
  }
  function OutletPropertiesBlessing(constructor) {
    const outlets = readInheritableStaticArrayValues(constructor, "outlets");
    return outlets.reduce((properties, outletDefinition) => {
      return Object.assign(properties, propertiesForOutletDefinition(outletDefinition));
    }, {});
  }
  function getOutletController(controller, element, identifier) {
    return controller.application.getControllerForElementAndIdentifier(element, identifier);
  }
  function getControllerAndEnsureConnectedScope(controller, element, outletName) {
    let outletController = getOutletController(controller, element, outletName);
    if (outletController)
      return outletController;
    controller.application.router.proposeToConnectScopeForElementAndIdentifier(element, outletName);
    outletController = getOutletController(controller, element, outletName);
    if (outletController)
      return outletController;
  }
  function propertiesForOutletDefinition(name) {
    const camelizedName = namespaceCamelize(name);
    return {
      [`${camelizedName}Outlet`]: {
        get() {
          const outletElement = this.outlets.find(name);
          const selector = this.outlets.getSelectorForOutletName(name);
          if (outletElement) {
            const outletController = getControllerAndEnsureConnectedScope(this, outletElement, name);
            if (outletController)
              return outletController;
            throw new Error(`The provided outlet element is missing an outlet controller "${name}" instance for host controller "${this.identifier}"`);
          }
          throw new Error(`Missing outlet element "${name}" for host controller "${this.identifier}". Stimulus couldn't find a matching outlet element using selector "${selector}".`);
        }
      },
      [`${camelizedName}Outlets`]: {
        get() {
          const outlets = this.outlets.findAll(name);
          if (outlets.length > 0) {
            return outlets.map((outletElement) => {
              const outletController = getControllerAndEnsureConnectedScope(this, outletElement, name);
              if (outletController)
                return outletController;
              console.warn(`The provided outlet element is missing an outlet controller "${name}" instance for host controller "${this.identifier}"`, outletElement);
            }).filter((controller) => controller);
          }
          return [];
        }
      },
      [`${camelizedName}OutletElement`]: {
        get() {
          const outletElement = this.outlets.find(name);
          const selector = this.outlets.getSelectorForOutletName(name);
          if (outletElement) {
            return outletElement;
          } else {
            throw new Error(`Missing outlet element "${name}" for host controller "${this.identifier}". Stimulus couldn't find a matching outlet element using selector "${selector}".`);
          }
        }
      },
      [`${camelizedName}OutletElements`]: {
        get() {
          return this.outlets.findAll(name);
        }
      },
      [`has${capitalize(camelizedName)}Outlet`]: {
        get() {
          return this.outlets.has(name);
        }
      }
    };
  }
  function TargetPropertiesBlessing(constructor) {
    const targets = readInheritableStaticArrayValues(constructor, "targets");
    return targets.reduce((properties, targetDefinition) => {
      return Object.assign(properties, propertiesForTargetDefinition(targetDefinition));
    }, {});
  }
  function propertiesForTargetDefinition(name) {
    return {
      [`${name}Target`]: {
        get() {
          const target = this.targets.find(name);
          if (target) {
            return target;
          } else {
            throw new Error(`Missing target element "${name}" for "${this.identifier}" controller`);
          }
        }
      },
      [`${name}Targets`]: {
        get() {
          return this.targets.findAll(name);
        }
      },
      [`has${capitalize(name)}Target`]: {
        get() {
          return this.targets.has(name);
        }
      }
    };
  }
  function ValuePropertiesBlessing(constructor) {
    const valueDefinitionPairs = readInheritableStaticObjectPairs(constructor, "values");
    const propertyDescriptorMap = {
      valueDescriptorMap: {
        get() {
          return valueDefinitionPairs.reduce((result, valueDefinitionPair) => {
            const valueDescriptor = parseValueDefinitionPair(valueDefinitionPair, this.identifier);
            const attributeName = this.data.getAttributeNameForKey(valueDescriptor.key);
            return Object.assign(result, { [attributeName]: valueDescriptor });
          }, {});
        }
      }
    };
    return valueDefinitionPairs.reduce((properties, valueDefinitionPair) => {
      return Object.assign(properties, propertiesForValueDefinitionPair(valueDefinitionPair));
    }, propertyDescriptorMap);
  }
  function propertiesForValueDefinitionPair(valueDefinitionPair, controller) {
    const definition = parseValueDefinitionPair(valueDefinitionPair, controller);
    const { key, name, reader: read2, writer: write2 } = definition;
    return {
      [name]: {
        get() {
          const value = this.data.get(key);
          if (value !== null) {
            return read2(value);
          } else {
            return definition.defaultValue;
          }
        },
        set(value) {
          if (value === void 0) {
            this.data.delete(key);
          } else {
            this.data.set(key, write2(value));
          }
        }
      },
      [`has${capitalize(name)}`]: {
        get() {
          return this.data.has(key) || definition.hasCustomDefaultValue;
        }
      }
    };
  }
  function parseValueDefinitionPair([token, typeDefinition], controller) {
    return valueDescriptorForTokenAndTypeDefinition({
      controller,
      token,
      typeDefinition
    });
  }
  function parseValueTypeConstant(constant) {
    switch (constant) {
      case Array:
        return "array";
      case Boolean:
        return "boolean";
      case Number:
        return "number";
      case Object:
        return "object";
      case String:
        return "string";
    }
  }
  function parseValueTypeDefault(defaultValue) {
    switch (typeof defaultValue) {
      case "boolean":
        return "boolean";
      case "number":
        return "number";
      case "string":
        return "string";
    }
    if (Array.isArray(defaultValue))
      return "array";
    if (Object.prototype.toString.call(defaultValue) === "[object Object]")
      return "object";
  }
  function parseValueTypeObject(payload) {
    const { controller, token, typeObject } = payload;
    const hasType = isSomething(typeObject.type);
    const hasDefault = isSomething(typeObject.default);
    const fullObject = hasType && hasDefault;
    const onlyType = hasType && !hasDefault;
    const onlyDefault = !hasType && hasDefault;
    const typeFromObject = parseValueTypeConstant(typeObject.type);
    const typeFromDefaultValue = parseValueTypeDefault(payload.typeObject.default);
    if (onlyType)
      return typeFromObject;
    if (onlyDefault)
      return typeFromDefaultValue;
    if (typeFromObject !== typeFromDefaultValue) {
      const propertyPath = controller ? `${controller}.${token}` : token;
      throw new Error(`The specified default value for the Stimulus Value "${propertyPath}" must match the defined type "${typeFromObject}". The provided default value of "${typeObject.default}" is of type "${typeFromDefaultValue}".`);
    }
    if (fullObject)
      return typeFromObject;
  }
  function parseValueTypeDefinition(payload) {
    const { controller, token, typeDefinition } = payload;
    const typeObject = { controller, token, typeObject: typeDefinition };
    const typeFromObject = parseValueTypeObject(typeObject);
    const typeFromDefaultValue = parseValueTypeDefault(typeDefinition);
    const typeFromConstant = parseValueTypeConstant(typeDefinition);
    const type = typeFromObject || typeFromDefaultValue || typeFromConstant;
    if (type)
      return type;
    const propertyPath = controller ? `${controller}.${typeDefinition}` : token;
    throw new Error(`Unknown value type "${propertyPath}" for "${token}" value`);
  }
  function defaultValueForDefinition(typeDefinition) {
    const constant = parseValueTypeConstant(typeDefinition);
    if (constant)
      return defaultValuesByType[constant];
    const hasDefault = hasProperty(typeDefinition, "default");
    const hasType = hasProperty(typeDefinition, "type");
    const typeObject = typeDefinition;
    if (hasDefault)
      return typeObject.default;
    if (hasType) {
      const { type } = typeObject;
      const constantFromType = parseValueTypeConstant(type);
      if (constantFromType)
        return defaultValuesByType[constantFromType];
    }
    return typeDefinition;
  }
  function valueDescriptorForTokenAndTypeDefinition(payload) {
    const { token, typeDefinition } = payload;
    const key = `${dasherize(token)}-value`;
    const type = parseValueTypeDefinition(payload);
    return {
      type,
      key,
      name: camelize(key),
      get defaultValue() {
        return defaultValueForDefinition(typeDefinition);
      },
      get hasCustomDefaultValue() {
        return parseValueTypeDefault(typeDefinition) !== void 0;
      },
      reader: readers[type],
      writer: writers[type] || writers.default
    };
  }
  var defaultValuesByType = {
    get array() {
      return [];
    },
    boolean: false,
    number: 0,
    get object() {
      return {};
    },
    string: ""
  };
  var readers = {
    array(value) {
      const array = JSON.parse(value);
      if (!Array.isArray(array)) {
        throw new TypeError(`expected value of type "array" but instead got value "${value}" of type "${parseValueTypeDefault(array)}"`);
      }
      return array;
    },
    boolean(value) {
      return !(value == "0" || String(value).toLowerCase() == "false");
    },
    number(value) {
      return Number(value.replace(/_/g, ""));
    },
    object(value) {
      const object = JSON.parse(value);
      if (object === null || typeof object != "object" || Array.isArray(object)) {
        throw new TypeError(`expected value of type "object" but instead got value "${value}" of type "${parseValueTypeDefault(object)}"`);
      }
      return object;
    },
    string(value) {
      return value;
    }
  };
  var writers = {
    default: writeString,
    array: writeJSON,
    object: writeJSON
  };
  function writeJSON(value) {
    return JSON.stringify(value);
  }
  function writeString(value) {
    return `${value}`;
  }
  var Controller = class {
    constructor(context) {
      this.context = context;
    }
    static get shouldLoad() {
      return true;
    }
    static afterLoad(_identifier, _application) {
      return;
    }
    get application() {
      return this.context.application;
    }
    get scope() {
      return this.context.scope;
    }
    get element() {
      return this.scope.element;
    }
    get identifier() {
      return this.scope.identifier;
    }
    get targets() {
      return this.scope.targets;
    }
    get outlets() {
      return this.scope.outlets;
    }
    get classes() {
      return this.scope.classes;
    }
    get data() {
      return this.scope.data;
    }
    initialize() {
    }
    connect() {
    }
    disconnect() {
    }
    dispatch(eventName, { target = this.element, detail = {}, prefix = this.identifier, bubbles = true, cancelable = true } = {}) {
      const type = prefix ? `${prefix}:${eventName}` : eventName;
      const event = new CustomEvent(type, { detail, bubbles, cancelable });
      target.dispatchEvent(event);
      return event;
    }
  };
  Controller.blessings = [
    ClassPropertiesBlessing,
    TargetPropertiesBlessing,
    ValuePropertiesBlessing,
    OutletPropertiesBlessing
  ];
  Controller.targets = [];
  Controller.outlets = [];
  Controller.values = {};

  // controllers/application.js
  var application = Application.start();

  // controllers/additional_employees_controller.js
  var additional_employees_controller_exports = {};
  __export(additional_employees_controller_exports, {
    default: () => additional_employees_controller_default
  });
  var additional_employees_controller_default = class extends Controller {
    addEmployee(event) {
      let application_step = event.target.dataset.applicationStep;
      let step = window.location.pathname.match(/\d$/g) || application_step.match(/\d$/g);
      let new_employee_count;
      let controller = window.location.pathname == "/quotes/new" ? "quotes" : "policies";
      let application_or_upgrade = /upgrade/.test(window.location.pathname) ? "upgrade" : "application";
      new_employee_count = +this.employeesAreaTarget.dataset.additionalEmployeeCountValue + 1;
      this.employeesAreaTarget.dataset.additionalEmployeeCountValue = new_employee_count;
      fetch(`/${controller}/add_additional_employee/${step}`, {
        method: "POST",
        headers: { "x-csrf-token": this.getXcsrfToken(), "content-type": "application/json" },
        body: JSON.stringify({ "application_step": application_step, "count": new_employee_count, "application_or_upgrade": application_or_upgrade })
      }).then((response) => response.json()).then((data) => {
        let newForm = document.createElement("div");
        newForm.innerHTML = data.form;
        let employeeArea = document.getElementById("employees-area");
        if (employeeArea) {
          employeeArea.appendChild(newForm);
        }
        let totalCost = document.querySelector("#total-cost");
        this.currentStepTotalTarget.value = +this.currentStepTotalTarget.value + this.priceValue;
        totalCost.setAttribute(`data-additional-employee-${new_employee_count}`, this.priceValue);
        totalCost.dataset.currentStepTotal = +this.currentStepTotalTarget.value;
        totalCost.innerText = `$${+totalCost.dataset.currentStepTotal + +totalCost.dataset.completedStepsTotal}`;
      });
    }
    removeEmployee(event) {
      event.target.closest(".additional-employee").remove();
      let totalCost = document.querySelector("#total-cost");
      this.currentStepTotalTarget.value = +this.currentStepTotalTarget.value - this.priceValue;
      totalCost.removeAttribute(`data-additional-employee-${this.employeesAreaTarget.dataset.employeesAreaCountValue}`);
      totalCost.dataset.currentStepTotal = +this.currentStepTotalTarget.value;
      totalCost.innerText = `$${+totalCost.dataset.currentStepTotal + +totalCost.dataset.completedStepsTotal}`;
    }
    getXcsrfToken() {
      return document.getElementsByName("csrf-token")[0].content;
    }
  };
  __publicField(additional_employees_controller_default, "targets", ["employeesArea", "formArea", "currentCount", "currentStepTotal"]);
  __publicField(additional_employees_controller_default, "values", {
    count: Number,
    price: { type: Number, default: 99 }
  });

  // controllers/additional_insureds_controller.js
  var additional_insureds_controller_exports = {};
  __export(additional_insureds_controller_exports, {
    default: () => additional_insureds_controller_default
  });
  var additional_insureds_controller_default = class extends Controller {
    addAdditionalInsured(event) {
      let application_step = event.target.dataset.applicationStep;
      let step = window.location.pathname.match(/\d$/g) || application_step.match(/\d$/g);
      let new_ai_count;
      let controller = window.location.pathname == "/quotes/new" ? "quotes" : "policies";
      let application_or_upgrade = /upgrade/.test(window.location.pathname) ? "upgrade" : "application";
      let masterPolicyId;
      if (controller == "quotes") {
        masterPolicyId = document.querySelector("#user_master_policy_id").value;
      } else {
        masterPolicyId = document.querySelector("#policy_master_policy_id").value;
      }
      new_ai_count = +this.additionalInsuredsAreaTarget.dataset.additionalInsuredCountValue + 1;
      this.additionalInsuredsAreaTarget.dataset.additionalInsuredCountValue = new_ai_count;
      fetch(`/${controller}/add_additional_insured/${step}`, {
        method: "POST",
        headers: { "x-csrf-token": this.getXcsrfToken(), "content-type": "application/json" },
        body: JSON.stringify({
          "application_step": application_step,
          "count": new_ai_count,
          "application_or_upgrade": application_or_upgrade,
          "master_policy_id": masterPolicyId
        })
      }).then((response) => response.json()).then((data) => {
        let newForm = document.createElement("div");
        newForm.innerHTML = data.form;
        let insuredsArea = document.getElementById("insureds-area");
        if (insuredsArea) {
          insuredsArea.appendChild(newForm);
        }
        let totalCost = document.querySelector("#total-cost");
        this.currentStepTotalTarget.value = +this.currentStepTotalTarget.value + this.priceValue;
        totalCost.setAttribute(`data-additional-insured-${new_ai_count}`, this.priceValue);
        totalCost.dataset.currentStepTotal = +this.currentStepTotalTarget.value;
        totalCost.innerText = `$${+totalCost.dataset.currentStepTotal + +totalCost.dataset.completedStepsTotal}`;
      });
    }
    removeAdditionalInsured(e2) {
      e2.target.closest(".additional-insured").remove();
      let totalCost = document.querySelector("#total-cost");
      this.currentStepTotalTarget.value = +this.currentStepTotalTarget.value - this.priceValue;
      totalCost.removeAttribute(`data-additional-insured-${this.additionalInsuredsAreaTarget.dataset.additionalInsuredCountValue}`);
      totalCost.dataset.currentStepTotal = +this.currentStepTotalTarget.value;
      totalCost.innerText = `$${+totalCost.dataset.currentStepTotal + +totalCost.dataset.completedStepsTotal}`;
    }
    getXcsrfToken() {
      return document.getElementsByName("csrf-token")[0].content;
    }
  };
  __publicField(additional_insureds_controller_default, "targets", ["additionalInsuredsArea", "aiFormArea", "currentCount", "currentStepTotal"]);
  __publicField(additional_insureds_controller_default, "values", {
    count: Number,
    price: { type: Number, default: 10 }
  });

  // controllers/application_detail_options_controller.js
  var application_detail_options_controller_exports = {};
  __export(application_detail_options_controller_exports, {
    default: () => application_detail_options_controller_default
  });
  var import_ujs = __toESM(require_rails_ujs());
  var application_detail_options_controller_default = class extends Controller {
    addOption() {
      fetch("/administration/application_detail_options/new").then((response) => response.json()).then((data) => {
        document.querySelector('[data-target="applicationDetailForm"]').classList.add("d-none");
        let formArea = document.querySelector('[data-target="applicationOptionArea"]');
        formArea.classList.remove("d-none");
        formArea.innerHTML = data.form;
        formArea.querySelector('[data-target="application-detail-options.applicationDetailId"]').setAttribute("value", this.data.get("applicationDetailId"));
      });
    }
    editDetailOption(event) {
      fetch(`/administration/application_detail_options/${event.target.dataset.applicationDetailOptionsId}/edit`).then((response) => response.json()).then((data) => {
        document.querySelector('[data-target="applicationDetailForm"]').classList.add("d-none");
        let formArea = document.querySelector('[data-target="applicationOptionArea"]');
        formArea.classList.remove("d-none");
        formArea.innerHTML = data.form;
      });
    }
    handleAjaxResponse(event) {
      this.closeForm();
    }
    destroyDetailOption(event) {
      let answer = confirm("Are you sure you want to destroy this Application Detail?");
      if (answer) {
        let metaTag = document.getElementsByName("csrf-token")[0].content;
        fetch(`/administration/application_detail_options/${event.target.dataset.applicationDetailOptionsId}`, { headers: { "X-CSRF-Token": metaTag }, method: "DELETE" });
      }
    }
    closeForm(event) {
      document.querySelector('[data-target="applicationDetailForm"]').classList.remove("d-none");
      document.querySelector('[data-target="applicationOptionArea"]').classList.add("d-none");
    }
  };

  // controllers/application_details_controller.js
  var application_details_controller_exports = {};
  __export(application_details_controller_exports, {
    default: () => application_details_controller_default
  });
  var application_details_controller_default = class extends Controller {
    addDetail() {
      let modalController = this.setupModalController();
      fetch("/administration/application_details/new").then((response) => response.json()).then((data) => {
        modalController.contentAreaTarget.innerHTML = data.form;
        modalController.contentAreaTarget.querySelector('[data-target="application-details.applicationStepId"]').setAttribute("value", this.data.get("applicationStepId"));
        modalController.open();
      });
    }
    editDetail(event) {
      let modalController = this.setupModalController();
      fetch(`/administration/application_details/${event.target.dataset.applicationDetailId}/edit`).then((response) => response.json()).then((data) => {
        modalController.contentAreaTarget.innerHTML = data.form;
        modalController.open();
      });
    }
    handleAjaxResponse(event) {
      let modalController = this.setupModalController();
      if (document.querySelector(`[data-application-detail-id="${event.detail[0].applicationDetailId}"]`)) {
        let old_element = document.querySelector(`[data-application-detail-id="${event.detail[0].applicationDetailId}"]`);
        old_element.insertAdjacentHTML("beforebegin", event.detail[0].applicationDetail);
        old_element.remove();
      } else if (event.detail[0].applicationDetails) {
        let details_section = document.querySelector(`[data-application-details-area-${event.detail[0].applicationStepId}`);
        details_section.innerHTML = "";
        JSON.parse(event.detail[0].applicationDetails).forEach((element) => details_section.insertAdjacentHTML("beforeend", element));
      } else {
        document.querySelector(`[data-application-details-area-${event.detail[0].applicationStepId}]`).insertAdjacentHTML("beforeend", event.detail[0].applicationDetail);
      }
      modalController.close();
    }
    destroyDetail(event) {
      let answer = confirm("Are you sure you want to destroy this Application Detail?");
      if (answer) {
        let metaTag = document.getElementsByName("csrf-token")[0].content;
        fetch(`/administration/application_details/${event.target.dataset.applicationDetailId}`, { headers: { "X-CSRF-Token": metaTag }, method: "DELETE" }).then((response) => response.json()).then((data) => {
          if (data.ok) {
            document.querySelector(`[data-application-detail-id="${data.applicationDetailId}"]`).remove();
          } else {
            alert(data.error);
          }
        });
      }
    }
    toggleOptionsDisplay(event) {
      if (event.target.value == "radio_button") {
        this.optionsAreaTarget.classList.remove("d-none");
      } else {
        this.optionsAreaTarget.classList.add("d-none");
      }
    }
    toggleInformationTypeFields(event) {
      if (event.target.value == "question") {
        this.inputAttributesTarget.classList.remove("d-none");
      } else {
        this.inputAttributesTarget.classList.add("d-none");
      }
      if (event.target.value == "company") {
      }
    }
    setupModalController() {
      return this.application.getControllerForElementAndIdentifier(document.querySelector("[data-modal-window]"), "modal");
    }
  };
  __publicField(application_details_controller_default, "targets", ["formArea", "applicationStepId", "detailsArea", "optionsArea", "inputAttributes"]);

  // controllers/application_steps_controller.js
  var application_steps_controller_exports = {};
  __export(application_steps_controller_exports, {
    default: () => application_steps_controller_default
  });
  var application_steps_controller_default = class extends Controller {
    addNewStep() {
      let modalController = this.setupModalController();
      fetch("/administration/application_steps/new").then((response) => response.json()).then((data) => {
        modalController.contentAreaTarget.innerHTML = data.form;
        modalController.contentAreaTarget.querySelector("[data-application-steps-masterPolicyId]").setAttribute("value", this.data.get("masterPolicyId"));
        modalController.open();
      });
    }
    editApplicationStep(event) {
      let modalController = this.setupModalController();
      fetch(`/administration/application_steps/${event.target.dataset.applicationStepsId}/edit`).then((response) => response.json()).then((data) => {
        modalController.contentAreaTarget.innerHTML = data.form;
        modalController.open();
      });
    }
    formSubmitted(event) {
      let modalController = this.setupModalController();
      modalController.close();
      if (document.querySelector(`[data-application-step-id="${event.detail[0].applicationStepId}"]`)) {
        let step = document.querySelector(`[data-application-step-id="${event.detail[0].applicationStepId}"]`);
        step.querySelector("[data-application-step-name]").innerHTML = event.detail[0].applicationStepName;
      } else if (event.detail[0].applicationSteps) {
        let steps_area = document.querySelector('[data-target="application-steps.stepsArea"]');
        steps_area.innerHTML = "";
        JSON.parse(event.detail[0].applicationSteps).forEach((element) => {
          steps_area.insertAdjacentHTML("beforeend", element);
        });
      } else {
        document.querySelector('[data-target="application-steps.stepsArea"]').insertAdjacentHTML("beforeend", event.detail[0].newApplicationStep);
      }
    }
    destroyApplicationStep(event) {
      let answer = confirm("Are you sure you want to destroy this Application Step? All Policy Detail questions will also be destroyed!");
      if (answer) {
        let metaTag = document.getElementsByName("csrf-token")[0].content;
        fetch(`/administration/application_steps/${event.target.dataset.applicationStepsId}`, { headers: { "X-CSRF-Token": metaTag }, method: "DELETE" }).then((response) => response.json()).then((data) => {
          if (data.ok) {
            document.querySelector(`[data-application-step-id="${data.applicationStepId}"]`).remove();
          } else {
            alert(data.error);
          }
        });
      }
    }
    setupModalController() {
      return this.application.getControllerForElementAndIdentifier(document.querySelector("[data-modal-window]"), "modal");
    }
  };
  __publicField(application_steps_controller_default, "targets", ["formArea", "masterPolicyId", "stepsArea"]);

  // controllers/doc_type_fields_controller.js
  var doc_type_fields_controller_exports = {};
  __export(doc_type_fields_controller_exports, {
    default: () => doc_type_fields_controller_default
  });
  var doc_type_fields_controller_default = class extends Controller {
    addDocField(event) {
      fetch(`/administration/application_details/${this.data.get("applicationDetailId")}/document_template_fields/new`).then((response) => response.json()).then((data) => {
        document.querySelector('[data-target="applicationDetailForm"]').classList.add("d-none");
        let formArea = document.querySelector('[data-target="applicationOptionArea"]');
        formArea.classList.remove("d-none");
        formArea.innerHTML = data.form;
      });
    }
    removeDocField() {
      consolelog('The "remove" function was executed!');
    }
    closeForm(event) {
      document.querySelector('[data-target="applicationDetailForm"]').classList.remove("d-none");
      document.querySelector('[data-target="applicationOptionArea"]').classList.add("d-none");
    }
  };

  // controllers/documents_controller.js
  var documents_controller_exports = {};
  __export(documents_controller_exports, {
    default: () => documents_controller_default
  });
  var documents_controller_default = class extends Controller {
    toggleCreateForm() {
      this.formCreateTarget.classList.toggle("hidden");
    }
    hideCreateForm() {
      this.formCreateTarget.classList.add("hidden");
    }
  };
  __publicField(documents_controller_default, "targets", ["formCreate"]);

  // controllers/endorsements_controller.js
  var endorsements_controller_exports = {};
  __export(endorsements_controller_exports, {
    default: () => endorsements_controller_default
  });

  // ../../node_modules/@popperjs/core/lib/index.js
  var lib_exports = {};
  __export(lib_exports, {
    afterMain: () => afterMain,
    afterRead: () => afterRead,
    afterWrite: () => afterWrite,
    applyStyles: () => applyStyles_default,
    arrow: () => arrow_default,
    auto: () => auto,
    basePlacements: () => basePlacements,
    beforeMain: () => beforeMain,
    beforeRead: () => beforeRead,
    beforeWrite: () => beforeWrite,
    bottom: () => bottom,
    clippingParents: () => clippingParents,
    computeStyles: () => computeStyles_default,
    createPopper: () => createPopper3,
    createPopperBase: () => createPopper,
    createPopperLite: () => createPopper2,
    detectOverflow: () => detectOverflow,
    end: () => end,
    eventListeners: () => eventListeners_default,
    flip: () => flip_default,
    hide: () => hide_default,
    left: () => left,
    main: () => main,
    modifierPhases: () => modifierPhases,
    offset: () => offset_default,
    placements: () => placements,
    popper: () => popper,
    popperGenerator: () => popperGenerator,
    popperOffsets: () => popperOffsets_default,
    preventOverflow: () => preventOverflow_default,
    read: () => read,
    reference: () => reference,
    right: () => right,
    start: () => start2,
    top: () => top,
    variationPlacements: () => variationPlacements,
    viewport: () => viewport,
    write: () => write
  });

  // ../../node_modules/@popperjs/core/lib/enums.js
  var top = "top";
  var bottom = "bottom";
  var right = "right";
  var left = "left";
  var auto = "auto";
  var basePlacements = [top, bottom, right, left];
  var start2 = "start";
  var end = "end";
  var clippingParents = "clippingParents";
  var viewport = "viewport";
  var popper = "popper";
  var reference = "reference";
  var variationPlacements = /* @__PURE__ */ basePlacements.reduce(function(acc, placement) {
    return acc.concat([placement + "-" + start2, placement + "-" + end]);
  }, []);
  var placements = /* @__PURE__ */ [].concat(basePlacements, [auto]).reduce(function(acc, placement) {
    return acc.concat([placement, placement + "-" + start2, placement + "-" + end]);
  }, []);
  var beforeRead = "beforeRead";
  var read = "read";
  var afterRead = "afterRead";
  var beforeMain = "beforeMain";
  var main = "main";
  var afterMain = "afterMain";
  var beforeWrite = "beforeWrite";
  var write = "write";
  var afterWrite = "afterWrite";
  var modifierPhases = [beforeRead, read, afterRead, beforeMain, main, afterMain, beforeWrite, write, afterWrite];

  // ../../node_modules/@popperjs/core/lib/dom-utils/getNodeName.js
  function getNodeName(element) {
    return element ? (element.nodeName || "").toLowerCase() : null;
  }

  // ../../node_modules/@popperjs/core/lib/dom-utils/getWindow.js
  function getWindow(node) {
    if (node == null) {
      return window;
    }
    if (node.toString() !== "[object Window]") {
      var ownerDocument = node.ownerDocument;
      return ownerDocument ? ownerDocument.defaultView || window : window;
    }
    return node;
  }

  // ../../node_modules/@popperjs/core/lib/dom-utils/instanceOf.js
  function isElement(node) {
    var OwnElement = getWindow(node).Element;
    return node instanceof OwnElement || node instanceof Element;
  }
  function isHTMLElement(node) {
    var OwnElement = getWindow(node).HTMLElement;
    return node instanceof OwnElement || node instanceof HTMLElement;
  }
  function isShadowRoot(node) {
    if (typeof ShadowRoot === "undefined") {
      return false;
    }
    var OwnElement = getWindow(node).ShadowRoot;
    return node instanceof OwnElement || node instanceof ShadowRoot;
  }

  // ../../node_modules/@popperjs/core/lib/modifiers/applyStyles.js
  function applyStyles(_ref) {
    var state = _ref.state;
    Object.keys(state.elements).forEach(function(name) {
      var style = state.styles[name] || {};
      var attributes = state.attributes[name] || {};
      var element = state.elements[name];
      if (!isHTMLElement(element) || !getNodeName(element)) {
        return;
      }
      Object.assign(element.style, style);
      Object.keys(attributes).forEach(function(name2) {
        var value = attributes[name2];
        if (value === false) {
          element.removeAttribute(name2);
        } else {
          element.setAttribute(name2, value === true ? "" : value);
        }
      });
    });
  }
  function effect(_ref2) {
    var state = _ref2.state;
    var initialStyles = {
      popper: {
        position: state.options.strategy,
        left: "0",
        top: "0",
        margin: "0"
      },
      arrow: {
        position: "absolute"
      },
      reference: {}
    };
    Object.assign(state.elements.popper.style, initialStyles.popper);
    state.styles = initialStyles;
    if (state.elements.arrow) {
      Object.assign(state.elements.arrow.style, initialStyles.arrow);
    }
    return function() {
      Object.keys(state.elements).forEach(function(name) {
        var element = state.elements[name];
        var attributes = state.attributes[name] || {};
        var styleProperties = Object.keys(state.styles.hasOwnProperty(name) ? state.styles[name] : initialStyles[name]);
        var style = styleProperties.reduce(function(style2, property) {
          style2[property] = "";
          return style2;
        }, {});
        if (!isHTMLElement(element) || !getNodeName(element)) {
          return;
        }
        Object.assign(element.style, style);
        Object.keys(attributes).forEach(function(attribute) {
          element.removeAttribute(attribute);
        });
      });
    };
  }
  var applyStyles_default = {
    name: "applyStyles",
    enabled: true,
    phase: "write",
    fn: applyStyles,
    effect,
    requires: ["computeStyles"]
  };

  // ../../node_modules/@popperjs/core/lib/utils/getBasePlacement.js
  function getBasePlacement(placement) {
    return placement.split("-")[0];
  }

  // ../../node_modules/@popperjs/core/lib/utils/math.js
  var max = Math.max;
  var min = Math.min;
  var round = Math.round;

  // ../../node_modules/@popperjs/core/lib/dom-utils/getBoundingClientRect.js
  function getBoundingClientRect(element, includeScale) {
    if (includeScale === void 0) {
      includeScale = false;
    }
    var rect = element.getBoundingClientRect();
    var scaleX = 1;
    var scaleY = 1;
    if (isHTMLElement(element) && includeScale) {
      var offsetHeight = element.offsetHeight;
      var offsetWidth = element.offsetWidth;
      if (offsetWidth > 0) {
        scaleX = round(rect.width) / offsetWidth || 1;
      }
      if (offsetHeight > 0) {
        scaleY = round(rect.height) / offsetHeight || 1;
      }
    }
    return {
      width: rect.width / scaleX,
      height: rect.height / scaleY,
      top: rect.top / scaleY,
      right: rect.right / scaleX,
      bottom: rect.bottom / scaleY,
      left: rect.left / scaleX,
      x: rect.left / scaleX,
      y: rect.top / scaleY
    };
  }

  // ../../node_modules/@popperjs/core/lib/dom-utils/getLayoutRect.js
  function getLayoutRect(element) {
    var clientRect = getBoundingClientRect(element);
    var width = element.offsetWidth;
    var height = element.offsetHeight;
    if (Math.abs(clientRect.width - width) <= 1) {
      width = clientRect.width;
    }
    if (Math.abs(clientRect.height - height) <= 1) {
      height = clientRect.height;
    }
    return {
      x: element.offsetLeft,
      y: element.offsetTop,
      width,
      height
    };
  }

  // ../../node_modules/@popperjs/core/lib/dom-utils/contains.js
  function contains(parent, child) {
    var rootNode = child.getRootNode && child.getRootNode();
    if (parent.contains(child)) {
      return true;
    } else if (rootNode && isShadowRoot(rootNode)) {
      var next = child;
      do {
        if (next && parent.isSameNode(next)) {
          return true;
        }
        next = next.parentNode || next.host;
      } while (next);
    }
    return false;
  }

  // ../../node_modules/@popperjs/core/lib/dom-utils/getComputedStyle.js
  function getComputedStyle2(element) {
    return getWindow(element).getComputedStyle(element);
  }

  // ../../node_modules/@popperjs/core/lib/dom-utils/isTableElement.js
  function isTableElement(element) {
    return ["table", "td", "th"].indexOf(getNodeName(element)) >= 0;
  }

  // ../../node_modules/@popperjs/core/lib/dom-utils/getDocumentElement.js
  function getDocumentElement(element) {
    return ((isElement(element) ? element.ownerDocument : element.document) || window.document).documentElement;
  }

  // ../../node_modules/@popperjs/core/lib/dom-utils/getParentNode.js
  function getParentNode(element) {
    if (getNodeName(element) === "html") {
      return element;
    }
    return element.assignedSlot || element.parentNode || (isShadowRoot(element) ? element.host : null) || getDocumentElement(element);
  }

  // ../../node_modules/@popperjs/core/lib/dom-utils/getOffsetParent.js
  function getTrueOffsetParent(element) {
    if (!isHTMLElement(element) || getComputedStyle2(element).position === "fixed") {
      return null;
    }
    return element.offsetParent;
  }
  function getContainingBlock(element) {
    var isFirefox = navigator.userAgent.toLowerCase().indexOf("firefox") !== -1;
    var isIE = navigator.userAgent.indexOf("Trident") !== -1;
    if (isIE && isHTMLElement(element)) {
      var elementCss = getComputedStyle2(element);
      if (elementCss.position === "fixed") {
        return null;
      }
    }
    var currentNode = getParentNode(element);
    while (isHTMLElement(currentNode) && ["html", "body"].indexOf(getNodeName(currentNode)) < 0) {
      var css = getComputedStyle2(currentNode);
      if (css.transform !== "none" || css.perspective !== "none" || css.contain === "paint" || ["transform", "perspective"].indexOf(css.willChange) !== -1 || isFirefox && css.willChange === "filter" || isFirefox && css.filter && css.filter !== "none") {
        return currentNode;
      } else {
        currentNode = currentNode.parentNode;
      }
    }
    return null;
  }
  function getOffsetParent(element) {
    var window2 = getWindow(element);
    var offsetParent = getTrueOffsetParent(element);
    while (offsetParent && isTableElement(offsetParent) && getComputedStyle2(offsetParent).position === "static") {
      offsetParent = getTrueOffsetParent(offsetParent);
    }
    if (offsetParent && (getNodeName(offsetParent) === "html" || getNodeName(offsetParent) === "body" && getComputedStyle2(offsetParent).position === "static")) {
      return window2;
    }
    return offsetParent || getContainingBlock(element) || window2;
  }

  // ../../node_modules/@popperjs/core/lib/utils/getMainAxisFromPlacement.js
  function getMainAxisFromPlacement(placement) {
    return ["top", "bottom"].indexOf(placement) >= 0 ? "x" : "y";
  }

  // ../../node_modules/@popperjs/core/lib/utils/within.js
  function within(min2, value, max2) {
    return max(min2, min(value, max2));
  }
  function withinMaxClamp(min2, value, max2) {
    var v2 = within(min2, value, max2);
    return v2 > max2 ? max2 : v2;
  }

  // ../../node_modules/@popperjs/core/lib/utils/getFreshSideObject.js
  function getFreshSideObject() {
    return {
      top: 0,
      right: 0,
      bottom: 0,
      left: 0
    };
  }

  // ../../node_modules/@popperjs/core/lib/utils/mergePaddingObject.js
  function mergePaddingObject(paddingObject) {
    return Object.assign({}, getFreshSideObject(), paddingObject);
  }

  // ../../node_modules/@popperjs/core/lib/utils/expandToHashMap.js
  function expandToHashMap(value, keys) {
    return keys.reduce(function(hashMap, key) {
      hashMap[key] = value;
      return hashMap;
    }, {});
  }

  // ../../node_modules/@popperjs/core/lib/modifiers/arrow.js
  var toPaddingObject = function toPaddingObject2(padding, state) {
    padding = typeof padding === "function" ? padding(Object.assign({}, state.rects, {
      placement: state.placement
    })) : padding;
    return mergePaddingObject(typeof padding !== "number" ? padding : expandToHashMap(padding, basePlacements));
  };
  function arrow(_ref) {
    var _state$modifiersData$;
    var state = _ref.state, name = _ref.name, options = _ref.options;
    var arrowElement = state.elements.arrow;
    var popperOffsets2 = state.modifiersData.popperOffsets;
    var basePlacement = getBasePlacement(state.placement);
    var axis = getMainAxisFromPlacement(basePlacement);
    var isVertical = [left, right].indexOf(basePlacement) >= 0;
    var len = isVertical ? "height" : "width";
    if (!arrowElement || !popperOffsets2) {
      return;
    }
    var paddingObject = toPaddingObject(options.padding, state);
    var arrowRect = getLayoutRect(arrowElement);
    var minProp = axis === "y" ? top : left;
    var maxProp = axis === "y" ? bottom : right;
    var endDiff = state.rects.reference[len] + state.rects.reference[axis] - popperOffsets2[axis] - state.rects.popper[len];
    var startDiff = popperOffsets2[axis] - state.rects.reference[axis];
    var arrowOffsetParent = getOffsetParent(arrowElement);
    var clientSize = arrowOffsetParent ? axis === "y" ? arrowOffsetParent.clientHeight || 0 : arrowOffsetParent.clientWidth || 0 : 0;
    var centerToReference = endDiff / 2 - startDiff / 2;
    var min2 = paddingObject[minProp];
    var max2 = clientSize - arrowRect[len] - paddingObject[maxProp];
    var center = clientSize / 2 - arrowRect[len] / 2 + centerToReference;
    var offset2 = within(min2, center, max2);
    var axisProp = axis;
    state.modifiersData[name] = (_state$modifiersData$ = {}, _state$modifiersData$[axisProp] = offset2, _state$modifiersData$.centerOffset = offset2 - center, _state$modifiersData$);
  }
  function effect2(_ref2) {
    var state = _ref2.state, options = _ref2.options;
    var _options$element = options.element, arrowElement = _options$element === void 0 ? "[data-popper-arrow]" : _options$element;
    if (arrowElement == null) {
      return;
    }
    if (typeof arrowElement === "string") {
      arrowElement = state.elements.popper.querySelector(arrowElement);
      if (!arrowElement) {
        return;
      }
    }
    if (true) {
      if (!isHTMLElement(arrowElement)) {
        console.error(['Popper: "arrow" element must be an HTMLElement (not an SVGElement).', "To use an SVG arrow, wrap it in an HTMLElement that will be used as", "the arrow."].join(" "));
      }
    }
    if (!contains(state.elements.popper, arrowElement)) {
      if (true) {
        console.error(['Popper: "arrow" modifier\'s `element` must be a child of the popper', "element."].join(" "));
      }
      return;
    }
    state.elements.arrow = arrowElement;
  }
  var arrow_default = {
    name: "arrow",
    enabled: true,
    phase: "main",
    fn: arrow,
    effect: effect2,
    requires: ["popperOffsets"],
    requiresIfExists: ["preventOverflow"]
  };

  // ../../node_modules/@popperjs/core/lib/utils/getVariation.js
  function getVariation(placement) {
    return placement.split("-")[1];
  }

  // ../../node_modules/@popperjs/core/lib/modifiers/computeStyles.js
  var unsetSides = {
    top: "auto",
    right: "auto",
    bottom: "auto",
    left: "auto"
  };
  function roundOffsetsByDPR(_ref) {
    var x2 = _ref.x, y2 = _ref.y;
    var win = window;
    var dpr = win.devicePixelRatio || 1;
    return {
      x: round(x2 * dpr) / dpr || 0,
      y: round(y2 * dpr) / dpr || 0
    };
  }
  function mapToStyles(_ref2) {
    var _Object$assign2;
    var popper2 = _ref2.popper, popperRect = _ref2.popperRect, placement = _ref2.placement, variation = _ref2.variation, offsets = _ref2.offsets, position = _ref2.position, gpuAcceleration = _ref2.gpuAcceleration, adaptive = _ref2.adaptive, roundOffsets = _ref2.roundOffsets, isFixed = _ref2.isFixed;
    var _offsets$x = offsets.x, x2 = _offsets$x === void 0 ? 0 : _offsets$x, _offsets$y = offsets.y, y2 = _offsets$y === void 0 ? 0 : _offsets$y;
    var _ref3 = typeof roundOffsets === "function" ? roundOffsets({
      x: x2,
      y: y2
    }) : {
      x: x2,
      y: y2
    };
    x2 = _ref3.x;
    y2 = _ref3.y;
    var hasX = offsets.hasOwnProperty("x");
    var hasY = offsets.hasOwnProperty("y");
    var sideX = left;
    var sideY = top;
    var win = window;
    if (adaptive) {
      var offsetParent = getOffsetParent(popper2);
      var heightProp = "clientHeight";
      var widthProp = "clientWidth";
      if (offsetParent === getWindow(popper2)) {
        offsetParent = getDocumentElement(popper2);
        if (getComputedStyle2(offsetParent).position !== "static" && position === "absolute") {
          heightProp = "scrollHeight";
          widthProp = "scrollWidth";
        }
      }
      offsetParent = offsetParent;
      if (placement === top || (placement === left || placement === right) && variation === end) {
        sideY = bottom;
        var offsetY = isFixed && win.visualViewport ? win.visualViewport.height : offsetParent[heightProp];
        y2 -= offsetY - popperRect.height;
        y2 *= gpuAcceleration ? 1 : -1;
      }
      if (placement === left || (placement === top || placement === bottom) && variation === end) {
        sideX = right;
        var offsetX = isFixed && win.visualViewport ? win.visualViewport.width : offsetParent[widthProp];
        x2 -= offsetX - popperRect.width;
        x2 *= gpuAcceleration ? 1 : -1;
      }
    }
    var commonStyles = Object.assign({
      position
    }, adaptive && unsetSides);
    var _ref4 = roundOffsets === true ? roundOffsetsByDPR({
      x: x2,
      y: y2
    }) : {
      x: x2,
      y: y2
    };
    x2 = _ref4.x;
    y2 = _ref4.y;
    if (gpuAcceleration) {
      var _Object$assign;
      return Object.assign({}, commonStyles, (_Object$assign = {}, _Object$assign[sideY] = hasY ? "0" : "", _Object$assign[sideX] = hasX ? "0" : "", _Object$assign.transform = (win.devicePixelRatio || 1) <= 1 ? "translate(" + x2 + "px, " + y2 + "px)" : "translate3d(" + x2 + "px, " + y2 + "px, 0)", _Object$assign));
    }
    return Object.assign({}, commonStyles, (_Object$assign2 = {}, _Object$assign2[sideY] = hasY ? y2 + "px" : "", _Object$assign2[sideX] = hasX ? x2 + "px" : "", _Object$assign2.transform = "", _Object$assign2));
  }
  function computeStyles(_ref5) {
    var state = _ref5.state, options = _ref5.options;
    var _options$gpuAccelerat = options.gpuAcceleration, gpuAcceleration = _options$gpuAccelerat === void 0 ? true : _options$gpuAccelerat, _options$adaptive = options.adaptive, adaptive = _options$adaptive === void 0 ? true : _options$adaptive, _options$roundOffsets = options.roundOffsets, roundOffsets = _options$roundOffsets === void 0 ? true : _options$roundOffsets;
    if (true) {
      var transitionProperty = getComputedStyle2(state.elements.popper).transitionProperty || "";
      if (adaptive && ["transform", "top", "right", "bottom", "left"].some(function(property) {
        return transitionProperty.indexOf(property) >= 0;
      })) {
        console.warn(["Popper: Detected CSS transitions on at least one of the following", 'CSS properties: "transform", "top", "right", "bottom", "left".', "\n\n", 'Disable the "computeStyles" modifier\'s `adaptive` option to allow', "for smooth transitions, or remove these properties from the CSS", "transition declaration on the popper element if only transitioning", "opacity or background-color for example.", "\n\n", "We recommend using the popper element as a wrapper around an inner", "element that can have any CSS property transitioned for animations."].join(" "));
      }
    }
    var commonStyles = {
      placement: getBasePlacement(state.placement),
      variation: getVariation(state.placement),
      popper: state.elements.popper,
      popperRect: state.rects.popper,
      gpuAcceleration,
      isFixed: state.options.strategy === "fixed"
    };
    if (state.modifiersData.popperOffsets != null) {
      state.styles.popper = Object.assign({}, state.styles.popper, mapToStyles(Object.assign({}, commonStyles, {
        offsets: state.modifiersData.popperOffsets,
        position: state.options.strategy,
        adaptive,
        roundOffsets
      })));
    }
    if (state.modifiersData.arrow != null) {
      state.styles.arrow = Object.assign({}, state.styles.arrow, mapToStyles(Object.assign({}, commonStyles, {
        offsets: state.modifiersData.arrow,
        position: "absolute",
        adaptive: false,
        roundOffsets
      })));
    }
    state.attributes.popper = Object.assign({}, state.attributes.popper, {
      "data-popper-placement": state.placement
    });
  }
  var computeStyles_default = {
    name: "computeStyles",
    enabled: true,
    phase: "beforeWrite",
    fn: computeStyles,
    data: {}
  };

  // ../../node_modules/@popperjs/core/lib/modifiers/eventListeners.js
  var passive = {
    passive: true
  };
  function effect3(_ref) {
    var state = _ref.state, instance = _ref.instance, options = _ref.options;
    var _options$scroll = options.scroll, scroll = _options$scroll === void 0 ? true : _options$scroll, _options$resize = options.resize, resize = _options$resize === void 0 ? true : _options$resize;
    var window2 = getWindow(state.elements.popper);
    var scrollParents = [].concat(state.scrollParents.reference, state.scrollParents.popper);
    if (scroll) {
      scrollParents.forEach(function(scrollParent) {
        scrollParent.addEventListener("scroll", instance.update, passive);
      });
    }
    if (resize) {
      window2.addEventListener("resize", instance.update, passive);
    }
    return function() {
      if (scroll) {
        scrollParents.forEach(function(scrollParent) {
          scrollParent.removeEventListener("scroll", instance.update, passive);
        });
      }
      if (resize) {
        window2.removeEventListener("resize", instance.update, passive);
      }
    };
  }
  var eventListeners_default = {
    name: "eventListeners",
    enabled: true,
    phase: "write",
    fn: function fn() {
    },
    effect: effect3,
    data: {}
  };

  // ../../node_modules/@popperjs/core/lib/utils/getOppositePlacement.js
  var hash = {
    left: "right",
    right: "left",
    bottom: "top",
    top: "bottom"
  };
  function getOppositePlacement(placement) {
    return placement.replace(/left|right|bottom|top/g, function(matched) {
      return hash[matched];
    });
  }

  // ../../node_modules/@popperjs/core/lib/utils/getOppositeVariationPlacement.js
  var hash2 = {
    start: "end",
    end: "start"
  };
  function getOppositeVariationPlacement(placement) {
    return placement.replace(/start|end/g, function(matched) {
      return hash2[matched];
    });
  }

  // ../../node_modules/@popperjs/core/lib/dom-utils/getWindowScroll.js
  function getWindowScroll(node) {
    var win = getWindow(node);
    var scrollLeft = win.pageXOffset;
    var scrollTop = win.pageYOffset;
    return {
      scrollLeft,
      scrollTop
    };
  }

  // ../../node_modules/@popperjs/core/lib/dom-utils/getWindowScrollBarX.js
  function getWindowScrollBarX(element) {
    return getBoundingClientRect(getDocumentElement(element)).left + getWindowScroll(element).scrollLeft;
  }

  // ../../node_modules/@popperjs/core/lib/dom-utils/getViewportRect.js
  function getViewportRect(element) {
    var win = getWindow(element);
    var html = getDocumentElement(element);
    var visualViewport = win.visualViewport;
    var width = html.clientWidth;
    var height = html.clientHeight;
    var x2 = 0;
    var y2 = 0;
    if (visualViewport) {
      width = visualViewport.width;
      height = visualViewport.height;
      if (!/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {
        x2 = visualViewport.offsetLeft;
        y2 = visualViewport.offsetTop;
      }
    }
    return {
      width,
      height,
      x: x2 + getWindowScrollBarX(element),
      y: y2
    };
  }

  // ../../node_modules/@popperjs/core/lib/dom-utils/getDocumentRect.js
  function getDocumentRect(element) {
    var _element$ownerDocumen;
    var html = getDocumentElement(element);
    var winScroll = getWindowScroll(element);
    var body = (_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body;
    var width = max(html.scrollWidth, html.clientWidth, body ? body.scrollWidth : 0, body ? body.clientWidth : 0);
    var height = max(html.scrollHeight, html.clientHeight, body ? body.scrollHeight : 0, body ? body.clientHeight : 0);
    var x2 = -winScroll.scrollLeft + getWindowScrollBarX(element);
    var y2 = -winScroll.scrollTop;
    if (getComputedStyle2(body || html).direction === "rtl") {
      x2 += max(html.clientWidth, body ? body.clientWidth : 0) - width;
    }
    return {
      width,
      height,
      x: x2,
      y: y2
    };
  }

  // ../../node_modules/@popperjs/core/lib/dom-utils/isScrollParent.js
  function isScrollParent(element) {
    var _getComputedStyle = getComputedStyle2(element), overflow = _getComputedStyle.overflow, overflowX = _getComputedStyle.overflowX, overflowY = _getComputedStyle.overflowY;
    return /auto|scroll|overlay|hidden/.test(overflow + overflowY + overflowX);
  }

  // ../../node_modules/@popperjs/core/lib/dom-utils/getScrollParent.js
  function getScrollParent(node) {
    if (["html", "body", "#document"].indexOf(getNodeName(node)) >= 0) {
      return node.ownerDocument.body;
    }
    if (isHTMLElement(node) && isScrollParent(node)) {
      return node;
    }
    return getScrollParent(getParentNode(node));
  }

  // ../../node_modules/@popperjs/core/lib/dom-utils/listScrollParents.js
  function listScrollParents(element, list) {
    var _element$ownerDocumen;
    if (list === void 0) {
      list = [];
    }
    var scrollParent = getScrollParent(element);
    var isBody = scrollParent === ((_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body);
    var win = getWindow(scrollParent);
    var target = isBody ? [win].concat(win.visualViewport || [], isScrollParent(scrollParent) ? scrollParent : []) : scrollParent;
    var updatedList = list.concat(target);
    return isBody ? updatedList : updatedList.concat(listScrollParents(getParentNode(target)));
  }

  // ../../node_modules/@popperjs/core/lib/utils/rectToClientRect.js
  function rectToClientRect(rect) {
    return Object.assign({}, rect, {
      left: rect.x,
      top: rect.y,
      right: rect.x + rect.width,
      bottom: rect.y + rect.height
    });
  }

  // ../../node_modules/@popperjs/core/lib/dom-utils/getClippingRect.js
  function getInnerBoundingClientRect(element) {
    var rect = getBoundingClientRect(element);
    rect.top = rect.top + element.clientTop;
    rect.left = rect.left + element.clientLeft;
    rect.bottom = rect.top + element.clientHeight;
    rect.right = rect.left + element.clientWidth;
    rect.width = element.clientWidth;
    rect.height = element.clientHeight;
    rect.x = rect.left;
    rect.y = rect.top;
    return rect;
  }
  function getClientRectFromMixedType(element, clippingParent) {
    return clippingParent === viewport ? rectToClientRect(getViewportRect(element)) : isElement(clippingParent) ? getInnerBoundingClientRect(clippingParent) : rectToClientRect(getDocumentRect(getDocumentElement(element)));
  }
  function getClippingParents(element) {
    var clippingParents2 = listScrollParents(getParentNode(element));
    var canEscapeClipping = ["absolute", "fixed"].indexOf(getComputedStyle2(element).position) >= 0;
    var clipperElement = canEscapeClipping && isHTMLElement(element) ? getOffsetParent(element) : element;
    if (!isElement(clipperElement)) {
      return [];
    }
    return clippingParents2.filter(function(clippingParent) {
      return isElement(clippingParent) && contains(clippingParent, clipperElement) && getNodeName(clippingParent) !== "body";
    });
  }
  function getClippingRect(element, boundary, rootBoundary) {
    var mainClippingParents = boundary === "clippingParents" ? getClippingParents(element) : [].concat(boundary);
    var clippingParents2 = [].concat(mainClippingParents, [rootBoundary]);
    var firstClippingParent = clippingParents2[0];
    var clippingRect = clippingParents2.reduce(function(accRect, clippingParent) {
      var rect = getClientRectFromMixedType(element, clippingParent);
      accRect.top = max(rect.top, accRect.top);
      accRect.right = min(rect.right, accRect.right);
      accRect.bottom = min(rect.bottom, accRect.bottom);
      accRect.left = max(rect.left, accRect.left);
      return accRect;
    }, getClientRectFromMixedType(element, firstClippingParent));
    clippingRect.width = clippingRect.right - clippingRect.left;
    clippingRect.height = clippingRect.bottom - clippingRect.top;
    clippingRect.x = clippingRect.left;
    clippingRect.y = clippingRect.top;
    return clippingRect;
  }

  // ../../node_modules/@popperjs/core/lib/utils/computeOffsets.js
  function computeOffsets(_ref) {
    var reference2 = _ref.reference, element = _ref.element, placement = _ref.placement;
    var basePlacement = placement ? getBasePlacement(placement) : null;
    var variation = placement ? getVariation(placement) : null;
    var commonX = reference2.x + reference2.width / 2 - element.width / 2;
    var commonY = reference2.y + reference2.height / 2 - element.height / 2;
    var offsets;
    switch (basePlacement) {
      case top:
        offsets = {
          x: commonX,
          y: reference2.y - element.height
        };
        break;
      case bottom:
        offsets = {
          x: commonX,
          y: reference2.y + reference2.height
        };
        break;
      case right:
        offsets = {
          x: reference2.x + reference2.width,
          y: commonY
        };
        break;
      case left:
        offsets = {
          x: reference2.x - element.width,
          y: commonY
        };
        break;
      default:
        offsets = {
          x: reference2.x,
          y: reference2.y
        };
    }
    var mainAxis = basePlacement ? getMainAxisFromPlacement(basePlacement) : null;
    if (mainAxis != null) {
      var len = mainAxis === "y" ? "height" : "width";
      switch (variation) {
        case start2:
          offsets[mainAxis] = offsets[mainAxis] - (reference2[len] / 2 - element[len] / 2);
          break;
        case end:
          offsets[mainAxis] = offsets[mainAxis] + (reference2[len] / 2 - element[len] / 2);
          break;
        default:
      }
    }
    return offsets;
  }

  // ../../node_modules/@popperjs/core/lib/utils/detectOverflow.js
  function detectOverflow(state, options) {
    if (options === void 0) {
      options = {};
    }
    var _options = options, _options$placement = _options.placement, placement = _options$placement === void 0 ? state.placement : _options$placement, _options$boundary = _options.boundary, boundary = _options$boundary === void 0 ? clippingParents : _options$boundary, _options$rootBoundary = _options.rootBoundary, rootBoundary = _options$rootBoundary === void 0 ? viewport : _options$rootBoundary, _options$elementConte = _options.elementContext, elementContext = _options$elementConte === void 0 ? popper : _options$elementConte, _options$altBoundary = _options.altBoundary, altBoundary = _options$altBoundary === void 0 ? false : _options$altBoundary, _options$padding = _options.padding, padding = _options$padding === void 0 ? 0 : _options$padding;
    var paddingObject = mergePaddingObject(typeof padding !== "number" ? padding : expandToHashMap(padding, basePlacements));
    var altContext = elementContext === popper ? reference : popper;
    var popperRect = state.rects.popper;
    var element = state.elements[altBoundary ? altContext : elementContext];
    var clippingClientRect = getClippingRect(isElement(element) ? element : element.contextElement || getDocumentElement(state.elements.popper), boundary, rootBoundary);
    var referenceClientRect = getBoundingClientRect(state.elements.reference);
    var popperOffsets2 = computeOffsets({
      reference: referenceClientRect,
      element: popperRect,
      strategy: "absolute",
      placement
    });
    var popperClientRect = rectToClientRect(Object.assign({}, popperRect, popperOffsets2));
    var elementClientRect = elementContext === popper ? popperClientRect : referenceClientRect;
    var overflowOffsets = {
      top: clippingClientRect.top - elementClientRect.top + paddingObject.top,
      bottom: elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom,
      left: clippingClientRect.left - elementClientRect.left + paddingObject.left,
      right: elementClientRect.right - clippingClientRect.right + paddingObject.right
    };
    var offsetData = state.modifiersData.offset;
    if (elementContext === popper && offsetData) {
      var offset2 = offsetData[placement];
      Object.keys(overflowOffsets).forEach(function(key) {
        var multiply = [right, bottom].indexOf(key) >= 0 ? 1 : -1;
        var axis = [top, bottom].indexOf(key) >= 0 ? "y" : "x";
        overflowOffsets[key] += offset2[axis] * multiply;
      });
    }
    return overflowOffsets;
  }

  // ../../node_modules/@popperjs/core/lib/utils/computeAutoPlacement.js
  function computeAutoPlacement(state, options) {
    if (options === void 0) {
      options = {};
    }
    var _options = options, placement = _options.placement, boundary = _options.boundary, rootBoundary = _options.rootBoundary, padding = _options.padding, flipVariations = _options.flipVariations, _options$allowedAutoP = _options.allowedAutoPlacements, allowedAutoPlacements = _options$allowedAutoP === void 0 ? placements : _options$allowedAutoP;
    var variation = getVariation(placement);
    var placements2 = variation ? flipVariations ? variationPlacements : variationPlacements.filter(function(placement2) {
      return getVariation(placement2) === variation;
    }) : basePlacements;
    var allowedPlacements = placements2.filter(function(placement2) {
      return allowedAutoPlacements.indexOf(placement2) >= 0;
    });
    if (allowedPlacements.length === 0) {
      allowedPlacements = placements2;
      if (true) {
        console.error(["Popper: The `allowedAutoPlacements` option did not allow any", "placements. Ensure the `placement` option matches the variation", "of the allowed placements.", 'For example, "auto" cannot be used to allow "bottom-start".', 'Use "auto-start" instead.'].join(" "));
      }
    }
    var overflows = allowedPlacements.reduce(function(acc, placement2) {
      acc[placement2] = detectOverflow(state, {
        placement: placement2,
        boundary,
        rootBoundary,
        padding
      })[getBasePlacement(placement2)];
      return acc;
    }, {});
    return Object.keys(overflows).sort(function(a2, b2) {
      return overflows[a2] - overflows[b2];
    });
  }

  // ../../node_modules/@popperjs/core/lib/modifiers/flip.js
  function getExpandedFallbackPlacements(placement) {
    if (getBasePlacement(placement) === auto) {
      return [];
    }
    var oppositePlacement = getOppositePlacement(placement);
    return [getOppositeVariationPlacement(placement), oppositePlacement, getOppositeVariationPlacement(oppositePlacement)];
  }
  function flip(_ref) {
    var state = _ref.state, options = _ref.options, name = _ref.name;
    if (state.modifiersData[name]._skip) {
      return;
    }
    var _options$mainAxis = options.mainAxis, checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis, _options$altAxis = options.altAxis, checkAltAxis = _options$altAxis === void 0 ? true : _options$altAxis, specifiedFallbackPlacements = options.fallbackPlacements, padding = options.padding, boundary = options.boundary, rootBoundary = options.rootBoundary, altBoundary = options.altBoundary, _options$flipVariatio = options.flipVariations, flipVariations = _options$flipVariatio === void 0 ? true : _options$flipVariatio, allowedAutoPlacements = options.allowedAutoPlacements;
    var preferredPlacement = state.options.placement;
    var basePlacement = getBasePlacement(preferredPlacement);
    var isBasePlacement = basePlacement === preferredPlacement;
    var fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipVariations ? [getOppositePlacement(preferredPlacement)] : getExpandedFallbackPlacements(preferredPlacement));
    var placements2 = [preferredPlacement].concat(fallbackPlacements).reduce(function(acc, placement2) {
      return acc.concat(getBasePlacement(placement2) === auto ? computeAutoPlacement(state, {
        placement: placement2,
        boundary,
        rootBoundary,
        padding,
        flipVariations,
        allowedAutoPlacements
      }) : placement2);
    }, []);
    var referenceRect = state.rects.reference;
    var popperRect = state.rects.popper;
    var checksMap = /* @__PURE__ */ new Map();
    var makeFallbackChecks = true;
    var firstFittingPlacement = placements2[0];
    for (var i2 = 0; i2 < placements2.length; i2++) {
      var placement = placements2[i2];
      var _basePlacement = getBasePlacement(placement);
      var isStartVariation = getVariation(placement) === start2;
      var isVertical = [top, bottom].indexOf(_basePlacement) >= 0;
      var len = isVertical ? "width" : "height";
      var overflow = detectOverflow(state, {
        placement,
        boundary,
        rootBoundary,
        altBoundary,
        padding
      });
      var mainVariationSide = isVertical ? isStartVariation ? right : left : isStartVariation ? bottom : top;
      if (referenceRect[len] > popperRect[len]) {
        mainVariationSide = getOppositePlacement(mainVariationSide);
      }
      var altVariationSide = getOppositePlacement(mainVariationSide);
      var checks = [];
      if (checkMainAxis) {
        checks.push(overflow[_basePlacement] <= 0);
      }
      if (checkAltAxis) {
        checks.push(overflow[mainVariationSide] <= 0, overflow[altVariationSide] <= 0);
      }
      if (checks.every(function(check) {
        return check;
      })) {
        firstFittingPlacement = placement;
        makeFallbackChecks = false;
        break;
      }
      checksMap.set(placement, checks);
    }
    if (makeFallbackChecks) {
      var numberOfChecks = flipVariations ? 3 : 1;
      var _loop = function _loop2(_i3) {
        var fittingPlacement = placements2.find(function(placement2) {
          var checks2 = checksMap.get(placement2);
          if (checks2) {
            return checks2.slice(0, _i3).every(function(check) {
              return check;
            });
          }
        });
        if (fittingPlacement) {
          firstFittingPlacement = fittingPlacement;
          return "break";
        }
      };
      for (var _i2 = numberOfChecks; _i2 > 0; _i2--) {
        var _ret = _loop(_i2);
        if (_ret === "break")
          break;
      }
    }
    if (state.placement !== firstFittingPlacement) {
      state.modifiersData[name]._skip = true;
      state.placement = firstFittingPlacement;
      state.reset = true;
    }
  }
  var flip_default = {
    name: "flip",
    enabled: true,
    phase: "main",
    fn: flip,
    requiresIfExists: ["offset"],
    data: {
      _skip: false
    }
  };

  // ../../node_modules/@popperjs/core/lib/modifiers/hide.js
  function getSideOffsets(overflow, rect, preventedOffsets) {
    if (preventedOffsets === void 0) {
      preventedOffsets = {
        x: 0,
        y: 0
      };
    }
    return {
      top: overflow.top - rect.height - preventedOffsets.y,
      right: overflow.right - rect.width + preventedOffsets.x,
      bottom: overflow.bottom - rect.height + preventedOffsets.y,
      left: overflow.left - rect.width - preventedOffsets.x
    };
  }
  function isAnySideFullyClipped(overflow) {
    return [top, right, bottom, left].some(function(side) {
      return overflow[side] >= 0;
    });
  }
  function hide(_ref) {
    var state = _ref.state, name = _ref.name;
    var referenceRect = state.rects.reference;
    var popperRect = state.rects.popper;
    var preventedOffsets = state.modifiersData.preventOverflow;
    var referenceOverflow = detectOverflow(state, {
      elementContext: "reference"
    });
    var popperAltOverflow = detectOverflow(state, {
      altBoundary: true
    });
    var referenceClippingOffsets = getSideOffsets(referenceOverflow, referenceRect);
    var popperEscapeOffsets = getSideOffsets(popperAltOverflow, popperRect, preventedOffsets);
    var isReferenceHidden = isAnySideFullyClipped(referenceClippingOffsets);
    var hasPopperEscaped = isAnySideFullyClipped(popperEscapeOffsets);
    state.modifiersData[name] = {
      referenceClippingOffsets,
      popperEscapeOffsets,
      isReferenceHidden,
      hasPopperEscaped
    };
    state.attributes.popper = Object.assign({}, state.attributes.popper, {
      "data-popper-reference-hidden": isReferenceHidden,
      "data-popper-escaped": hasPopperEscaped
    });
  }
  var hide_default = {
    name: "hide",
    enabled: true,
    phase: "main",
    requiresIfExists: ["preventOverflow"],
    fn: hide
  };

  // ../../node_modules/@popperjs/core/lib/modifiers/offset.js
  function distanceAndSkiddingToXY(placement, rects, offset2) {
    var basePlacement = getBasePlacement(placement);
    var invertDistance = [left, top].indexOf(basePlacement) >= 0 ? -1 : 1;
    var _ref = typeof offset2 === "function" ? offset2(Object.assign({}, rects, {
      placement
    })) : offset2, skidding = _ref[0], distance = _ref[1];
    skidding = skidding || 0;
    distance = (distance || 0) * invertDistance;
    return [left, right].indexOf(basePlacement) >= 0 ? {
      x: distance,
      y: skidding
    } : {
      x: skidding,
      y: distance
    };
  }
  function offset(_ref2) {
    var state = _ref2.state, options = _ref2.options, name = _ref2.name;
    var _options$offset = options.offset, offset2 = _options$offset === void 0 ? [0, 0] : _options$offset;
    var data = placements.reduce(function(acc, placement) {
      acc[placement] = distanceAndSkiddingToXY(placement, state.rects, offset2);
      return acc;
    }, {});
    var _data$state$placement = data[state.placement], x2 = _data$state$placement.x, y2 = _data$state$placement.y;
    if (state.modifiersData.popperOffsets != null) {
      state.modifiersData.popperOffsets.x += x2;
      state.modifiersData.popperOffsets.y += y2;
    }
    state.modifiersData[name] = data;
  }
  var offset_default = {
    name: "offset",
    enabled: true,
    phase: "main",
    requires: ["popperOffsets"],
    fn: offset
  };

  // ../../node_modules/@popperjs/core/lib/modifiers/popperOffsets.js
  function popperOffsets(_ref) {
    var state = _ref.state, name = _ref.name;
    state.modifiersData[name] = computeOffsets({
      reference: state.rects.reference,
      element: state.rects.popper,
      strategy: "absolute",
      placement: state.placement
    });
  }
  var popperOffsets_default = {
    name: "popperOffsets",
    enabled: true,
    phase: "read",
    fn: popperOffsets,
    data: {}
  };

  // ../../node_modules/@popperjs/core/lib/utils/getAltAxis.js
  function getAltAxis(axis) {
    return axis === "x" ? "y" : "x";
  }

  // ../../node_modules/@popperjs/core/lib/modifiers/preventOverflow.js
  function preventOverflow(_ref) {
    var state = _ref.state, options = _ref.options, name = _ref.name;
    var _options$mainAxis = options.mainAxis, checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis, _options$altAxis = options.altAxis, checkAltAxis = _options$altAxis === void 0 ? false : _options$altAxis, boundary = options.boundary, rootBoundary = options.rootBoundary, altBoundary = options.altBoundary, padding = options.padding, _options$tether = options.tether, tether = _options$tether === void 0 ? true : _options$tether, _options$tetherOffset = options.tetherOffset, tetherOffset = _options$tetherOffset === void 0 ? 0 : _options$tetherOffset;
    var overflow = detectOverflow(state, {
      boundary,
      rootBoundary,
      padding,
      altBoundary
    });
    var basePlacement = getBasePlacement(state.placement);
    var variation = getVariation(state.placement);
    var isBasePlacement = !variation;
    var mainAxis = getMainAxisFromPlacement(basePlacement);
    var altAxis = getAltAxis(mainAxis);
    var popperOffsets2 = state.modifiersData.popperOffsets;
    var referenceRect = state.rects.reference;
    var popperRect = state.rects.popper;
    var tetherOffsetValue = typeof tetherOffset === "function" ? tetherOffset(Object.assign({}, state.rects, {
      placement: state.placement
    })) : tetherOffset;
    var normalizedTetherOffsetValue = typeof tetherOffsetValue === "number" ? {
      mainAxis: tetherOffsetValue,
      altAxis: tetherOffsetValue
    } : Object.assign({
      mainAxis: 0,
      altAxis: 0
    }, tetherOffsetValue);
    var offsetModifierState = state.modifiersData.offset ? state.modifiersData.offset[state.placement] : null;
    var data = {
      x: 0,
      y: 0
    };
    if (!popperOffsets2) {
      return;
    }
    if (checkMainAxis) {
      var _offsetModifierState$;
      var mainSide = mainAxis === "y" ? top : left;
      var altSide = mainAxis === "y" ? bottom : right;
      var len = mainAxis === "y" ? "height" : "width";
      var offset2 = popperOffsets2[mainAxis];
      var min2 = offset2 + overflow[mainSide];
      var max2 = offset2 - overflow[altSide];
      var additive = tether ? -popperRect[len] / 2 : 0;
      var minLen = variation === start2 ? referenceRect[len] : popperRect[len];
      var maxLen = variation === start2 ? -popperRect[len] : -referenceRect[len];
      var arrowElement = state.elements.arrow;
      var arrowRect = tether && arrowElement ? getLayoutRect(arrowElement) : {
        width: 0,
        height: 0
      };
      var arrowPaddingObject = state.modifiersData["arrow#persistent"] ? state.modifiersData["arrow#persistent"].padding : getFreshSideObject();
      var arrowPaddingMin = arrowPaddingObject[mainSide];
      var arrowPaddingMax = arrowPaddingObject[altSide];
      var arrowLen = within(0, referenceRect[len], arrowRect[len]);
      var minOffset = isBasePlacement ? referenceRect[len] / 2 - additive - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis : minLen - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis;
      var maxOffset = isBasePlacement ? -referenceRect[len] / 2 + additive + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis : maxLen + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis;
      var arrowOffsetParent = state.elements.arrow && getOffsetParent(state.elements.arrow);
      var clientOffset = arrowOffsetParent ? mainAxis === "y" ? arrowOffsetParent.clientTop || 0 : arrowOffsetParent.clientLeft || 0 : 0;
      var offsetModifierValue = (_offsetModifierState$ = offsetModifierState == null ? void 0 : offsetModifierState[mainAxis]) != null ? _offsetModifierState$ : 0;
      var tetherMin = offset2 + minOffset - offsetModifierValue - clientOffset;
      var tetherMax = offset2 + maxOffset - offsetModifierValue;
      var preventedOffset = within(tether ? min(min2, tetherMin) : min2, offset2, tether ? max(max2, tetherMax) : max2);
      popperOffsets2[mainAxis] = preventedOffset;
      data[mainAxis] = preventedOffset - offset2;
    }
    if (checkAltAxis) {
      var _offsetModifierState$2;
      var _mainSide = mainAxis === "x" ? top : left;
      var _altSide = mainAxis === "x" ? bottom : right;
      var _offset = popperOffsets2[altAxis];
      var _len = altAxis === "y" ? "height" : "width";
      var _min = _offset + overflow[_mainSide];
      var _max = _offset - overflow[_altSide];
      var isOriginSide = [top, left].indexOf(basePlacement) !== -1;
      var _offsetModifierValue = (_offsetModifierState$2 = offsetModifierState == null ? void 0 : offsetModifierState[altAxis]) != null ? _offsetModifierState$2 : 0;
      var _tetherMin = isOriginSide ? _min : _offset - referenceRect[_len] - popperRect[_len] - _offsetModifierValue + normalizedTetherOffsetValue.altAxis;
      var _tetherMax = isOriginSide ? _offset + referenceRect[_len] + popperRect[_len] - _offsetModifierValue - normalizedTetherOffsetValue.altAxis : _max;
      var _preventedOffset = tether && isOriginSide ? withinMaxClamp(_tetherMin, _offset, _tetherMax) : within(tether ? _tetherMin : _min, _offset, tether ? _tetherMax : _max);
      popperOffsets2[altAxis] = _preventedOffset;
      data[altAxis] = _preventedOffset - _offset;
    }
    state.modifiersData[name] = data;
  }
  var preventOverflow_default = {
    name: "preventOverflow",
    enabled: true,
    phase: "main",
    fn: preventOverflow,
    requiresIfExists: ["offset"]
  };

  // ../../node_modules/@popperjs/core/lib/dom-utils/getHTMLElementScroll.js
  function getHTMLElementScroll(element) {
    return {
      scrollLeft: element.scrollLeft,
      scrollTop: element.scrollTop
    };
  }

  // ../../node_modules/@popperjs/core/lib/dom-utils/getNodeScroll.js
  function getNodeScroll(node) {
    if (node === getWindow(node) || !isHTMLElement(node)) {
      return getWindowScroll(node);
    } else {
      return getHTMLElementScroll(node);
    }
  }

  // ../../node_modules/@popperjs/core/lib/dom-utils/getCompositeRect.js
  function isElementScaled(element) {
    var rect = element.getBoundingClientRect();
    var scaleX = round(rect.width) / element.offsetWidth || 1;
    var scaleY = round(rect.height) / element.offsetHeight || 1;
    return scaleX !== 1 || scaleY !== 1;
  }
  function getCompositeRect(elementOrVirtualElement, offsetParent, isFixed) {
    if (isFixed === void 0) {
      isFixed = false;
    }
    var isOffsetParentAnElement = isHTMLElement(offsetParent);
    var offsetParentIsScaled = isHTMLElement(offsetParent) && isElementScaled(offsetParent);
    var documentElement = getDocumentElement(offsetParent);
    var rect = getBoundingClientRect(elementOrVirtualElement, offsetParentIsScaled);
    var scroll = {
      scrollLeft: 0,
      scrollTop: 0
    };
    var offsets = {
      x: 0,
      y: 0
    };
    if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
      if (getNodeName(offsetParent) !== "body" || isScrollParent(documentElement)) {
        scroll = getNodeScroll(offsetParent);
      }
      if (isHTMLElement(offsetParent)) {
        offsets = getBoundingClientRect(offsetParent, true);
        offsets.x += offsetParent.clientLeft;
        offsets.y += offsetParent.clientTop;
      } else if (documentElement) {
        offsets.x = getWindowScrollBarX(documentElement);
      }
    }
    return {
      x: rect.left + scroll.scrollLeft - offsets.x,
      y: rect.top + scroll.scrollTop - offsets.y,
      width: rect.width,
      height: rect.height
    };
  }

  // ../../node_modules/@popperjs/core/lib/utils/orderModifiers.js
  function order(modifiers) {
    var map3 = /* @__PURE__ */ new Map();
    var visited = /* @__PURE__ */ new Set();
    var result = [];
    modifiers.forEach(function(modifier) {
      map3.set(modifier.name, modifier);
    });
    function sort(modifier) {
      visited.add(modifier.name);
      var requires = [].concat(modifier.requires || [], modifier.requiresIfExists || []);
      requires.forEach(function(dep) {
        if (!visited.has(dep)) {
          var depModifier = map3.get(dep);
          if (depModifier) {
            sort(depModifier);
          }
        }
      });
      result.push(modifier);
    }
    modifiers.forEach(function(modifier) {
      if (!visited.has(modifier.name)) {
        sort(modifier);
      }
    });
    return result;
  }
  function orderModifiers(modifiers) {
    var orderedModifiers = order(modifiers);
    return modifierPhases.reduce(function(acc, phase) {
      return acc.concat(orderedModifiers.filter(function(modifier) {
        return modifier.phase === phase;
      }));
    }, []);
  }

  // ../../node_modules/@popperjs/core/lib/utils/debounce.js
  function debounce2(fn3) {
    var pending;
    return function() {
      if (!pending) {
        pending = new Promise(function(resolve2) {
          Promise.resolve().then(function() {
            pending = void 0;
            resolve2(fn3());
          });
        });
      }
      return pending;
    };
  }

  // ../../node_modules/@popperjs/core/lib/utils/format.js
  function format(str) {
    for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
      args[_key - 1] = arguments[_key];
    }
    return [].concat(args).reduce(function(p2, c2) {
      return p2.replace(/%s/, c2);
    }, str);
  }

  // ../../node_modules/@popperjs/core/lib/utils/validateModifiers.js
  var INVALID_MODIFIER_ERROR = 'Popper: modifier "%s" provided an invalid %s property, expected %s but got %s';
  var MISSING_DEPENDENCY_ERROR = 'Popper: modifier "%s" requires "%s", but "%s" modifier is not available';
  var VALID_PROPERTIES = ["name", "enabled", "phase", "fn", "effect", "requires", "options"];
  function validateModifiers(modifiers) {
    modifiers.forEach(function(modifier) {
      [].concat(Object.keys(modifier), VALID_PROPERTIES).filter(function(value, index, self2) {
        return self2.indexOf(value) === index;
      }).forEach(function(key) {
        switch (key) {
          case "name":
            if (typeof modifier.name !== "string") {
              console.error(format(INVALID_MODIFIER_ERROR, String(modifier.name), '"name"', '"string"', '"' + String(modifier.name) + '"'));
            }
            break;
          case "enabled":
            if (typeof modifier.enabled !== "boolean") {
              console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"enabled"', '"boolean"', '"' + String(modifier.enabled) + '"'));
            }
            break;
          case "phase":
            if (modifierPhases.indexOf(modifier.phase) < 0) {
              console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"phase"', "either " + modifierPhases.join(", "), '"' + String(modifier.phase) + '"'));
            }
            break;
          case "fn":
            if (typeof modifier.fn !== "function") {
              console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"fn"', '"function"', '"' + String(modifier.fn) + '"'));
            }
            break;
          case "effect":
            if (modifier.effect != null && typeof modifier.effect !== "function") {
              console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"effect"', '"function"', '"' + String(modifier.fn) + '"'));
            }
            break;
          case "requires":
            if (modifier.requires != null && !Array.isArray(modifier.requires)) {
              console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"requires"', '"array"', '"' + String(modifier.requires) + '"'));
            }
            break;
          case "requiresIfExists":
            if (!Array.isArray(modifier.requiresIfExists)) {
              console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"requiresIfExists"', '"array"', '"' + String(modifier.requiresIfExists) + '"'));
            }
            break;
          case "options":
          case "data":
            break;
          default:
            console.error('PopperJS: an invalid property has been provided to the "' + modifier.name + '" modifier, valid properties are ' + VALID_PROPERTIES.map(function(s2) {
              return '"' + s2 + '"';
            }).join(", ") + '; but "' + key + '" was provided.');
        }
        modifier.requires && modifier.requires.forEach(function(requirement) {
          if (modifiers.find(function(mod) {
            return mod.name === requirement;
          }) == null) {
            console.error(format(MISSING_DEPENDENCY_ERROR, String(modifier.name), requirement, requirement));
          }
        });
      });
    });
  }

  // ../../node_modules/@popperjs/core/lib/utils/uniqueBy.js
  function uniqueBy(arr, fn3) {
    var identifiers = /* @__PURE__ */ new Set();
    return arr.filter(function(item) {
      var identifier = fn3(item);
      if (!identifiers.has(identifier)) {
        identifiers.add(identifier);
        return true;
      }
    });
  }

  // ../../node_modules/@popperjs/core/lib/utils/mergeByName.js
  function mergeByName(modifiers) {
    var merged = modifiers.reduce(function(merged2, current) {
      var existing = merged2[current.name];
      merged2[current.name] = existing ? Object.assign({}, existing, current, {
        options: Object.assign({}, existing.options, current.options),
        data: Object.assign({}, existing.data, current.data)
      }) : current;
      return merged2;
    }, {});
    return Object.keys(merged).map(function(key) {
      return merged[key];
    });
  }

  // ../../node_modules/@popperjs/core/lib/createPopper.js
  var INVALID_ELEMENT_ERROR = "Popper: Invalid reference or popper argument provided. They must be either a DOM element or virtual element.";
  var INFINITE_LOOP_ERROR = "Popper: An infinite loop in the modifiers cycle has been detected! The cycle has been interrupted to prevent a browser crash.";
  var DEFAULT_OPTIONS = {
    placement: "bottom",
    modifiers: [],
    strategy: "absolute"
  };
  function areValidElements() {
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    return !args.some(function(element) {
      return !(element && typeof element.getBoundingClientRect === "function");
    });
  }
  function popperGenerator(generatorOptions) {
    if (generatorOptions === void 0) {
      generatorOptions = {};
    }
    var _generatorOptions = generatorOptions, _generatorOptions$def = _generatorOptions.defaultModifiers, defaultModifiers3 = _generatorOptions$def === void 0 ? [] : _generatorOptions$def, _generatorOptions$def2 = _generatorOptions.defaultOptions, defaultOptions2 = _generatorOptions$def2 === void 0 ? DEFAULT_OPTIONS : _generatorOptions$def2;
    return function createPopper4(reference2, popper2, options) {
      if (options === void 0) {
        options = defaultOptions2;
      }
      var state = {
        placement: "bottom",
        orderedModifiers: [],
        options: Object.assign({}, DEFAULT_OPTIONS, defaultOptions2),
        modifiersData: {},
        elements: {
          reference: reference2,
          popper: popper2
        },
        attributes: {},
        styles: {}
      };
      var effectCleanupFns = [];
      var isDestroyed = false;
      var instance = {
        state,
        setOptions: function setOptions(setOptionsAction) {
          var options2 = typeof setOptionsAction === "function" ? setOptionsAction(state.options) : setOptionsAction;
          cleanupModifierEffects();
          state.options = Object.assign({}, defaultOptions2, state.options, options2);
          state.scrollParents = {
            reference: isElement(reference2) ? listScrollParents(reference2) : reference2.contextElement ? listScrollParents(reference2.contextElement) : [],
            popper: listScrollParents(popper2)
          };
          var orderedModifiers = orderModifiers(mergeByName([].concat(defaultModifiers3, state.options.modifiers)));
          state.orderedModifiers = orderedModifiers.filter(function(m2) {
            return m2.enabled;
          });
          if (true) {
            var modifiers = uniqueBy([].concat(orderedModifiers, state.options.modifiers), function(_ref) {
              var name = _ref.name;
              return name;
            });
            validateModifiers(modifiers);
            if (getBasePlacement(state.options.placement) === auto) {
              var flipModifier = state.orderedModifiers.find(function(_ref2) {
                var name = _ref2.name;
                return name === "flip";
              });
              if (!flipModifier) {
                console.error(['Popper: "auto" placements require the "flip" modifier be', "present and enabled to work."].join(" "));
              }
            }
            var _getComputedStyle = getComputedStyle2(popper2), marginTop = _getComputedStyle.marginTop, marginRight = _getComputedStyle.marginRight, marginBottom = _getComputedStyle.marginBottom, marginLeft = _getComputedStyle.marginLeft;
            if ([marginTop, marginRight, marginBottom, marginLeft].some(function(margin) {
              return parseFloat(margin);
            })) {
              console.warn(['Popper: CSS "margin" styles cannot be used to apply padding', "between the popper and its reference element or boundary.", "To replicate margin, use the `offset` modifier, as well as", "the `padding` option in the `preventOverflow` and `flip`", "modifiers."].join(" "));
            }
          }
          runModifierEffects();
          return instance.update();
        },
        forceUpdate: function forceUpdate() {
          if (isDestroyed) {
            return;
          }
          var _state$elements = state.elements, reference3 = _state$elements.reference, popper3 = _state$elements.popper;
          if (!areValidElements(reference3, popper3)) {
            if (true) {
              console.error(INVALID_ELEMENT_ERROR);
            }
            return;
          }
          state.rects = {
            reference: getCompositeRect(reference3, getOffsetParent(popper3), state.options.strategy === "fixed"),
            popper: getLayoutRect(popper3)
          };
          state.reset = false;
          state.placement = state.options.placement;
          state.orderedModifiers.forEach(function(modifier) {
            return state.modifiersData[modifier.name] = Object.assign({}, modifier.data);
          });
          var __debug_loops__ = 0;
          for (var index = 0; index < state.orderedModifiers.length; index++) {
            if (true) {
              __debug_loops__ += 1;
              if (__debug_loops__ > 100) {
                console.error(INFINITE_LOOP_ERROR);
                break;
              }
            }
            if (state.reset === true) {
              state.reset = false;
              index = -1;
              continue;
            }
            var _state$orderedModifie = state.orderedModifiers[index], fn3 = _state$orderedModifie.fn, _state$orderedModifie2 = _state$orderedModifie.options, _options = _state$orderedModifie2 === void 0 ? {} : _state$orderedModifie2, name = _state$orderedModifie.name;
            if (typeof fn3 === "function") {
              state = fn3({
                state,
                options: _options,
                name,
                instance
              }) || state;
            }
          }
        },
        update: debounce2(function() {
          return new Promise(function(resolve2) {
            instance.forceUpdate();
            resolve2(state);
          });
        }),
        destroy: function destroy() {
          cleanupModifierEffects();
          isDestroyed = true;
        }
      };
      if (!areValidElements(reference2, popper2)) {
        if (true) {
          console.error(INVALID_ELEMENT_ERROR);
        }
        return instance;
      }
      instance.setOptions(options).then(function(state2) {
        if (!isDestroyed && options.onFirstUpdate) {
          options.onFirstUpdate(state2);
        }
      });
      function runModifierEffects() {
        state.orderedModifiers.forEach(function(_ref3) {
          var name = _ref3.name, _ref3$options = _ref3.options, options2 = _ref3$options === void 0 ? {} : _ref3$options, effect4 = _ref3.effect;
          if (typeof effect4 === "function") {
            var cleanupFn = effect4({
              state,
              name,
              instance,
              options: options2
            });
            var noopFn = function noopFn2() {
            };
            effectCleanupFns.push(cleanupFn || noopFn);
          }
        });
      }
      function cleanupModifierEffects() {
        effectCleanupFns.forEach(function(fn3) {
          return fn3();
        });
        effectCleanupFns = [];
      }
      return instance;
    };
  }
  var createPopper = /* @__PURE__ */ popperGenerator();

  // ../../node_modules/@popperjs/core/lib/popper-lite.js
  var defaultModifiers = [eventListeners_default, popperOffsets_default, computeStyles_default, applyStyles_default];
  var createPopper2 = /* @__PURE__ */ popperGenerator({
    defaultModifiers
  });

  // ../../node_modules/@popperjs/core/lib/popper.js
  var defaultModifiers2 = [eventListeners_default, popperOffsets_default, computeStyles_default, applyStyles_default, offset_default, flip_default, preventOverflow_default, arrow_default, hide_default];
  var createPopper3 = /* @__PURE__ */ popperGenerator({
    defaultModifiers: defaultModifiers2
  });

  // controllers/endorsements_controller.js
  var endorsements_controller_default = class extends Controller {
    connect() {
      if (document.getElementById("policy_additional_insured_to_endorse").selectedOptions[0].dataset.addedEndorsementsCount > 0) {
        this.setAllEndorsementPricesToZero();
      } else if (document.getElementById("policy_additional_insured_to_endorse").selectedOptions[0].dataset.addedEndorsementsCount == 0) {
        this.setRemainingEndorsementPricesToZero();
      }
      this.hideUnavailableEndorsements();
    }
    insuredSelected(event) {
      this.availableEndorsementTargets.forEach((endorsement) => {
        endorsement.parentElement.classList.remove("d-none");
        endorsement.checked = false;
      });
      if (event.target.selectedOptions[0].dataset.addedEndorsementsCount > 0) {
        this.setRemainingEndorsementPricesToZero();
        this.hideUnavailableEndorsements();
      } else {
        this.resetAvailableEndorsementPrices();
      }
    }
    endorsementSelected() {
      this.toggleAdditionalInsuredFieldRequirement();
      this.setRemainingEndorsementPricesToZero();
      this.resetAvailableEndorsementPrices();
    }
    hideUnavailableEndorsements() {
      if (document.getElementById("policy_additional_insured_to_endorse").selectedOptions[0].dataset.addedEndorsementsCount > 0) {
        document.getElementById("policy_additional_insured_to_endorse").selectedOptions[0].dataset.addedEndorsements.split(",").forEach((endorsement) => {
          endorsement = endorsement.replace(/[\[\]/"]+/g, "");
          document.getElementById(`${endorsement}`).parentElement.classList.add("d-none");
        });
      }
    }
    setAllEndorsementPricesToZero() {
      this.availableEndorsementTargets.forEach((endorsement) => {
        endorsement.dataset.optionValue = 0;
        endorsement.parentElement.querySelector("label").innerText = endorsement.parentElement.querySelector("label").innerText.replace(/\$\d+/, "$0");
      });
    }
    setRemainingEndorsementPricesToZero() {
      this.availableEndorsementTargets.forEach((endorsement) => {
        if (endorsement.checked == false) {
          endorsement.dataset.optionValue = 0;
          endorsement.parentElement.querySelector("label").innerText = endorsement.parentElement.querySelector("label").innerText.replace(/\$\d+/, "$0");
        }
      });
    }
    resetAvailableEndorsementPrices() {
      if (!(document.getElementById("policy_additional_insured_to_endorse").selectedOptions[0].dataset.addedEndorsementsCount > 0)) {
        if (this.availableEndorsementTargets.every((endorsement) => endorsement.checked == false)) {
          this.availableEndorsementTargets.forEach((endorsement) => {
            endorsement.dataset.optionValue = endorsement.dataset.defaultPrice;
            endorsement.parentElement.querySelector("label").innerText = endorsement.parentElement.querySelector("label").innerText.replace(/\$\d+/, `$${endorsement.dataset.optionValue}`);
          });
        }
      }
    }
    toggleAdditionalInsuredFieldRequirement() {
      if (this.availableEndorsementTargets.some((endorsement) => endorsement.checked == true)) {
        document.getElementById("policy_additional_insured_to_endorse").required = true;
      } else {
        document.getElementById("policy_additional_insured_to_endorse").required = false;
      }
    }
  };
  __publicField(endorsements_controller_default, "targets", ["availableEndorsement"]);
  __publicField(endorsements_controller_default, "values", {});

  // controllers/fmodal_controller.js
  var fmodal_controller_exports = {};
  __export(fmodal_controller_exports, {
    default: () => fmodal_controller_default
  });
  var fmodal_controller_default = class extends Controller {
    connect() {
      this.modal = new bootstrap.Modal(this.element);
      this.modal.show();
    }
    disconnect() {
      this.modal.hide();
    }
  };

  // controllers/membership_application_controller.js
  var membership_application_controller_exports = {};
  __export(membership_application_controller_exports, {
    default: () => membership_application_controller_default
  });
  var membership_application_controller_default = class extends Controller {
    connect() {
      let select_menus = document.querySelectorAll("select");
      let radio_buttons = document.querySelectorAll('[type="radio"]');
      let checkboxes = document.querySelectorAll('[type="checkbox"]');
      let additional_insureds = document.querySelectorAll(".additional-insured");
      let additional_employees = document.querySelectorAll(".additional-employee");
      let endorsed_insureds = [];
      this.currentStepTotalTarget.value = Number(0);
      radio_buttons.forEach((e2) => {
        if (e2.checked) {
          this.totalCostTarget.setAttribute(`data-${e2.dataset.applicationDetailType}-${e2.dataset.applicationDetailId}`, e2.dataset.optionValue);
          if (e2.dataset.optionValue) {
            this.currentStepTotalTarget.value = Number(this.currentStepTotalTarget.value) + Number(e2.dataset.optionValue);
          }
        }
      });
      checkboxes.forEach((e2) => {
        if (e2.checked && e2.dataset.applicationDetailType != "additional_insured_endorsements") {
          this.totalCostTarget.setAttribute(`data-${e2.dataset.applicationDetailType}-${e2.dataset.applicationDetailId}`, e2.dataset.optionValue);
          if (e2.dataset.optionValue) {
            this.currentStepTotalTarget.value = Number(this.currentStepTotalTarget.value) + Number(e2.dataset.optionValue);
          }
        }
      });
      select_menus.forEach((e2) => {
        for (const element of e2.selectedOptions) {
          this.totalCostTarget.setAttribute(`data-${element.dataset.applicationDetailType}-${element.dataset.applicationDetailId}`, element.dataset.optionValue);
          if (element.dataset.optionValue) {
            this.currentStepTotalTarget.value = Number(this.currentStepTotalTarget.value) + Number(element.dataset.optionValue);
          }
        }
      });
      additional_employees.forEach((e2, index) => {
        this.currentStepTotalTarget.value = Number(this.currentStepTotalTarget.value) + Number(99);
        this.totalCostTarget.setAttribute(`data-employee-${index + 1}`, 99);
      });
      additional_insureds.forEach((e2, index) => {
        this.currentStepTotalTarget.value = Number(this.currentStepTotalTarget.value) + Number(10);
        this.totalCostTarget.setAttribute(`data-additional-insured-${index + 1}`, 10);
      });
      this.newAdditionalInsuredEndorsementTargets.forEach((el) => {
        if (el.checked == true && el.dataset.optionValue > 0) {
          endorsed_insureds.push(el.dataset.group);
        }
      });
      if (endorsed_insureds.length > 0) {
        let unique_data_groups = [...new Set(endorsed_insureds)];
        this.currentStepTotalTarget.value = Number(this.currentStepTotalTarget.value) + unique_data_groups.length * Number(this.additionalInsuredEndorsementPriceValue);
      }
      if (this.hasOldAdditionalInsuredEndorsementTarget) {
        let addVariablePrice = false;
        this.oldAdditionalInsuredEndorsementTargets.forEach((el) => {
          if (el.checked == true && el.dataset.optionValue > 0) {
            addVariablePrice = true;
          }
        });
        if (addVariablePrice) {
          this.currentStepTotalTarget.value = Number(this.currentStepTotalTarget.value) + this.additionalInsuredEndorsementPriceValue;
        }
      }
      this.toggleMatchedCoverage();
      this.toggleBppCoverage();
      this.initializeServicesLimit();
      this.initializeTotalCost();
    }
    initializeTotalCost() {
      this.totalCostTarget.innerHTML = `$${+this.currentStepTotalTarget.value + +this.totalCostTarget.dataset.completedStepsTotal}`;
    }
    businessTypeTargetConnected() {
      this.toggleBusinessNameField();
    }
    referralSourceTargetConnected() {
      this.toggleReferralSourceDetailField();
    }
    sameAsCheckboxTargetConnected() {
      this.toggleBillingAddress();
    }
    recalculateTotal() {
      let selectionsTotal = 0;
      this.selectionTargets.forEach((el) => {
        if (el.checked == true) {
          selectionsTotal += Number(el.dataset.optionValue);
        }
        if (el.selected == true) {
          selectionsTotal += Number(el.dataset.optionValue);
        }
      });
      let additional_insureds = document.querySelectorAll(".additional-insured");
      let additional_employees = document.querySelectorAll(".additional-employee");
      if (this.hasPrimaryCoverageLevelTarget || this.hasUpgradePrimaryCoverageLevelTarget) {
        let employer_selected;
        let upgradingCoverage = false;
        this.primaryCoverageLevelTargets.forEach((level) => {
          if (level.checked) {
            upgradingCoverage = true;
            employer_selected = level.dataset.canHaveEmployees;
          }
        });
        if (upgradingCoverage == false && this.hasUpgradePrimaryCoverageLevelTarget) {
          employer_selected = this.upgradePrimaryCoverageLevelTarget.dataset.canHaveEmployees;
        }
        if (employer_selected == "true") {
          additional_employees.forEach(() => {
            selectionsTotal += Number(99);
          });
        }
      }
      additional_insureds.forEach(() => {
        selectionsTotal += Number(10);
      });
      if (this.hasOldAdditionalInsuredEndorsementTarget) {
        let addVariablePrice = false;
        this.oldAdditionalInsuredEndorsementTargets.forEach((el) => {
          if (el.checked == true && el.dataset.optionValue > 0) {
            addVariablePrice = true;
          }
        });
        if (addVariablePrice) {
          selectionsTotal += this.additionalInsuredEndorsementPriceValue;
        }
      }
      if (this.hasNewAdditionalInsuredEndorsementTarget) {
        let endorsed_insureds = [];
        this.newAdditionalInsuredEndorsementTargets.forEach((el) => {
          if (el.checked == true && el.dataset.optionValue > 0) {
            endorsed_insureds.push(el.dataset.group);
          }
        });
        if (endorsed_insureds.length > 0) {
          let unique_data_groups = [...new Set(endorsed_insureds)];
          selectionsTotal += unique_data_groups.length * Number(this.additionalInsuredEndorsementPriceValue);
        }
      }
      return selectionsTotal;
    }
    dropdownChanged(e2) {
      if (!e2.srcElement.selectedOptions[0].hasAttribute("data-option-value")) {
        let new_target = document.createElement("div");
        new_target.setAttribute("data-option-value", 0);
        new_target.setAttribute("data-application-detail-type", e2.srcElement.dataset.applicationDetailType);
        new_target.setAttribute("data-application-detail-id", e2.srcElement.dataset.applicationDetailId);
        let blank_object = { target: new_target };
        this.optionSelected(blank_object);
      } else {
        let new_target = { target: e2.srcElement.selectedOptions[0] };
        this.optionSelected(new_target);
      }
    }
    toggleBillingAddress(e2) {
      clearTimeout(this.removeBillingAddressFieldValue);
      if (this.sameAsCheckboxTarget.checked) {
        this.billingAddressContainerTarget.classList.add("d-none");
        this.removeBillingAddressFieldValue = setTimeout(() => {
          this.clearBillingAddressFields();
        }, "3000");
      } else {
        this.billingAddressContainerTarget.classList.remove("d-none");
        this.resetBillingAddressFields();
      }
    }
    clearBillingAddressFields() {
      this.billingAddressFieldsTargets.forEach((field) => {
        field.value = "";
        field.required = false;
      });
    }
    resetBillingAddressFields() {
      this.billingAddressFieldsTargets.forEach((field) => {
        if (!field.name.includes("billing_address_2"))
          field.required = true;
      });
    }
    toggleBusinessNameField(e2) {
      clearTimeout(this.removeFieldValue);
      if (this.businessNameContainerTarget.dataset.splitTestAttribute == "true") {
        if (this.businessTypeTarget.value == 2 || this.businessTypeTarget.value == "") {
          this.businessNameContainerTarget.classList.add("d-none");
          this.businessNameFieldTarget.required = false;
          this.removeFieldValue = setTimeout(() => {
            this.businessNameFieldTarget.value = "";
          }, "3000");
        } else {
          this.businessNameContainerTarget.classList.remove("d-none");
          this.businessNameFieldTarget.required = true;
        }
      } else {
        if (this.businessTypeTarget.value == 2 || this.businessTypeTarget.value == "") {
          this.businessNameFieldTarget.setAttribute("disabled", true);
          this.businessNameFieldTarget.required = false;
          this.businessNameContainerTarget.children[0].children[0].classList.add("d-none");
          this.businessNameFieldTarget.value = "";
        } else {
          this.businessNameFieldTarget.removeAttribute("disabled");
          this.businessNameFieldTarget.required = true;
          this.businessNameContainerTarget.children[0].children[0].classList.remove("d-none");
        }
      }
    }
    toggleReferralSourceDetailField(e2) {
      clearTimeout(this.removeSourceFieldValue);
      const selectedSource = this.referralSourceTarget.options[this.referralSourceTarget.selectedIndex].dataset.detailType;
      if (selectedSource == "no_details" || !selectedSource) {
        this.referralSourceDetailContainerTarget.classList.add("d-none");
        this.referralSourceDetailFieldTarget.required = false;
        this.removeSourceFieldValue = setTimeout(() => {
          this.referralSourceDetailFieldTarget.value = "";
        }, "3000");
      } else {
        this.referralSourceDetailContainerTarget.classList.remove("d-none");
        this.referralSourceDetailFieldTarget.required = true;
      }
    }
    optionSelected(e2) {
      let totalCost = this.recalculateTotal();
      let totalCostTarget = this.totalCostTarget;
      this.currentStepTotalTarget.value = totalCost;
      totalCostTarget.dataset.currentStepTotal = totalCost;
      totalCostTarget.innerHTML = `$${+totalCostTarget.dataset.currentStepTotal + +totalCostTarget.dataset.completedStepsTotal}`;
      if (totalCostTarget.hasAttribute(`data-${e2.target.dataset.applicationDetailType}-${e2.target.dataset.applicationDetailId}`)) {
        if (e2.target.checked == false) {
          totalCostTarget.setAttribute(`data-${e2.target.dataset.applicationDetailType}-${e2.target.dataset.applicationDetailId}`, 0);
        } else {
          totalCostTarget.setAttribute(`data-${e2.target.dataset.applicationDetailType}-${e2.target.dataset.applicationDetailId}`, e2.target.dataset.optionValue);
        }
      }
    }
    toggleAdditionalEmployees(e2) {
      if (this.hasEmployeesAreaTarget == false)
        return;
      if (e2.target.dataset.canHaveEmployees == "true") {
        this.employeesAreaTarget.classList.remove("d-none");
      } else {
        this.employeesAreaTarget.classList.add("d-none");
      }
    }
    initializeServicesLimit() {
      if (this.hasServicesLimitTarget == false)
        return;
      let currentServiceLimit = document.querySelector("#current-service-limit").dataset.currentServiceLimit;
      let upgradeSelected = false;
      if (document.querySelector("#current-service-limit") != null) {
        this.primaryCoverageLevelTargets.forEach((el) => {
          if (el.checked == true) {
            upgradeSelected = true;
            if (el.dataset.servicesLimit == null || el.dataset.servicesLimit == void 0 || el.dataset.servicesLimit > 1) {
              this.servicesLimitTarget.classList.remove("d-none");
              if (this.hasServicesLimitMessageTarget == false)
                return;
              this.servicesLimitMessageTarget.classList.add("d-none");
            } else {
              this.servicesLimitTarget.classList.add("d-none");
              this.removeSecondaryServices();
              if (this.hasServicesLimitMessageTarget == false)
                return;
              this.servicesLimitMessageTarget.classList.remove("d-none");
            }
            return;
          }
        });
        if (upgradeSelected == false) {
          if (currentServiceLimit == null || currentServiceLimit == void 0 || currentServiceLimit > 1 || currentServiceLimit == "") {
            this.servicesLimitTarget.classList.remove("d-none");
            this.servicesLimitMessageTarget.classList.add("d-none");
          } else {
            this.servicesLimitTarget.classList.add("d-none");
            this.servicesLimitMessageTarget.classList.remove("d-none");
            this.removeSecondaryServices();
          }
          return;
        }
      } else {
        this.primaryCoverageLevelTargets.forEach((el) => {
          if (el.checked == true) {
            if (el.dataset.servicesLimit == null || el.dataset.servicesLimit == void 0 || el.dataset.servicesLimit > 1) {
              this.servicesLimitTarget.classList.remove("d-none");
              this.servicesLimitMessageTarget.classList.add("d-none");
            } else {
              this.servicesLimitTarget.classList.add("d-none");
              this.servicesLimitMessageTarget.classList.remove("d-none");
              this.removeSecondaryServices();
            }
          }
        });
      }
    }
    toggleServicesLimit(e2) {
      if (this.hasServicesLimitTarget == false)
        return;
      if (e2.target.dataset.servicesLimit > 0) {
        this.servicesLimitTarget.classList.add("d-none");
        this.servicesLimitMessageTarget.classList.remove("d-none");
        this.removeSecondaryServices();
      } else {
        this.servicesLimitTarget.classList.remove("d-none");
        this.servicesLimitMessageTarget.classList.add("d-none");
      }
    }
    toggleBppCoverage() {
      if (this.hasMatchedCoverageSetTarget == false)
        return;
      let bppCoverageSelected = false;
      this.bppSelectionTargets.forEach((el) => {
        if (el.checked == true) {
          bppCoverageSelected = true;
        }
      });
      if (bppCoverageSelected == true) {
        document.getElementById("bppScreener_Yes").checked = true;
        this.toggleBppOptions({ target: { value: "Yes" } });
      } else {
        document.getElementById("bppScreener_No").checked = true;
      }
    }
    toggleMatchedCoverage() {
      if (this.hasMatchedCoverageSetTarget == false)
        return;
      let showUnmatchedCoverage = false;
      this.selectionTargets.forEach((el) => {
        if (el.selected == true) {
          if (el.dataset.qualifiedService == "true") {
            showUnmatchedCoverage = true;
          }
        }
      });
      if (showUnmatchedCoverage == true) {
        this.unmatchedCoverageSetTarget.classList.remove("d-none");
        this.matchedCoverageSetTarget.classList.add("d-none");
        this.selectionTargets.forEach((el) => {
          if (el.checked == true && el.dataset.matchedCoverage == "true") {
            this.unmatchedCoverageSetTarget.firstElementChild.firstElementChild.checked = true;
            this.unmatchedCoverageSetTarget.firstElementChild.firstElementChild.checked = false;
          }
        });
      } else {
        this.unmatchedCoverageSetTarget.classList.add("d-none");
        this.matchedCoverageSetTarget.classList.remove("d-none");
        this.selectionTargets.forEach((el) => {
          if (el.checked == true && el.dataset.matchedCoverage == "false") {
            this.matchedCoverageSetTarget.firstElementChild.firstElementChild.checked = true;
            this.matchedCoverageSetTarget.firstElementChild.firstElementChild.checked = false;
          }
        });
      }
    }
    toggleBppOptions(e2) {
      if (this.hasBppOptionsTarget == false)
        return;
      if (e2.target.value == "Yes") {
        this.bppOptionsTarget.classList.remove("d-none");
      } else {
        this.bppOptionsTarget.classList.add("d-none");
      }
    }
    toggleBppQuestions(e2) {
      if (this.hasBppQuestionsTarget == false)
        return;
      if (e2.target.dataset.matchedCoverage == "false") {
        this.bppQuestionsTarget.classList.remove("d-none");
      } else {
        this.bppQuestionsTarget.classList.add("d-none");
      }
    }
    clearBppSelection() {
      if (this.hasMatchedCoverageSetTarget == false)
        return;
      this.selectionTargets.forEach((el) => {
        if (el.checked == true && el.dataset.matchedCoverage == "true") {
          this.unmatchedCoverageSetTarget.firstElementChild.firstElementChild.checked = true;
          this.unmatchedCoverageSetTarget.firstElementChild.firstElementChild.checked = false;
        }
        if (el.checked == true && el.dataset.matchedCoverage == "false") {
          this.matchedCoverageSetTarget.firstElementChild.firstElementChild.checked = true;
          this.matchedCoverageSetTarget.firstElementChild.firstElementChild.checked = false;
        }
      });
    }
    addService(e2) {
      let count = e2.target.dataset.servicesCount;
      let dropdowns = document.querySelectorAll("[data-secondary-service-dropdown]");
      let position = dropdowns.length - 1;
      let new_dropdown = dropdowns[position].cloneNode(true);
      let replacement_target = dropdowns[position].selectedOptions[0].dataset.applicationDetailId.match(/-\d$/)[0];
      new_dropdown.id = "service_" + dropdowns.length;
      new_dropdown.name = dropdowns[0].name.replace(/\d]$/g, `${count}]`);
      new_dropdown.value = "";
      new_dropdown.classList.add("mt-2");
      Array.from(new_dropdown.options).forEach((option) => option.dataset.applicationDetailId = option.dataset.applicationDetailId.replace(replacement_target, `-${count}`));
      new_dropdown.options[0].dataset.selected = "selected";
      dropdowns[position].insertAdjacentElement("afterend", new_dropdown);
      e2.target.dataset.servicesCount = +count + 1;
    }
    removeService(e2) {
      this.removeLastService(this.addServiceButtonTarget);
      this.optionSelected(e2);
    }
    removeSecondaryServices() {
      if (this.hasAddServiceButtonTarget == false)
        return;
      let dropdowns = document.querySelectorAll("[data-secondary-service-dropdown]");
      for (let i2 = dropdowns.length; i2 > 0; i2--) {
        this.removeLastService(this.addServiceButtonTarget);
      }
    }
    removeLastService(e2) {
      let count = e2.dataset.servicesCount;
      let dropdowns = document.querySelectorAll("[data-secondary-service-dropdown]");
      let position = dropdowns.length - 1;
      let last_dropdown = dropdowns[position];
      if (dropdowns.length > 1) {
        last_dropdown.remove();
        e2.dataset.servicesCount = +count - 1;
      } else {
        last_dropdown.value = "";
      }
    }
    addSponsorCode(e2) {
      let sponsor_code = this.sponsorCodeTarget.value;
      let policy_id = document.querySelector("[data-payments-policy-id]").value;
      let user_role = this.userRoleValue;
      fetch("/administration/sponsor_codes/verify_code", {
        method: "POST",
        headers: {
          "x-csrf-token": this.getXcsrfToken(),
          "content-type": "application/json"
        },
        body: JSON.stringify({ "code": sponsor_code, "policy": policy_id, "user_role": user_role })
      }).then((data) => data.json()).then((response) => {
        if (response.status) {
          this.sponsorCodeAmountTarget.value = response.sponsor_code_amount;
          this.totalCostTarget.value = "$" + response.new_total;
          this.sponsorCodeSuccessAlertTarget.classList.remove("d-none");
          this.sponsorCodeErrorAlertTarget.classList.add("d-none");
          this.sponsorCodeSuccessAlertTarget.innerText = response.message;
        } else {
          this.sponsorCodeErrorAlertTarget.classList.remove("d-none");
          this.sponsorCodeSuccessAlertTarget.classList.add("d-none");
          this.sponsorCodeErrorAlertTarget.innerText = response.message;
        }
        this.updatePaymentIntent();
      });
    }
    updatePaymentIntent() {
      let policy_id = document.querySelector("#policy_id")?.value;
      fetch(`/policies/update_payment_intent?policy_id=${policy_id}`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: ""
      });
    }
    optionIsWrong(e2) {
      let prompt = document.querySelector(`[data-is-wrong-prompt-${e2.srcElement.dataset.applicationDetailId}]`);
      let button = document.getElementById("proceed-button");
      if (e2.srcElement.dataset.isWrong == "true") {
        prompt.classList.remove("d-none");
        button.setAttribute("disabled", "");
      } else {
        prompt.classList.add("d-none");
        button.removeAttribute("disabled", "");
      }
    }
    toggleModalWindow(e2) {
      let modal_controller = this.setupModalController();
      let modal_content = document.querySelector(`[${e2.target.dataset.membershipApplicationContentAttribute}]`);
      let exit_button = document.createElement("button");
      exit_button.classList.add("btn");
      exit_button.classList.add("btn-primary");
      exit_button.setAttribute("data-action", "click->modal#close");
      exit_button.innerText = "Done";
      modal_controller.contentAreaTarget.innerHTML = modal_content.innerHTML;
      modal_controller.footerAreaTarget.innerHTML = "";
      modal_controller.footerAreaTarget.insertAdjacentElement("afterbegin", exit_button);
      modal_controller.open();
    }
    scrollToPayments() {
      let payments_area = document.querySelector("#payment-element");
      let save_button = document.querySelector("[data-save-policy-changes]");
      if (payments_area != null) {
        payments_area.scrollIntoView({ block: "center", behavior: "smooth", inline: "center" });
        payments_area.focus();
      } else {
        save_button.scrollIntoView({ block: "center", behavior: "smooth", inline: "center" });
      }
    }
    setupModalController() {
      return this.application.getControllerForElementAndIdentifier(document.querySelector("[data-modal-window]"), "modal");
    }
    getXcsrfToken() {
      return document.getElementsByName("csrf-token")[0].content;
    }
  };
  __publicField(membership_application_controller_default, "targets", [
    "addServiceButton",
    "newAdditionalInsuredEndorsement",
    "oldAdditionalInsuredEndorsement",
    "billingAddress",
    "billingAddressContainer",
    "billingAddressFields",
    "bppOptions",
    "bppQuestions",
    "bppSelection",
    "businessName",
    "businessNameContainer",
    "businessNameField",
    "businessType",
    "currentStepTotal",
    "employeesArea",
    "matchedCoverageSet",
    "primaryCoverageLevel",
    "referralSourceDetailContainer",
    "referralSourceDetailField",
    "referralSource",
    "sameAsCheckbox",
    "servicesLimit",
    "servicesLimitMessage",
    "selection",
    "sponsorCode",
    "sponsorCodeAmountLabel",
    "sponsorCodeAmountArea",
    "sponsorCodeAmount",
    "sponsorCodeArea",
    "sponsorCodeMessageArea",
    "sponsorCodeErrorAlert",
    "sponsorCodeSuccessAlert",
    "totalCost",
    "unmatchedCoverageSet",
    "upgradePrimaryCoverageLevel"
  ]);
  __publicField(membership_application_controller_default, "values", {
    userRole: { type: String, default: "subscriber" },
    additionalInsuredEndorsementPrice: { type: Number, default: 99 }
  });

  // controllers/modal_controller.js
  var modal_controller_exports = {};
  __export(modal_controller_exports, {
    default: () => modal_controller_default
  });
  var modal_controller_default = class extends Controller {
    handleAjaxEvent(event) {
      if (event.detail[0].error == null) {
        let targetController = this.application.getControllerForElementAndIdentifier(document.querySelector(`[data-${event.detail[0].stimulusController}-${event.detail[0].tableClass}]`), event.detail[0].stimulusController);
        targetController.handleAjaxResponse(event.detail[0]);
        this.close();
      } else {
        alert(event.detail[0].error);
      }
    }
    open() {
      document.body.classList.add("modal-open");
      this.element.setAttribute("style", "display: block;");
      this.element.classList.add("show");
      document.body.insertAdjacentHTML("beforeend", '<div data-modal-backdrop class="modal-backdrop fade show"></div>');
    }
    close() {
      let modalWindow = document.querySelector("[data-modal-window]");
      document.body.classList.remove("modal-open");
      modalWindow.setAttribute("style", "");
      modalWindow.classList.remove("show");
      document.querySelector("[data-modal-backdrop]").remove();
    }
  };
  __publicField(modal_controller_default, "targets", ["modal", "contentArea", "headerArea", "footerArea"]);

  // controllers/notes_controller.js
  var notes_controller_exports = {};
  __export(notes_controller_exports, {
    default: () => notes_controller_default
  });

  // ../../node_modules/@stimulus/core/dist/event_listener.js
  var EventListener2 = function() {
    function EventListener3(eventTarget, eventName, eventOptions) {
      this.eventTarget = eventTarget;
      this.eventName = eventName;
      this.eventOptions = eventOptions;
      this.unorderedBindings = /* @__PURE__ */ new Set();
    }
    EventListener3.prototype.connect = function() {
      this.eventTarget.addEventListener(this.eventName, this, this.eventOptions);
    };
    EventListener3.prototype.disconnect = function() {
      this.eventTarget.removeEventListener(this.eventName, this, this.eventOptions);
    };
    EventListener3.prototype.bindingConnected = function(binding) {
      this.unorderedBindings.add(binding);
    };
    EventListener3.prototype.bindingDisconnected = function(binding) {
      this.unorderedBindings.delete(binding);
    };
    EventListener3.prototype.handleEvent = function(event) {
      var extendedEvent = extendEvent2(event);
      for (var _i2 = 0, _a = this.bindings; _i2 < _a.length; _i2++) {
        var binding = _a[_i2];
        if (extendedEvent.immediatePropagationStopped) {
          break;
        } else {
          binding.handleEvent(extendedEvent);
        }
      }
    };
    Object.defineProperty(EventListener3.prototype, "bindings", {
      get: function() {
        return Array.from(this.unorderedBindings).sort(function(left2, right2) {
          var leftIndex = left2.index, rightIndex = right2.index;
          return leftIndex < rightIndex ? -1 : leftIndex > rightIndex ? 1 : 0;
        });
      },
      enumerable: false,
      configurable: true
    });
    return EventListener3;
  }();
  function extendEvent2(event) {
    if ("immediatePropagationStopped" in event) {
      return event;
    } else {
      var stopImmediatePropagation_1 = event.stopImmediatePropagation;
      return Object.assign(event, {
        immediatePropagationStopped: false,
        stopImmediatePropagation: function() {
          this.immediatePropagationStopped = true;
          stopImmediatePropagation_1.call(this);
        }
      });
    }
  }

  // ../../node_modules/@stimulus/core/dist/dispatcher.js
  var Dispatcher2 = function() {
    function Dispatcher3(application2) {
      this.application = application2;
      this.eventListenerMaps = /* @__PURE__ */ new Map();
      this.started = false;
    }
    Dispatcher3.prototype.start = function() {
      if (!this.started) {
        this.started = true;
        this.eventListeners.forEach(function(eventListener) {
          return eventListener.connect();
        });
      }
    };
    Dispatcher3.prototype.stop = function() {
      if (this.started) {
        this.started = false;
        this.eventListeners.forEach(function(eventListener) {
          return eventListener.disconnect();
        });
      }
    };
    Object.defineProperty(Dispatcher3.prototype, "eventListeners", {
      get: function() {
        return Array.from(this.eventListenerMaps.values()).reduce(function(listeners, map3) {
          return listeners.concat(Array.from(map3.values()));
        }, []);
      },
      enumerable: false,
      configurable: true
    });
    Dispatcher3.prototype.bindingConnected = function(binding) {
      this.fetchEventListenerForBinding(binding).bindingConnected(binding);
    };
    Dispatcher3.prototype.bindingDisconnected = function(binding) {
      this.fetchEventListenerForBinding(binding).bindingDisconnected(binding);
    };
    Dispatcher3.prototype.handleError = function(error3, message, detail) {
      if (detail === void 0) {
        detail = {};
      }
      this.application.handleError(error3, "Error " + message, detail);
    };
    Dispatcher3.prototype.fetchEventListenerForBinding = function(binding) {
      var eventTarget = binding.eventTarget, eventName = binding.eventName, eventOptions = binding.eventOptions;
      return this.fetchEventListener(eventTarget, eventName, eventOptions);
    };
    Dispatcher3.prototype.fetchEventListener = function(eventTarget, eventName, eventOptions) {
      var eventListenerMap = this.fetchEventListenerMapForEventTarget(eventTarget);
      var cacheKey = this.cacheKey(eventName, eventOptions);
      var eventListener = eventListenerMap.get(cacheKey);
      if (!eventListener) {
        eventListener = this.createEventListener(eventTarget, eventName, eventOptions);
        eventListenerMap.set(cacheKey, eventListener);
      }
      return eventListener;
    };
    Dispatcher3.prototype.createEventListener = function(eventTarget, eventName, eventOptions) {
      var eventListener = new EventListener2(eventTarget, eventName, eventOptions);
      if (this.started) {
        eventListener.connect();
      }
      return eventListener;
    };
    Dispatcher3.prototype.fetchEventListenerMapForEventTarget = function(eventTarget) {
      var eventListenerMap = this.eventListenerMaps.get(eventTarget);
      if (!eventListenerMap) {
        eventListenerMap = /* @__PURE__ */ new Map();
        this.eventListenerMaps.set(eventTarget, eventListenerMap);
      }
      return eventListenerMap;
    };
    Dispatcher3.prototype.cacheKey = function(eventName, eventOptions) {
      var parts = [eventName];
      Object.keys(eventOptions).sort().forEach(function(key) {
        parts.push((eventOptions[key] ? "" : "!") + key);
      });
      return parts.join(":");
    };
    return Dispatcher3;
  }();

  // ../../node_modules/@stimulus/core/dist/action_descriptor.js
  var descriptorPattern2 = /^((.+?)(@(window|document))?->)?(.+?)(#([^:]+?))(:(.+))?$/;
  function parseActionDescriptorString2(descriptorString) {
    var source = descriptorString.trim();
    var matches = source.match(descriptorPattern2) || [];
    return {
      eventTarget: parseEventTarget2(matches[4]),
      eventName: matches[2],
      eventOptions: matches[9] ? parseEventOptions2(matches[9]) : {},
      identifier: matches[5],
      methodName: matches[7]
    };
  }
  function parseEventTarget2(eventTargetName) {
    if (eventTargetName == "window") {
      return window;
    } else if (eventTargetName == "document") {
      return document;
    }
  }
  function parseEventOptions2(eventOptions) {
    return eventOptions.split(":").reduce(function(options, token) {
      var _a;
      return Object.assign(options, (_a = {}, _a[token.replace(/^!/, "")] = !/^!/.test(token), _a));
    }, {});
  }
  function stringifyEventTarget2(eventTarget) {
    if (eventTarget == window) {
      return "window";
    } else if (eventTarget == document) {
      return "document";
    }
  }

  // ../../node_modules/@stimulus/core/dist/action.js
  var Action2 = function() {
    function Action3(element, index, descriptor) {
      this.element = element;
      this.index = index;
      this.eventTarget = descriptor.eventTarget || element;
      this.eventName = descriptor.eventName || getDefaultEventNameForElement2(element) || error2("missing event name");
      this.eventOptions = descriptor.eventOptions || {};
      this.identifier = descriptor.identifier || error2("missing identifier");
      this.methodName = descriptor.methodName || error2("missing method name");
    }
    Action3.forToken = function(token) {
      return new this(token.element, token.index, parseActionDescriptorString2(token.content));
    };
    Action3.prototype.toString = function() {
      var eventNameSuffix = this.eventTargetName ? "@" + this.eventTargetName : "";
      return "" + this.eventName + eventNameSuffix + "->" + this.identifier + "#" + this.methodName;
    };
    Object.defineProperty(Action3.prototype, "eventTargetName", {
      get: function() {
        return stringifyEventTarget2(this.eventTarget);
      },
      enumerable: false,
      configurable: true
    });
    return Action3;
  }();
  var defaultEventNames2 = {
    "a": function(e2) {
      return "click";
    },
    "button": function(e2) {
      return "click";
    },
    "form": function(e2) {
      return "submit";
    },
    "input": function(e2) {
      return e2.getAttribute("type") == "submit" ? "click" : "input";
    },
    "select": function(e2) {
      return "change";
    },
    "textarea": function(e2) {
      return "input";
    }
  };
  function getDefaultEventNameForElement2(element) {
    var tagName = element.tagName.toLowerCase();
    if (tagName in defaultEventNames2) {
      return defaultEventNames2[tagName](element);
    }
  }
  function error2(message) {
    throw new Error(message);
  }

  // ../../node_modules/@stimulus/core/dist/binding.js
  var Binding2 = function() {
    function Binding3(context, action) {
      this.context = context;
      this.action = action;
    }
    Object.defineProperty(Binding3.prototype, "index", {
      get: function() {
        return this.action.index;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Binding3.prototype, "eventTarget", {
      get: function() {
        return this.action.eventTarget;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Binding3.prototype, "eventOptions", {
      get: function() {
        return this.action.eventOptions;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Binding3.prototype, "identifier", {
      get: function() {
        return this.context.identifier;
      },
      enumerable: false,
      configurable: true
    });
    Binding3.prototype.handleEvent = function(event) {
      if (this.willBeInvokedByEvent(event)) {
        this.invokeWithEvent(event);
      }
    };
    Object.defineProperty(Binding3.prototype, "eventName", {
      get: function() {
        return this.action.eventName;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Binding3.prototype, "method", {
      get: function() {
        var method = this.controller[this.methodName];
        if (typeof method == "function") {
          return method;
        }
        throw new Error('Action "' + this.action + '" references undefined method "' + this.methodName + '"');
      },
      enumerable: false,
      configurable: true
    });
    Binding3.prototype.invokeWithEvent = function(event) {
      try {
        this.method.call(this.controller, event);
      } catch (error3) {
        var _a = this, identifier = _a.identifier, controller = _a.controller, element = _a.element, index = _a.index;
        var detail = { identifier, controller, element, index, event };
        this.context.handleError(error3, 'invoking action "' + this.action + '"', detail);
      }
    };
    Binding3.prototype.willBeInvokedByEvent = function(event) {
      var eventTarget = event.target;
      if (this.element === eventTarget) {
        return true;
      } else if (eventTarget instanceof Element && this.element.contains(eventTarget)) {
        return this.scope.containsElement(eventTarget);
      } else {
        return this.scope.containsElement(this.action.element);
      }
    };
    Object.defineProperty(Binding3.prototype, "controller", {
      get: function() {
        return this.context.controller;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Binding3.prototype, "methodName", {
      get: function() {
        return this.action.methodName;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Binding3.prototype, "element", {
      get: function() {
        return this.scope.element;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Binding3.prototype, "scope", {
      get: function() {
        return this.context.scope;
      },
      enumerable: false,
      configurable: true
    });
    return Binding3;
  }();

  // ../../node_modules/@stimulus/mutation-observers/dist/element_observer.js
  var ElementObserver2 = function() {
    function ElementObserver3(element, delegate) {
      var _this = this;
      this.element = element;
      this.started = false;
      this.delegate = delegate;
      this.elements = /* @__PURE__ */ new Set();
      this.mutationObserver = new MutationObserver(function(mutations) {
        return _this.processMutations(mutations);
      });
    }
    ElementObserver3.prototype.start = function() {
      if (!this.started) {
        this.started = true;
        this.mutationObserver.observe(this.element, { attributes: true, childList: true, subtree: true });
        this.refresh();
      }
    };
    ElementObserver3.prototype.stop = function() {
      if (this.started) {
        this.mutationObserver.takeRecords();
        this.mutationObserver.disconnect();
        this.started = false;
      }
    };
    ElementObserver3.prototype.refresh = function() {
      if (this.started) {
        var matches = new Set(this.matchElementsInTree());
        for (var _i2 = 0, _a = Array.from(this.elements); _i2 < _a.length; _i2++) {
          var element = _a[_i2];
          if (!matches.has(element)) {
            this.removeElement(element);
          }
        }
        for (var _b = 0, _c = Array.from(matches); _b < _c.length; _b++) {
          var element = _c[_b];
          this.addElement(element);
        }
      }
    };
    ElementObserver3.prototype.processMutations = function(mutations) {
      if (this.started) {
        for (var _i2 = 0, mutations_1 = mutations; _i2 < mutations_1.length; _i2++) {
          var mutation = mutations_1[_i2];
          this.processMutation(mutation);
        }
      }
    };
    ElementObserver3.prototype.processMutation = function(mutation) {
      if (mutation.type == "attributes") {
        this.processAttributeChange(mutation.target, mutation.attributeName);
      } else if (mutation.type == "childList") {
        this.processRemovedNodes(mutation.removedNodes);
        this.processAddedNodes(mutation.addedNodes);
      }
    };
    ElementObserver3.prototype.processAttributeChange = function(node, attributeName) {
      var element = node;
      if (this.elements.has(element)) {
        if (this.delegate.elementAttributeChanged && this.matchElement(element)) {
          this.delegate.elementAttributeChanged(element, attributeName);
        } else {
          this.removeElement(element);
        }
      } else if (this.matchElement(element)) {
        this.addElement(element);
      }
    };
    ElementObserver3.prototype.processRemovedNodes = function(nodes) {
      for (var _i2 = 0, _a = Array.from(nodes); _i2 < _a.length; _i2++) {
        var node = _a[_i2];
        var element = this.elementFromNode(node);
        if (element) {
          this.processTree(element, this.removeElement);
        }
      }
    };
    ElementObserver3.prototype.processAddedNodes = function(nodes) {
      for (var _i2 = 0, _a = Array.from(nodes); _i2 < _a.length; _i2++) {
        var node = _a[_i2];
        var element = this.elementFromNode(node);
        if (element && this.elementIsActive(element)) {
          this.processTree(element, this.addElement);
        }
      }
    };
    ElementObserver3.prototype.matchElement = function(element) {
      return this.delegate.matchElement(element);
    };
    ElementObserver3.prototype.matchElementsInTree = function(tree) {
      if (tree === void 0) {
        tree = this.element;
      }
      return this.delegate.matchElementsInTree(tree);
    };
    ElementObserver3.prototype.processTree = function(tree, processor) {
      for (var _i2 = 0, _a = this.matchElementsInTree(tree); _i2 < _a.length; _i2++) {
        var element = _a[_i2];
        processor.call(this, element);
      }
    };
    ElementObserver3.prototype.elementFromNode = function(node) {
      if (node.nodeType == Node.ELEMENT_NODE) {
        return node;
      }
    };
    ElementObserver3.prototype.elementIsActive = function(element) {
      if (element.isConnected != this.element.isConnected) {
        return false;
      } else {
        return this.element.contains(element);
      }
    };
    ElementObserver3.prototype.addElement = function(element) {
      if (!this.elements.has(element)) {
        if (this.elementIsActive(element)) {
          this.elements.add(element);
          if (this.delegate.elementMatched) {
            this.delegate.elementMatched(element);
          }
        }
      }
    };
    ElementObserver3.prototype.removeElement = function(element) {
      if (this.elements.has(element)) {
        this.elements.delete(element);
        if (this.delegate.elementUnmatched) {
          this.delegate.elementUnmatched(element);
        }
      }
    };
    return ElementObserver3;
  }();

  // ../../node_modules/@stimulus/mutation-observers/dist/attribute_observer.js
  var AttributeObserver2 = function() {
    function AttributeObserver3(element, attributeName, delegate) {
      this.attributeName = attributeName;
      this.delegate = delegate;
      this.elementObserver = new ElementObserver2(element, this);
    }
    Object.defineProperty(AttributeObserver3.prototype, "element", {
      get: function() {
        return this.elementObserver.element;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(AttributeObserver3.prototype, "selector", {
      get: function() {
        return "[" + this.attributeName + "]";
      },
      enumerable: false,
      configurable: true
    });
    AttributeObserver3.prototype.start = function() {
      this.elementObserver.start();
    };
    AttributeObserver3.prototype.stop = function() {
      this.elementObserver.stop();
    };
    AttributeObserver3.prototype.refresh = function() {
      this.elementObserver.refresh();
    };
    Object.defineProperty(AttributeObserver3.prototype, "started", {
      get: function() {
        return this.elementObserver.started;
      },
      enumerable: false,
      configurable: true
    });
    AttributeObserver3.prototype.matchElement = function(element) {
      return element.hasAttribute(this.attributeName);
    };
    AttributeObserver3.prototype.matchElementsInTree = function(tree) {
      var match2 = this.matchElement(tree) ? [tree] : [];
      var matches = Array.from(tree.querySelectorAll(this.selector));
      return match2.concat(matches);
    };
    AttributeObserver3.prototype.elementMatched = function(element) {
      if (this.delegate.elementMatchedAttribute) {
        this.delegate.elementMatchedAttribute(element, this.attributeName);
      }
    };
    AttributeObserver3.prototype.elementUnmatched = function(element) {
      if (this.delegate.elementUnmatchedAttribute) {
        this.delegate.elementUnmatchedAttribute(element, this.attributeName);
      }
    };
    AttributeObserver3.prototype.elementAttributeChanged = function(element, attributeName) {
      if (this.delegate.elementAttributeValueChanged && this.attributeName == attributeName) {
        this.delegate.elementAttributeValueChanged(element, attributeName);
      }
    };
    return AttributeObserver3;
  }();

  // ../../node_modules/@stimulus/mutation-observers/dist/string_map_observer.js
  var StringMapObserver2 = function() {
    function StringMapObserver3(element, delegate) {
      var _this = this;
      this.element = element;
      this.delegate = delegate;
      this.started = false;
      this.stringMap = /* @__PURE__ */ new Map();
      this.mutationObserver = new MutationObserver(function(mutations) {
        return _this.processMutations(mutations);
      });
    }
    StringMapObserver3.prototype.start = function() {
      if (!this.started) {
        this.started = true;
        this.mutationObserver.observe(this.element, { attributes: true });
        this.refresh();
      }
    };
    StringMapObserver3.prototype.stop = function() {
      if (this.started) {
        this.mutationObserver.takeRecords();
        this.mutationObserver.disconnect();
        this.started = false;
      }
    };
    StringMapObserver3.prototype.refresh = function() {
      if (this.started) {
        for (var _i2 = 0, _a = this.knownAttributeNames; _i2 < _a.length; _i2++) {
          var attributeName = _a[_i2];
          this.refreshAttribute(attributeName);
        }
      }
    };
    StringMapObserver3.prototype.processMutations = function(mutations) {
      if (this.started) {
        for (var _i2 = 0, mutations_1 = mutations; _i2 < mutations_1.length; _i2++) {
          var mutation = mutations_1[_i2];
          this.processMutation(mutation);
        }
      }
    };
    StringMapObserver3.prototype.processMutation = function(mutation) {
      var attributeName = mutation.attributeName;
      if (attributeName) {
        this.refreshAttribute(attributeName);
      }
    };
    StringMapObserver3.prototype.refreshAttribute = function(attributeName) {
      var key = this.delegate.getStringMapKeyForAttribute(attributeName);
      if (key != null) {
        if (!this.stringMap.has(attributeName)) {
          this.stringMapKeyAdded(key, attributeName);
        }
        var value = this.element.getAttribute(attributeName);
        if (this.stringMap.get(attributeName) != value) {
          this.stringMapValueChanged(value, key);
        }
        if (value == null) {
          this.stringMap.delete(attributeName);
          this.stringMapKeyRemoved(key, attributeName);
        } else {
          this.stringMap.set(attributeName, value);
        }
      }
    };
    StringMapObserver3.prototype.stringMapKeyAdded = function(key, attributeName) {
      if (this.delegate.stringMapKeyAdded) {
        this.delegate.stringMapKeyAdded(key, attributeName);
      }
    };
    StringMapObserver3.prototype.stringMapValueChanged = function(value, key) {
      if (this.delegate.stringMapValueChanged) {
        this.delegate.stringMapValueChanged(value, key);
      }
    };
    StringMapObserver3.prototype.stringMapKeyRemoved = function(key, attributeName) {
      if (this.delegate.stringMapKeyRemoved) {
        this.delegate.stringMapKeyRemoved(key, attributeName);
      }
    };
    Object.defineProperty(StringMapObserver3.prototype, "knownAttributeNames", {
      get: function() {
        return Array.from(new Set(this.currentAttributeNames.concat(this.recordedAttributeNames)));
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(StringMapObserver3.prototype, "currentAttributeNames", {
      get: function() {
        return Array.from(this.element.attributes).map(function(attribute) {
          return attribute.name;
        });
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(StringMapObserver3.prototype, "recordedAttributeNames", {
      get: function() {
        return Array.from(this.stringMap.keys());
      },
      enumerable: false,
      configurable: true
    });
    return StringMapObserver3;
  }();

  // ../../node_modules/@stimulus/multimap/dist/set_operations.js
  function add2(map3, key, value) {
    fetch3(map3, key).add(value);
  }
  function del2(map3, key, value) {
    fetch3(map3, key).delete(value);
    prune2(map3, key);
  }
  function fetch3(map3, key) {
    var values = map3.get(key);
    if (!values) {
      values = /* @__PURE__ */ new Set();
      map3.set(key, values);
    }
    return values;
  }
  function prune2(map3, key) {
    var values = map3.get(key);
    if (values != null && values.size == 0) {
      map3.delete(key);
    }
  }

  // ../../node_modules/@stimulus/multimap/dist/multimap.js
  var Multimap2 = function() {
    function Multimap3() {
      this.valuesByKey = /* @__PURE__ */ new Map();
    }
    Object.defineProperty(Multimap3.prototype, "values", {
      get: function() {
        var sets = Array.from(this.valuesByKey.values());
        return sets.reduce(function(values, set2) {
          return values.concat(Array.from(set2));
        }, []);
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Multimap3.prototype, "size", {
      get: function() {
        var sets = Array.from(this.valuesByKey.values());
        return sets.reduce(function(size, set2) {
          return size + set2.size;
        }, 0);
      },
      enumerable: false,
      configurable: true
    });
    Multimap3.prototype.add = function(key, value) {
      add2(this.valuesByKey, key, value);
    };
    Multimap3.prototype.delete = function(key, value) {
      del2(this.valuesByKey, key, value);
    };
    Multimap3.prototype.has = function(key, value) {
      var values = this.valuesByKey.get(key);
      return values != null && values.has(value);
    };
    Multimap3.prototype.hasKey = function(key) {
      return this.valuesByKey.has(key);
    };
    Multimap3.prototype.hasValue = function(value) {
      var sets = Array.from(this.valuesByKey.values());
      return sets.some(function(set2) {
        return set2.has(value);
      });
    };
    Multimap3.prototype.getValuesForKey = function(key) {
      var values = this.valuesByKey.get(key);
      return values ? Array.from(values) : [];
    };
    Multimap3.prototype.getKeysForValue = function(value) {
      return Array.from(this.valuesByKey).filter(function(_a) {
        var key = _a[0], values = _a[1];
        return values.has(value);
      }).map(function(_a) {
        var key = _a[0], values = _a[1];
        return key;
      });
    };
    return Multimap3;
  }();

  // ../../node_modules/@stimulus/multimap/dist/indexed_multimap.js
  var __extends = function() {
    var extendStatics = function(d2, b2) {
      extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d3, b3) {
        d3.__proto__ = b3;
      } || function(d3, b3) {
        for (var p2 in b3)
          if (b3.hasOwnProperty(p2))
            d3[p2] = b3[p2];
      };
      return extendStatics(d2, b2);
    };
    return function(d2, b2) {
      extendStatics(d2, b2);
      function __() {
        this.constructor = d2;
      }
      d2.prototype = b2 === null ? Object.create(b2) : (__.prototype = b2.prototype, new __());
    };
  }();
  var IndexedMultimap = function(_super) {
    __extends(IndexedMultimap2, _super);
    function IndexedMultimap2() {
      var _this = _super.call(this) || this;
      _this.keysByValue = /* @__PURE__ */ new Map();
      return _this;
    }
    Object.defineProperty(IndexedMultimap2.prototype, "values", {
      get: function() {
        return Array.from(this.keysByValue.keys());
      },
      enumerable: false,
      configurable: true
    });
    IndexedMultimap2.prototype.add = function(key, value) {
      _super.prototype.add.call(this, key, value);
      add2(this.keysByValue, value, key);
    };
    IndexedMultimap2.prototype.delete = function(key, value) {
      _super.prototype.delete.call(this, key, value);
      del2(this.keysByValue, value, key);
    };
    IndexedMultimap2.prototype.hasValue = function(value) {
      return this.keysByValue.has(value);
    };
    IndexedMultimap2.prototype.getKeysForValue = function(value) {
      var set2 = this.keysByValue.get(value);
      return set2 ? Array.from(set2) : [];
    };
    return IndexedMultimap2;
  }(Multimap2);

  // ../../node_modules/@stimulus/mutation-observers/dist/token_list_observer.js
  var TokenListObserver2 = function() {
    function TokenListObserver3(element, attributeName, delegate) {
      this.attributeObserver = new AttributeObserver2(element, attributeName, this);
      this.delegate = delegate;
      this.tokensByElement = new Multimap2();
    }
    Object.defineProperty(TokenListObserver3.prototype, "started", {
      get: function() {
        return this.attributeObserver.started;
      },
      enumerable: false,
      configurable: true
    });
    TokenListObserver3.prototype.start = function() {
      this.attributeObserver.start();
    };
    TokenListObserver3.prototype.stop = function() {
      this.attributeObserver.stop();
    };
    TokenListObserver3.prototype.refresh = function() {
      this.attributeObserver.refresh();
    };
    Object.defineProperty(TokenListObserver3.prototype, "element", {
      get: function() {
        return this.attributeObserver.element;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(TokenListObserver3.prototype, "attributeName", {
      get: function() {
        return this.attributeObserver.attributeName;
      },
      enumerable: false,
      configurable: true
    });
    TokenListObserver3.prototype.elementMatchedAttribute = function(element) {
      this.tokensMatched(this.readTokensForElement(element));
    };
    TokenListObserver3.prototype.elementAttributeValueChanged = function(element) {
      var _a = this.refreshTokensForElement(element), unmatchedTokens = _a[0], matchedTokens = _a[1];
      this.tokensUnmatched(unmatchedTokens);
      this.tokensMatched(matchedTokens);
    };
    TokenListObserver3.prototype.elementUnmatchedAttribute = function(element) {
      this.tokensUnmatched(this.tokensByElement.getValuesForKey(element));
    };
    TokenListObserver3.prototype.tokensMatched = function(tokens) {
      var _this = this;
      tokens.forEach(function(token) {
        return _this.tokenMatched(token);
      });
    };
    TokenListObserver3.prototype.tokensUnmatched = function(tokens) {
      var _this = this;
      tokens.forEach(function(token) {
        return _this.tokenUnmatched(token);
      });
    };
    TokenListObserver3.prototype.tokenMatched = function(token) {
      this.delegate.tokenMatched(token);
      this.tokensByElement.add(token.element, token);
    };
    TokenListObserver3.prototype.tokenUnmatched = function(token) {
      this.delegate.tokenUnmatched(token);
      this.tokensByElement.delete(token.element, token);
    };
    TokenListObserver3.prototype.refreshTokensForElement = function(element) {
      var previousTokens = this.tokensByElement.getValuesForKey(element);
      var currentTokens = this.readTokensForElement(element);
      var firstDifferingIndex = zip2(previousTokens, currentTokens).findIndex(function(_a) {
        var previousToken = _a[0], currentToken = _a[1];
        return !tokensAreEqual2(previousToken, currentToken);
      });
      if (firstDifferingIndex == -1) {
        return [[], []];
      } else {
        return [previousTokens.slice(firstDifferingIndex), currentTokens.slice(firstDifferingIndex)];
      }
    };
    TokenListObserver3.prototype.readTokensForElement = function(element) {
      var attributeName = this.attributeName;
      var tokenString = element.getAttribute(attributeName) || "";
      return parseTokenString2(tokenString, element, attributeName);
    };
    return TokenListObserver3;
  }();
  function parseTokenString2(tokenString, element, attributeName) {
    return tokenString.trim().split(/\s+/).filter(function(content) {
      return content.length;
    }).map(function(content, index) {
      return { element, attributeName, content, index };
    });
  }
  function zip2(left2, right2) {
    var length = Math.max(left2.length, right2.length);
    return Array.from({ length }, function(_2, index) {
      return [left2[index], right2[index]];
    });
  }
  function tokensAreEqual2(left2, right2) {
    return left2 && right2 && left2.index == right2.index && left2.content == right2.content;
  }

  // ../../node_modules/@stimulus/mutation-observers/dist/value_list_observer.js
  var ValueListObserver2 = function() {
    function ValueListObserver3(element, attributeName, delegate) {
      this.tokenListObserver = new TokenListObserver2(element, attributeName, this);
      this.delegate = delegate;
      this.parseResultsByToken = /* @__PURE__ */ new WeakMap();
      this.valuesByTokenByElement = /* @__PURE__ */ new WeakMap();
    }
    Object.defineProperty(ValueListObserver3.prototype, "started", {
      get: function() {
        return this.tokenListObserver.started;
      },
      enumerable: false,
      configurable: true
    });
    ValueListObserver3.prototype.start = function() {
      this.tokenListObserver.start();
    };
    ValueListObserver3.prototype.stop = function() {
      this.tokenListObserver.stop();
    };
    ValueListObserver3.prototype.refresh = function() {
      this.tokenListObserver.refresh();
    };
    Object.defineProperty(ValueListObserver3.prototype, "element", {
      get: function() {
        return this.tokenListObserver.element;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(ValueListObserver3.prototype, "attributeName", {
      get: function() {
        return this.tokenListObserver.attributeName;
      },
      enumerable: false,
      configurable: true
    });
    ValueListObserver3.prototype.tokenMatched = function(token) {
      var element = token.element;
      var value = this.fetchParseResultForToken(token).value;
      if (value) {
        this.fetchValuesByTokenForElement(element).set(token, value);
        this.delegate.elementMatchedValue(element, value);
      }
    };
    ValueListObserver3.prototype.tokenUnmatched = function(token) {
      var element = token.element;
      var value = this.fetchParseResultForToken(token).value;
      if (value) {
        this.fetchValuesByTokenForElement(element).delete(token);
        this.delegate.elementUnmatchedValue(element, value);
      }
    };
    ValueListObserver3.prototype.fetchParseResultForToken = function(token) {
      var parseResult = this.parseResultsByToken.get(token);
      if (!parseResult) {
        parseResult = this.parseToken(token);
        this.parseResultsByToken.set(token, parseResult);
      }
      return parseResult;
    };
    ValueListObserver3.prototype.fetchValuesByTokenForElement = function(element) {
      var valuesByToken = this.valuesByTokenByElement.get(element);
      if (!valuesByToken) {
        valuesByToken = /* @__PURE__ */ new Map();
        this.valuesByTokenByElement.set(element, valuesByToken);
      }
      return valuesByToken;
    };
    ValueListObserver3.prototype.parseToken = function(token) {
      try {
        var value = this.delegate.parseValueForToken(token);
        return { value };
      } catch (error3) {
        return { error: error3 };
      }
    };
    return ValueListObserver3;
  }();

  // ../../node_modules/@stimulus/core/dist/binding_observer.js
  var BindingObserver2 = function() {
    function BindingObserver3(context, delegate) {
      this.context = context;
      this.delegate = delegate;
      this.bindingsByAction = /* @__PURE__ */ new Map();
    }
    BindingObserver3.prototype.start = function() {
      if (!this.valueListObserver) {
        this.valueListObserver = new ValueListObserver2(this.element, this.actionAttribute, this);
        this.valueListObserver.start();
      }
    };
    BindingObserver3.prototype.stop = function() {
      if (this.valueListObserver) {
        this.valueListObserver.stop();
        delete this.valueListObserver;
        this.disconnectAllActions();
      }
    };
    Object.defineProperty(BindingObserver3.prototype, "element", {
      get: function() {
        return this.context.element;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(BindingObserver3.prototype, "identifier", {
      get: function() {
        return this.context.identifier;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(BindingObserver3.prototype, "actionAttribute", {
      get: function() {
        return this.schema.actionAttribute;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(BindingObserver3.prototype, "schema", {
      get: function() {
        return this.context.schema;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(BindingObserver3.prototype, "bindings", {
      get: function() {
        return Array.from(this.bindingsByAction.values());
      },
      enumerable: false,
      configurable: true
    });
    BindingObserver3.prototype.connectAction = function(action) {
      var binding = new Binding2(this.context, action);
      this.bindingsByAction.set(action, binding);
      this.delegate.bindingConnected(binding);
    };
    BindingObserver3.prototype.disconnectAction = function(action) {
      var binding = this.bindingsByAction.get(action);
      if (binding) {
        this.bindingsByAction.delete(action);
        this.delegate.bindingDisconnected(binding);
      }
    };
    BindingObserver3.prototype.disconnectAllActions = function() {
      var _this = this;
      this.bindings.forEach(function(binding) {
        return _this.delegate.bindingDisconnected(binding);
      });
      this.bindingsByAction.clear();
    };
    BindingObserver3.prototype.parseValueForToken = function(token) {
      var action = Action2.forToken(token);
      if (action.identifier == this.identifier) {
        return action;
      }
    };
    BindingObserver3.prototype.elementMatchedValue = function(element, action) {
      this.connectAction(action);
    };
    BindingObserver3.prototype.elementUnmatchedValue = function(element, action) {
      this.disconnectAction(action);
    };
    return BindingObserver3;
  }();

  // ../../node_modules/@stimulus/core/dist/value_observer.js
  var ValueObserver2 = function() {
    function ValueObserver3(context, receiver) {
      this.context = context;
      this.receiver = receiver;
      this.stringMapObserver = new StringMapObserver2(this.element, this);
      this.valueDescriptorMap = this.controller.valueDescriptorMap;
      this.invokeChangedCallbacksForDefaultValues();
    }
    ValueObserver3.prototype.start = function() {
      this.stringMapObserver.start();
    };
    ValueObserver3.prototype.stop = function() {
      this.stringMapObserver.stop();
    };
    Object.defineProperty(ValueObserver3.prototype, "element", {
      get: function() {
        return this.context.element;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(ValueObserver3.prototype, "controller", {
      get: function() {
        return this.context.controller;
      },
      enumerable: false,
      configurable: true
    });
    ValueObserver3.prototype.getStringMapKeyForAttribute = function(attributeName) {
      if (attributeName in this.valueDescriptorMap) {
        return this.valueDescriptorMap[attributeName].name;
      }
    };
    ValueObserver3.prototype.stringMapValueChanged = function(attributeValue, name) {
      this.invokeChangedCallbackForValue(name);
    };
    ValueObserver3.prototype.invokeChangedCallbacksForDefaultValues = function() {
      for (var _i2 = 0, _a = this.valueDescriptors; _i2 < _a.length; _i2++) {
        var _b = _a[_i2], key = _b.key, name_1 = _b.name, defaultValue = _b.defaultValue;
        if (defaultValue != void 0 && !this.controller.data.has(key)) {
          this.invokeChangedCallbackForValue(name_1);
        }
      }
    };
    ValueObserver3.prototype.invokeChangedCallbackForValue = function(name) {
      var methodName = name + "Changed";
      var method = this.receiver[methodName];
      if (typeof method == "function") {
        var value = this.receiver[name];
        method.call(this.receiver, value);
      }
    };
    Object.defineProperty(ValueObserver3.prototype, "valueDescriptors", {
      get: function() {
        var valueDescriptorMap = this.valueDescriptorMap;
        return Object.keys(valueDescriptorMap).map(function(key) {
          return valueDescriptorMap[key];
        });
      },
      enumerable: false,
      configurable: true
    });
    return ValueObserver3;
  }();

  // ../../node_modules/@stimulus/core/dist/context.js
  var Context2 = function() {
    function Context3(module, scope) {
      this.module = module;
      this.scope = scope;
      this.controller = new module.controllerConstructor(this);
      this.bindingObserver = new BindingObserver2(this, this.dispatcher);
      this.valueObserver = new ValueObserver2(this, this.controller);
      try {
        this.controller.initialize();
      } catch (error3) {
        this.handleError(error3, "initializing controller");
      }
    }
    Context3.prototype.connect = function() {
      this.bindingObserver.start();
      this.valueObserver.start();
      try {
        this.controller.connect();
      } catch (error3) {
        this.handleError(error3, "connecting controller");
      }
    };
    Context3.prototype.disconnect = function() {
      try {
        this.controller.disconnect();
      } catch (error3) {
        this.handleError(error3, "disconnecting controller");
      }
      this.valueObserver.stop();
      this.bindingObserver.stop();
    };
    Object.defineProperty(Context3.prototype, "application", {
      get: function() {
        return this.module.application;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Context3.prototype, "identifier", {
      get: function() {
        return this.module.identifier;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Context3.prototype, "schema", {
      get: function() {
        return this.application.schema;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Context3.prototype, "dispatcher", {
      get: function() {
        return this.application.dispatcher;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Context3.prototype, "element", {
      get: function() {
        return this.scope.element;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Context3.prototype, "parentElement", {
      get: function() {
        return this.element.parentElement;
      },
      enumerable: false,
      configurable: true
    });
    Context3.prototype.handleError = function(error3, message, detail) {
      if (detail === void 0) {
        detail = {};
      }
      var _a = this, identifier = _a.identifier, controller = _a.controller, element = _a.element;
      detail = Object.assign({ identifier, controller, element }, detail);
      this.application.handleError(error3, "Error " + message, detail);
    };
    return Context3;
  }();

  // ../../node_modules/@stimulus/core/dist/inheritable_statics.js
  function readInheritableStaticArrayValues2(constructor, propertyName) {
    var ancestors = getAncestorsForConstructor2(constructor);
    return Array.from(ancestors.reduce(function(values, constructor2) {
      getOwnStaticArrayValues2(constructor2, propertyName).forEach(function(name) {
        return values.add(name);
      });
      return values;
    }, /* @__PURE__ */ new Set()));
  }
  function readInheritableStaticObjectPairs2(constructor, propertyName) {
    var ancestors = getAncestorsForConstructor2(constructor);
    return ancestors.reduce(function(pairs, constructor2) {
      pairs.push.apply(pairs, getOwnStaticObjectPairs2(constructor2, propertyName));
      return pairs;
    }, []);
  }
  function getAncestorsForConstructor2(constructor) {
    var ancestors = [];
    while (constructor) {
      ancestors.push(constructor);
      constructor = Object.getPrototypeOf(constructor);
    }
    return ancestors.reverse();
  }
  function getOwnStaticArrayValues2(constructor, propertyName) {
    var definition = constructor[propertyName];
    return Array.isArray(definition) ? definition : [];
  }
  function getOwnStaticObjectPairs2(constructor, propertyName) {
    var definition = constructor[propertyName];
    return definition ? Object.keys(definition).map(function(key) {
      return [key, definition[key]];
    }) : [];
  }

  // ../../node_modules/@stimulus/core/dist/blessing.js
  var __extends2 = function() {
    var extendStatics = function(d2, b2) {
      extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d3, b3) {
        d3.__proto__ = b3;
      } || function(d3, b3) {
        for (var p2 in b3)
          if (b3.hasOwnProperty(p2))
            d3[p2] = b3[p2];
      };
      return extendStatics(d2, b2);
    };
    return function(d2, b2) {
      extendStatics(d2, b2);
      function __() {
        this.constructor = d2;
      }
      d2.prototype = b2 === null ? Object.create(b2) : (__.prototype = b2.prototype, new __());
    };
  }();
  var __spreadArrays = function() {
    for (var s2 = 0, i2 = 0, il = arguments.length; i2 < il; i2++)
      s2 += arguments[i2].length;
    for (var r2 = Array(s2), k2 = 0, i2 = 0; i2 < il; i2++)
      for (var a2 = arguments[i2], j2 = 0, jl = a2.length; j2 < jl; j2++, k2++)
        r2[k2] = a2[j2];
    return r2;
  };
  function bless2(constructor) {
    return shadow2(constructor, getBlessedProperties2(constructor));
  }
  function shadow2(constructor, properties) {
    var shadowConstructor = extend3(constructor);
    var shadowProperties = getShadowProperties2(constructor.prototype, properties);
    Object.defineProperties(shadowConstructor.prototype, shadowProperties);
    return shadowConstructor;
  }
  function getBlessedProperties2(constructor) {
    var blessings = readInheritableStaticArrayValues2(constructor, "blessings");
    return blessings.reduce(function(blessedProperties, blessing) {
      var properties = blessing(constructor);
      for (var key in properties) {
        var descriptor = blessedProperties[key] || {};
        blessedProperties[key] = Object.assign(descriptor, properties[key]);
      }
      return blessedProperties;
    }, {});
  }
  function getShadowProperties2(prototype, properties) {
    return getOwnKeys2(properties).reduce(function(shadowProperties, key) {
      var _a;
      var descriptor = getShadowedDescriptor2(prototype, properties, key);
      if (descriptor) {
        Object.assign(shadowProperties, (_a = {}, _a[key] = descriptor, _a));
      }
      return shadowProperties;
    }, {});
  }
  function getShadowedDescriptor2(prototype, properties, key) {
    var shadowingDescriptor = Object.getOwnPropertyDescriptor(prototype, key);
    var shadowedByValue = shadowingDescriptor && "value" in shadowingDescriptor;
    if (!shadowedByValue) {
      var descriptor = Object.getOwnPropertyDescriptor(properties, key).value;
      if (shadowingDescriptor) {
        descriptor.get = shadowingDescriptor.get || descriptor.get;
        descriptor.set = shadowingDescriptor.set || descriptor.set;
      }
      return descriptor;
    }
  }
  var getOwnKeys2 = function() {
    if (typeof Object.getOwnPropertySymbols == "function") {
      return function(object) {
        return __spreadArrays(Object.getOwnPropertyNames(object), Object.getOwnPropertySymbols(object));
      };
    } else {
      return Object.getOwnPropertyNames;
    }
  }();
  var extend3 = function() {
    function extendWithReflect(constructor) {
      function extended() {
        var _newTarget = this && this instanceof extended ? this.constructor : void 0;
        return Reflect.construct(constructor, arguments, _newTarget);
      }
      extended.prototype = Object.create(constructor.prototype, {
        constructor: { value: extended }
      });
      Reflect.setPrototypeOf(extended, constructor);
      return extended;
    }
    function testReflectExtension() {
      var a2 = function() {
        this.a.call(this);
      };
      var b2 = extendWithReflect(a2);
      b2.prototype.a = function() {
      };
      return new b2();
    }
    try {
      testReflectExtension();
      return extendWithReflect;
    } catch (error3) {
      return function(constructor) {
        return function(_super) {
          __extends2(extended, _super);
          function extended() {
            return _super !== null && _super.apply(this, arguments) || this;
          }
          return extended;
        }(constructor);
      };
    }
  }();

  // ../../node_modules/@stimulus/core/dist/definition.js
  function blessDefinition2(definition) {
    return {
      identifier: definition.identifier,
      controllerConstructor: bless2(definition.controllerConstructor)
    };
  }

  // ../../node_modules/@stimulus/core/dist/module.js
  var Module2 = function() {
    function Module3(application2, definition) {
      this.application = application2;
      this.definition = blessDefinition2(definition);
      this.contextsByScope = /* @__PURE__ */ new WeakMap();
      this.connectedContexts = /* @__PURE__ */ new Set();
    }
    Object.defineProperty(Module3.prototype, "identifier", {
      get: function() {
        return this.definition.identifier;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Module3.prototype, "controllerConstructor", {
      get: function() {
        return this.definition.controllerConstructor;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Module3.prototype, "contexts", {
      get: function() {
        return Array.from(this.connectedContexts);
      },
      enumerable: false,
      configurable: true
    });
    Module3.prototype.connectContextForScope = function(scope) {
      var context = this.fetchContextForScope(scope);
      this.connectedContexts.add(context);
      context.connect();
    };
    Module3.prototype.disconnectContextForScope = function(scope) {
      var context = this.contextsByScope.get(scope);
      if (context) {
        this.connectedContexts.delete(context);
        context.disconnect();
      }
    };
    Module3.prototype.fetchContextForScope = function(scope) {
      var context = this.contextsByScope.get(scope);
      if (!context) {
        context = new Context2(this, scope);
        this.contextsByScope.set(scope, context);
      }
      return context;
    };
    return Module3;
  }();

  // ../../node_modules/@stimulus/core/dist/class_map.js
  var ClassMap2 = function() {
    function ClassMap3(scope) {
      this.scope = scope;
    }
    ClassMap3.prototype.has = function(name) {
      return this.data.has(this.getDataKey(name));
    };
    ClassMap3.prototype.get = function(name) {
      return this.data.get(this.getDataKey(name));
    };
    ClassMap3.prototype.getAttributeName = function(name) {
      return this.data.getAttributeNameForKey(this.getDataKey(name));
    };
    ClassMap3.prototype.getDataKey = function(name) {
      return name + "-class";
    };
    Object.defineProperty(ClassMap3.prototype, "data", {
      get: function() {
        return this.scope.data;
      },
      enumerable: false,
      configurable: true
    });
    return ClassMap3;
  }();

  // ../../node_modules/@stimulus/core/dist/string_helpers.js
  function camelize2(value) {
    return value.replace(/(?:[_-])([a-z0-9])/g, function(_2, char) {
      return char.toUpperCase();
    });
  }
  function capitalize2(value) {
    return value.charAt(0).toUpperCase() + value.slice(1);
  }
  function dasherize2(value) {
    return value.replace(/([A-Z])/g, function(_2, char) {
      return "-" + char.toLowerCase();
    });
  }

  // ../../node_modules/@stimulus/core/dist/data_map.js
  var DataMap2 = function() {
    function DataMap3(scope) {
      this.scope = scope;
    }
    Object.defineProperty(DataMap3.prototype, "element", {
      get: function() {
        return this.scope.element;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(DataMap3.prototype, "identifier", {
      get: function() {
        return this.scope.identifier;
      },
      enumerable: false,
      configurable: true
    });
    DataMap3.prototype.get = function(key) {
      var name = this.getAttributeNameForKey(key);
      return this.element.getAttribute(name);
    };
    DataMap3.prototype.set = function(key, value) {
      var name = this.getAttributeNameForKey(key);
      this.element.setAttribute(name, value);
      return this.get(key);
    };
    DataMap3.prototype.has = function(key) {
      var name = this.getAttributeNameForKey(key);
      return this.element.hasAttribute(name);
    };
    DataMap3.prototype.delete = function(key) {
      if (this.has(key)) {
        var name_1 = this.getAttributeNameForKey(key);
        this.element.removeAttribute(name_1);
        return true;
      } else {
        return false;
      }
    };
    DataMap3.prototype.getAttributeNameForKey = function(key) {
      return "data-" + this.identifier + "-" + dasherize2(key);
    };
    return DataMap3;
  }();

  // ../../node_modules/@stimulus/core/dist/guide.js
  var Guide2 = function() {
    function Guide3(logger) {
      this.warnedKeysByObject = /* @__PURE__ */ new WeakMap();
      this.logger = logger;
    }
    Guide3.prototype.warn = function(object, key, message) {
      var warnedKeys = this.warnedKeysByObject.get(object);
      if (!warnedKeys) {
        warnedKeys = /* @__PURE__ */ new Set();
        this.warnedKeysByObject.set(object, warnedKeys);
      }
      if (!warnedKeys.has(key)) {
        warnedKeys.add(key);
        this.logger.warn(message, object);
      }
    };
    return Guide3;
  }();

  // ../../node_modules/@stimulus/core/dist/selectors.js
  function attributeValueContainsToken2(attributeName, token) {
    return "[" + attributeName + '~="' + token + '"]';
  }

  // ../../node_modules/@stimulus/core/dist/target_set.js
  var __spreadArrays2 = function() {
    for (var s2 = 0, i2 = 0, il = arguments.length; i2 < il; i2++)
      s2 += arguments[i2].length;
    for (var r2 = Array(s2), k2 = 0, i2 = 0; i2 < il; i2++)
      for (var a2 = arguments[i2], j2 = 0, jl = a2.length; j2 < jl; j2++, k2++)
        r2[k2] = a2[j2];
    return r2;
  };
  var TargetSet2 = function() {
    function TargetSet3(scope) {
      this.scope = scope;
    }
    Object.defineProperty(TargetSet3.prototype, "element", {
      get: function() {
        return this.scope.element;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(TargetSet3.prototype, "identifier", {
      get: function() {
        return this.scope.identifier;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(TargetSet3.prototype, "schema", {
      get: function() {
        return this.scope.schema;
      },
      enumerable: false,
      configurable: true
    });
    TargetSet3.prototype.has = function(targetName) {
      return this.find(targetName) != null;
    };
    TargetSet3.prototype.find = function() {
      var _this = this;
      var targetNames = [];
      for (var _i2 = 0; _i2 < arguments.length; _i2++) {
        targetNames[_i2] = arguments[_i2];
      }
      return targetNames.reduce(function(target, targetName) {
        return target || _this.findTarget(targetName) || _this.findLegacyTarget(targetName);
      }, void 0);
    };
    TargetSet3.prototype.findAll = function() {
      var _this = this;
      var targetNames = [];
      for (var _i2 = 0; _i2 < arguments.length; _i2++) {
        targetNames[_i2] = arguments[_i2];
      }
      return targetNames.reduce(function(targets, targetName) {
        return __spreadArrays2(targets, _this.findAllTargets(targetName), _this.findAllLegacyTargets(targetName));
      }, []);
    };
    TargetSet3.prototype.findTarget = function(targetName) {
      var selector = this.getSelectorForTargetName(targetName);
      return this.scope.findElement(selector);
    };
    TargetSet3.prototype.findAllTargets = function(targetName) {
      var selector = this.getSelectorForTargetName(targetName);
      return this.scope.findAllElements(selector);
    };
    TargetSet3.prototype.getSelectorForTargetName = function(targetName) {
      var attributeName = "data-" + this.identifier + "-target";
      return attributeValueContainsToken2(attributeName, targetName);
    };
    TargetSet3.prototype.findLegacyTarget = function(targetName) {
      var selector = this.getLegacySelectorForTargetName(targetName);
      return this.deprecate(this.scope.findElement(selector), targetName);
    };
    TargetSet3.prototype.findAllLegacyTargets = function(targetName) {
      var _this = this;
      var selector = this.getLegacySelectorForTargetName(targetName);
      return this.scope.findAllElements(selector).map(function(element) {
        return _this.deprecate(element, targetName);
      });
    };
    TargetSet3.prototype.getLegacySelectorForTargetName = function(targetName) {
      var targetDescriptor = this.identifier + "." + targetName;
      return attributeValueContainsToken2(this.schema.targetAttribute, targetDescriptor);
    };
    TargetSet3.prototype.deprecate = function(element, targetName) {
      if (element) {
        var identifier = this.identifier;
        var attributeName = this.schema.targetAttribute;
        this.guide.warn(element, "target:" + targetName, "Please replace " + attributeName + '="' + identifier + "." + targetName + '" with data-' + identifier + '-target="' + targetName + '". ' + ("The " + attributeName + " attribute is deprecated and will be removed in a future version of Stimulus."));
      }
      return element;
    };
    Object.defineProperty(TargetSet3.prototype, "guide", {
      get: function() {
        return this.scope.guide;
      },
      enumerable: false,
      configurable: true
    });
    return TargetSet3;
  }();

  // ../../node_modules/@stimulus/core/dist/scope.js
  var __spreadArrays3 = function() {
    for (var s2 = 0, i2 = 0, il = arguments.length; i2 < il; i2++)
      s2 += arguments[i2].length;
    for (var r2 = Array(s2), k2 = 0, i2 = 0; i2 < il; i2++)
      for (var a2 = arguments[i2], j2 = 0, jl = a2.length; j2 < jl; j2++, k2++)
        r2[k2] = a2[j2];
    return r2;
  };
  var Scope2 = function() {
    function Scope3(schema, element, identifier, logger) {
      var _this = this;
      this.targets = new TargetSet2(this);
      this.classes = new ClassMap2(this);
      this.data = new DataMap2(this);
      this.containsElement = function(element2) {
        return element2.closest(_this.controllerSelector) === _this.element;
      };
      this.schema = schema;
      this.element = element;
      this.identifier = identifier;
      this.guide = new Guide2(logger);
    }
    Scope3.prototype.findElement = function(selector) {
      return this.element.matches(selector) ? this.element : this.queryElements(selector).find(this.containsElement);
    };
    Scope3.prototype.findAllElements = function(selector) {
      return __spreadArrays3(this.element.matches(selector) ? [this.element] : [], this.queryElements(selector).filter(this.containsElement));
    };
    Scope3.prototype.queryElements = function(selector) {
      return Array.from(this.element.querySelectorAll(selector));
    };
    Object.defineProperty(Scope3.prototype, "controllerSelector", {
      get: function() {
        return attributeValueContainsToken2(this.schema.controllerAttribute, this.identifier);
      },
      enumerable: false,
      configurable: true
    });
    return Scope3;
  }();

  // ../../node_modules/@stimulus/core/dist/scope_observer.js
  var ScopeObserver2 = function() {
    function ScopeObserver3(element, schema, delegate) {
      this.element = element;
      this.schema = schema;
      this.delegate = delegate;
      this.valueListObserver = new ValueListObserver2(this.element, this.controllerAttribute, this);
      this.scopesByIdentifierByElement = /* @__PURE__ */ new WeakMap();
      this.scopeReferenceCounts = /* @__PURE__ */ new WeakMap();
    }
    ScopeObserver3.prototype.start = function() {
      this.valueListObserver.start();
    };
    ScopeObserver3.prototype.stop = function() {
      this.valueListObserver.stop();
    };
    Object.defineProperty(ScopeObserver3.prototype, "controllerAttribute", {
      get: function() {
        return this.schema.controllerAttribute;
      },
      enumerable: false,
      configurable: true
    });
    ScopeObserver3.prototype.parseValueForToken = function(token) {
      var element = token.element, identifier = token.content;
      var scopesByIdentifier = this.fetchScopesByIdentifierForElement(element);
      var scope = scopesByIdentifier.get(identifier);
      if (!scope) {
        scope = this.delegate.createScopeForElementAndIdentifier(element, identifier);
        scopesByIdentifier.set(identifier, scope);
      }
      return scope;
    };
    ScopeObserver3.prototype.elementMatchedValue = function(element, value) {
      var referenceCount = (this.scopeReferenceCounts.get(value) || 0) + 1;
      this.scopeReferenceCounts.set(value, referenceCount);
      if (referenceCount == 1) {
        this.delegate.scopeConnected(value);
      }
    };
    ScopeObserver3.prototype.elementUnmatchedValue = function(element, value) {
      var referenceCount = this.scopeReferenceCounts.get(value);
      if (referenceCount) {
        this.scopeReferenceCounts.set(value, referenceCount - 1);
        if (referenceCount == 1) {
          this.delegate.scopeDisconnected(value);
        }
      }
    };
    ScopeObserver3.prototype.fetchScopesByIdentifierForElement = function(element) {
      var scopesByIdentifier = this.scopesByIdentifierByElement.get(element);
      if (!scopesByIdentifier) {
        scopesByIdentifier = /* @__PURE__ */ new Map();
        this.scopesByIdentifierByElement.set(element, scopesByIdentifier);
      }
      return scopesByIdentifier;
    };
    return ScopeObserver3;
  }();

  // ../../node_modules/@stimulus/core/dist/router.js
  var Router2 = function() {
    function Router3(application2) {
      this.application = application2;
      this.scopeObserver = new ScopeObserver2(this.element, this.schema, this);
      this.scopesByIdentifier = new Multimap2();
      this.modulesByIdentifier = /* @__PURE__ */ new Map();
    }
    Object.defineProperty(Router3.prototype, "element", {
      get: function() {
        return this.application.element;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Router3.prototype, "schema", {
      get: function() {
        return this.application.schema;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Router3.prototype, "logger", {
      get: function() {
        return this.application.logger;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Router3.prototype, "controllerAttribute", {
      get: function() {
        return this.schema.controllerAttribute;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Router3.prototype, "modules", {
      get: function() {
        return Array.from(this.modulesByIdentifier.values());
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Router3.prototype, "contexts", {
      get: function() {
        return this.modules.reduce(function(contexts, module) {
          return contexts.concat(module.contexts);
        }, []);
      },
      enumerable: false,
      configurable: true
    });
    Router3.prototype.start = function() {
      this.scopeObserver.start();
    };
    Router3.prototype.stop = function() {
      this.scopeObserver.stop();
    };
    Router3.prototype.loadDefinition = function(definition) {
      this.unloadIdentifier(definition.identifier);
      var module = new Module2(this.application, definition);
      this.connectModule(module);
    };
    Router3.prototype.unloadIdentifier = function(identifier) {
      var module = this.modulesByIdentifier.get(identifier);
      if (module) {
        this.disconnectModule(module);
      }
    };
    Router3.prototype.getContextForElementAndIdentifier = function(element, identifier) {
      var module = this.modulesByIdentifier.get(identifier);
      if (module) {
        return module.contexts.find(function(context) {
          return context.element == element;
        });
      }
    };
    Router3.prototype.handleError = function(error3, message, detail) {
      this.application.handleError(error3, message, detail);
    };
    Router3.prototype.createScopeForElementAndIdentifier = function(element, identifier) {
      return new Scope2(this.schema, element, identifier, this.logger);
    };
    Router3.prototype.scopeConnected = function(scope) {
      this.scopesByIdentifier.add(scope.identifier, scope);
      var module = this.modulesByIdentifier.get(scope.identifier);
      if (module) {
        module.connectContextForScope(scope);
      }
    };
    Router3.prototype.scopeDisconnected = function(scope) {
      this.scopesByIdentifier.delete(scope.identifier, scope);
      var module = this.modulesByIdentifier.get(scope.identifier);
      if (module) {
        module.disconnectContextForScope(scope);
      }
    };
    Router3.prototype.connectModule = function(module) {
      this.modulesByIdentifier.set(module.identifier, module);
      var scopes = this.scopesByIdentifier.getValuesForKey(module.identifier);
      scopes.forEach(function(scope) {
        return module.connectContextForScope(scope);
      });
    };
    Router3.prototype.disconnectModule = function(module) {
      this.modulesByIdentifier.delete(module.identifier);
      var scopes = this.scopesByIdentifier.getValuesForKey(module.identifier);
      scopes.forEach(function(scope) {
        return module.disconnectContextForScope(scope);
      });
    };
    return Router3;
  }();

  // ../../node_modules/@stimulus/core/dist/schema.js
  var defaultSchema2 = {
    controllerAttribute: "data-controller",
    actionAttribute: "data-action",
    targetAttribute: "data-target"
  };

  // ../../node_modules/@stimulus/core/dist/application.js
  var __awaiter = function(thisArg, _arguments, P2, generator) {
    function adopt(value) {
      return value instanceof P2 ? value : new P2(function(resolve2) {
        resolve2(value);
      });
    }
    return new (P2 || (P2 = Promise))(function(resolve2, reject) {
      function fulfilled(value) {
        try {
          step(generator.next(value));
        } catch (e2) {
          reject(e2);
        }
      }
      function rejected(value) {
        try {
          step(generator["throw"](value));
        } catch (e2) {
          reject(e2);
        }
      }
      function step(result) {
        result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
      }
      step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
  };
  var __generator = function(thisArg, body) {
    var _2 = { label: 0, sent: function() {
      if (t2[0] & 1)
        throw t2[1];
      return t2[1];
    }, trys: [], ops: [] }, f2, y2, t2, g2;
    return g2 = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g2[Symbol.iterator] = function() {
      return this;
    }), g2;
    function verb(n2) {
      return function(v2) {
        return step([n2, v2]);
      };
    }
    function step(op) {
      if (f2)
        throw new TypeError("Generator is already executing.");
      while (_2)
        try {
          if (f2 = 1, y2 && (t2 = op[0] & 2 ? y2["return"] : op[0] ? y2["throw"] || ((t2 = y2["return"]) && t2.call(y2), 0) : y2.next) && !(t2 = t2.call(y2, op[1])).done)
            return t2;
          if (y2 = 0, t2)
            op = [op[0] & 2, t2.value];
          switch (op[0]) {
            case 0:
            case 1:
              t2 = op;
              break;
            case 4:
              _2.label++;
              return { value: op[1], done: false };
            case 5:
              _2.label++;
              y2 = op[1];
              op = [0];
              continue;
            case 7:
              op = _2.ops.pop();
              _2.trys.pop();
              continue;
            default:
              if (!(t2 = _2.trys, t2 = t2.length > 0 && t2[t2.length - 1]) && (op[0] === 6 || op[0] === 2)) {
                _2 = 0;
                continue;
              }
              if (op[0] === 3 && (!t2 || op[1] > t2[0] && op[1] < t2[3])) {
                _2.label = op[1];
                break;
              }
              if (op[0] === 6 && _2.label < t2[1]) {
                _2.label = t2[1];
                t2 = op;
                break;
              }
              if (t2 && _2.label < t2[2]) {
                _2.label = t2[2];
                _2.ops.push(op);
                break;
              }
              if (t2[2])
                _2.ops.pop();
              _2.trys.pop();
              continue;
          }
          op = body.call(thisArg, _2);
        } catch (e2) {
          op = [6, e2];
          y2 = 0;
        } finally {
          f2 = t2 = 0;
        }
      if (op[0] & 5)
        throw op[1];
      return { value: op[0] ? op[1] : void 0, done: true };
    }
  };
  var __spreadArrays4 = function() {
    for (var s2 = 0, i2 = 0, il = arguments.length; i2 < il; i2++)
      s2 += arguments[i2].length;
    for (var r2 = Array(s2), k2 = 0, i2 = 0; i2 < il; i2++)
      for (var a2 = arguments[i2], j2 = 0, jl = a2.length; j2 < jl; j2++, k2++)
        r2[k2] = a2[j2];
    return r2;
  };
  var Application2 = function() {
    function Application3(element, schema) {
      if (element === void 0) {
        element = document.documentElement;
      }
      if (schema === void 0) {
        schema = defaultSchema2;
      }
      this.logger = console;
      this.element = element;
      this.schema = schema;
      this.dispatcher = new Dispatcher2(this);
      this.router = new Router2(this);
    }
    Application3.start = function(element, schema) {
      var application2 = new Application3(element, schema);
      application2.start();
      return application2;
    };
    Application3.prototype.start = function() {
      return __awaiter(this, void 0, void 0, function() {
        return __generator(this, function(_a) {
          switch (_a.label) {
            case 0:
              return [4, domReady2()];
            case 1:
              _a.sent();
              this.dispatcher.start();
              this.router.start();
              return [2];
          }
        });
      });
    };
    Application3.prototype.stop = function() {
      this.dispatcher.stop();
      this.router.stop();
    };
    Application3.prototype.register = function(identifier, controllerConstructor) {
      this.load({ identifier, controllerConstructor });
    };
    Application3.prototype.load = function(head) {
      var _this = this;
      var rest = [];
      for (var _i2 = 1; _i2 < arguments.length; _i2++) {
        rest[_i2 - 1] = arguments[_i2];
      }
      var definitions = Array.isArray(head) ? head : __spreadArrays4([head], rest);
      definitions.forEach(function(definition) {
        return _this.router.loadDefinition(definition);
      });
    };
    Application3.prototype.unload = function(head) {
      var _this = this;
      var rest = [];
      for (var _i2 = 1; _i2 < arguments.length; _i2++) {
        rest[_i2 - 1] = arguments[_i2];
      }
      var identifiers = Array.isArray(head) ? head : __spreadArrays4([head], rest);
      identifiers.forEach(function(identifier) {
        return _this.router.unloadIdentifier(identifier);
      });
    };
    Object.defineProperty(Application3.prototype, "controllers", {
      get: function() {
        return this.router.contexts.map(function(context) {
          return context.controller;
        });
      },
      enumerable: false,
      configurable: true
    });
    Application3.prototype.getControllerForElementAndIdentifier = function(element, identifier) {
      var context = this.router.getContextForElementAndIdentifier(element, identifier);
      return context ? context.controller : null;
    };
    Application3.prototype.handleError = function(error3, message, detail) {
      this.logger.error("%s\n\n%o\n\n%o", message, error3, detail);
    };
    return Application3;
  }();
  function domReady2() {
    return new Promise(function(resolve2) {
      if (document.readyState == "loading") {
        document.addEventListener("DOMContentLoaded", resolve2);
      } else {
        resolve2();
      }
    });
  }

  // ../../node_modules/@stimulus/core/dist/class_properties.js
  function ClassPropertiesBlessing2(constructor) {
    var classes = readInheritableStaticArrayValues2(constructor, "classes");
    return classes.reduce(function(properties, classDefinition) {
      return Object.assign(properties, propertiesForClassDefinition2(classDefinition));
    }, {});
  }
  function propertiesForClassDefinition2(key) {
    var _a;
    var name = key + "Class";
    return _a = {}, _a[name] = {
      get: function() {
        var classes = this.classes;
        if (classes.has(key)) {
          return classes.get(key);
        } else {
          var attribute = classes.getAttributeName(key);
          throw new Error('Missing attribute "' + attribute + '"');
        }
      }
    }, _a["has" + capitalize2(name)] = {
      get: function() {
        return this.classes.has(key);
      }
    }, _a;
  }

  // ../../node_modules/@stimulus/core/dist/target_properties.js
  function TargetPropertiesBlessing2(constructor) {
    var targets = readInheritableStaticArrayValues2(constructor, "targets");
    return targets.reduce(function(properties, targetDefinition) {
      return Object.assign(properties, propertiesForTargetDefinition2(targetDefinition));
    }, {});
  }
  function propertiesForTargetDefinition2(name) {
    var _a;
    return _a = {}, _a[name + "Target"] = {
      get: function() {
        var target = this.targets.find(name);
        if (target) {
          return target;
        } else {
          throw new Error('Missing target element "' + this.identifier + "." + name + '"');
        }
      }
    }, _a[name + "Targets"] = {
      get: function() {
        return this.targets.findAll(name);
      }
    }, _a["has" + capitalize2(name) + "Target"] = {
      get: function() {
        return this.targets.has(name);
      }
    }, _a;
  }

  // ../../node_modules/@stimulus/core/dist/value_properties.js
  function ValuePropertiesBlessing2(constructor) {
    var valueDefinitionPairs = readInheritableStaticObjectPairs2(constructor, "values");
    var propertyDescriptorMap = {
      valueDescriptorMap: {
        get: function() {
          var _this = this;
          return valueDefinitionPairs.reduce(function(result, valueDefinitionPair) {
            var _a;
            var valueDescriptor = parseValueDefinitionPair2(valueDefinitionPair);
            var attributeName = _this.data.getAttributeNameForKey(valueDescriptor.key);
            return Object.assign(result, (_a = {}, _a[attributeName] = valueDescriptor, _a));
          }, {});
        }
      }
    };
    return valueDefinitionPairs.reduce(function(properties, valueDefinitionPair) {
      return Object.assign(properties, propertiesForValueDefinitionPair2(valueDefinitionPair));
    }, propertyDescriptorMap);
  }
  function propertiesForValueDefinitionPair2(valueDefinitionPair) {
    var _a;
    var definition = parseValueDefinitionPair2(valueDefinitionPair);
    var type = definition.type, key = definition.key, name = definition.name;
    var read2 = readers2[type], write2 = writers2[type] || writers2.default;
    return _a = {}, _a[name] = {
      get: function() {
        var value = this.data.get(key);
        if (value !== null) {
          return read2(value);
        } else {
          return definition.defaultValue;
        }
      },
      set: function(value) {
        if (value === void 0) {
          this.data.delete(key);
        } else {
          this.data.set(key, write2(value));
        }
      }
    }, _a["has" + capitalize2(name)] = {
      get: function() {
        return this.data.has(key);
      }
    }, _a;
  }
  function parseValueDefinitionPair2(_a) {
    var token = _a[0], typeConstant = _a[1];
    var type = parseValueTypeConstant2(typeConstant);
    return valueDescriptorForTokenAndType(token, type);
  }
  function parseValueTypeConstant2(typeConstant) {
    switch (typeConstant) {
      case Array:
        return "array";
      case Boolean:
        return "boolean";
      case Number:
        return "number";
      case Object:
        return "object";
      case String:
        return "string";
    }
    throw new Error('Unknown value type constant "' + typeConstant + '"');
  }
  function valueDescriptorForTokenAndType(token, type) {
    var key = dasherize2(token) + "-value";
    return {
      type,
      key,
      name: camelize2(key),
      get defaultValue() {
        return defaultValuesByType2[type];
      }
    };
  }
  var defaultValuesByType2 = {
    get array() {
      return [];
    },
    boolean: false,
    number: 0,
    get object() {
      return {};
    },
    string: ""
  };
  var readers2 = {
    array: function(value) {
      var array = JSON.parse(value);
      if (!Array.isArray(array)) {
        throw new TypeError("Expected array");
      }
      return array;
    },
    boolean: function(value) {
      return !(value == "0" || value == "false");
    },
    number: function(value) {
      return parseFloat(value);
    },
    object: function(value) {
      var object = JSON.parse(value);
      if (object === null || typeof object != "object" || Array.isArray(object)) {
        throw new TypeError("Expected object");
      }
      return object;
    },
    string: function(value) {
      return value;
    }
  };
  var writers2 = {
    default: writeString2,
    array: writeJSON2,
    object: writeJSON2
  };
  function writeJSON2(value) {
    return JSON.stringify(value);
  }
  function writeString2(value) {
    return "" + value;
  }

  // ../../node_modules/@stimulus/core/dist/controller.js
  var Controller2 = function() {
    function Controller3(context) {
      this.context = context;
    }
    Object.defineProperty(Controller3.prototype, "application", {
      get: function() {
        return this.context.application;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Controller3.prototype, "scope", {
      get: function() {
        return this.context.scope;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Controller3.prototype, "element", {
      get: function() {
        return this.scope.element;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Controller3.prototype, "identifier", {
      get: function() {
        return this.scope.identifier;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Controller3.prototype, "targets", {
      get: function() {
        return this.scope.targets;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Controller3.prototype, "classes", {
      get: function() {
        return this.scope.classes;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Controller3.prototype, "data", {
      get: function() {
        return this.scope.data;
      },
      enumerable: false,
      configurable: true
    });
    Controller3.prototype.initialize = function() {
    };
    Controller3.prototype.connect = function() {
    };
    Controller3.prototype.disconnect = function() {
    };
    Controller3.blessings = [ClassPropertiesBlessing2, TargetPropertiesBlessing2, ValuePropertiesBlessing2];
    Controller3.targets = [];
    Controller3.values = {};
    return Controller3;
  }();

  // controllers/notes_controller.js
  var notes_controller_default = class extends Controller2 {
    message(event) {
      let notice_area = document.querySelector("#note-alert");
      notice_area.innerHTML = event.detail[0].message;
    }
  };
  __publicField(notes_controller_default, "targets", []);

  // controllers/password_controller.js
  var password_controller_exports = {};
  __export(password_controller_exports, {
    default: () => password_controller_default
  });
  var password_controller_default = class extends Controller {
    verifyPassword() {
      let matching = this.checkIfPasswordsMatch();
      let length = this.checkPasswordLength();
      if (matching && length) {
        this.submitButtonTarget.removeAttribute("disabled");
      } else {
        this.submitButtonTarget.setAttribute("disabled", true);
      }
    }
    checkIfPasswordsMatch() {
      if (this.passwordTarget.value == this.passwordConfirmationTarget.value) {
        if (document.querySelector("#mismatch-passwords") != null)
          document.querySelector("#mismatch-passwords").remove();
        return true;
      } else {
        if (document.querySelector("#mismatch-passwords") == null)
          this.messageBoxTarget.innerHTML += '<div id="mismatch-passwords">Sorry, your passwords do not match. Please try again.</div>';
        return false;
      }
    }
    checkPasswordLength() {
      if (this.passwordTarget.value.length >= 6) {
        if (document.querySelector("#invalid-length") != null)
          document.querySelector("#invalid-length").remove();
        return true;
      } else {
        if (document.querySelector("#invalid-length") == null)
          this.messageBoxTarget.innerHTML += '<div id="invalid-length">Please make your password longer. There must be 6 or more characters, numbers or symbols.</div>';
        return false;
      }
    }
  };
  __publicField(password_controller_default, "targets", ["password", "passwordConfirmation", "messageBox", "submitButton"]);

  // controllers/policy_controller.js
  var policy_controller_exports = {};
  __export(policy_controller_exports, {
    default: () => policy_controller_default
  });
  var policy_controller_default = class extends Controller {
    payForChanges(e2) {
    }
    upgradePrimaryCoverageLevel(e2) {
    }
    downgradePrimaryCoverageLevel(e2) {
    }
    addAdditionalEmployee(e2) {
    }
    addAdditionalInsured(e2) {
    }
    addEndorsement(e2) {
    }
    setupModalController() {
      return this.application.getControllerForElementAndIdentifier(document.querySelector("[data-modal-window]"), "modal");
    }
    getXcsrfToken() {
      return document.getElementsByName("csrf-token")[0].content;
    }
  };
  __publicField(policy_controller_default, "targets", ["additionalEmployeesArea", "additionalInsuredsArea", "purchaseBtn"]);

  // controllers/refresh_controller.js
  var refresh_controller_exports = {};
  __export(refresh_controller_exports, {
    default: () => refresh_controller_default
  });
  var refresh_controller_default = class extends Controller {
    intervalRefreshTargetConnected() {
      this.refresher = setTimeout(() => {
        location.reload();
      }, this.intervalValue);
    }
    intervalRefreshTargetDisconnected() {
      clearTimeout(this.refresher);
    }
  };
  __publicField(refresh_controller_default, "values", { interval: { type: Number, default: 5e3 } });
  __publicField(refresh_controller_default, "targets", ["intervalRefresh"]);

  // controllers/tables_controller.js
  var tables_controller_exports = {};
  __export(tables_controller_exports, {
    default: () => tables_controller_default
  });
  var tables_controller_default = class extends Controller {
    addRow(event) {
      let modalController = this.modalController();
      fetch(`/administration/${this.data.get("pluralClass")}/new`).then((response) => response.json()).then((data) => {
        modalController.contentAreaTarget.innerHTML = data.form;
        if (this.data.get("alternativeClassName") == null) {
          modalController.contentAreaTarget.querySelector(`input[name="${this.data.get("singularClass")}[${this.data.get("updateAttributeName")}]"]`).setAttribute("value", this.data.get("updateAttributeValue"));
        } else {
          modalController.contentAreaTarget.querySelector(`input[name="${this.data.get("alternativeClassName")}[${this.data.get("updateAttributeName")}]"]`).setAttribute("value", this.data.get("updateAttributeValue"));
        }
        modalController.open();
      });
    }
    editRow(event) {
      let modalController = this.modalController();
      fetch(`/administration/${this.data.get("pluralClass")}/${event.target.dataset.tablesObjectId}/edit`).then((response) => response.json()).then((data) => {
        modalController.contentAreaTarget.innerHTML = data.form;
        modalController.open();
      });
    }
    destroyRow(event) {
      let answer = confirm(`Are you sure you want to destroy this ${this.data.get("singularClass")}?`);
      if (answer) {
        let metaTag = document.getElementsByName("csrf-token")[0].content;
        fetch(`/administration/${this.data.get("pluralClass")}/${event.target.dataset.tablesObjectId}`, { headers: { "X-CSRF-Token": metaTag }, method: "DELETE" }).then((response) => response.json()).then((data) => this.tableAreaTarget.querySelector(`[data-tables-row-id="${data.rowId}"]`).remove());
      }
    }
    handleAjaxResponse(data) {
      if (data.rowId == null) {
        this.tableAreaTarget.insertAdjacentHTML("beforeEnd", data.tableSection);
      } else {
        let existing_row = this.tableAreaTarget.querySelector(`[data-tables-row-id="${data.rowId}"]`);
        existing_row.insertAdjacentHTML("afterEnd", data.tableSection);
        existing_row.remove();
      }
    }
    modalController() {
      return this.application.getControllerForElementAndIdentifier(document.querySelector("[data-modal-window]"), "modal");
    }
  };
  __publicField(tables_controller_default, "targets", ["tableArea"]);

  // controllers/tinymce_controller.js
  var tinymce_controller_exports = {};
  __export(tinymce_controller_exports, {
    default: () => tinymce_controller_default
  });
  var import_tinymce = __toESM(require_tinymce());

  // ../../node_modules/tinymce/icons/default/icons.js
  tinymce.IconManager.add("default", {
    icons: {
      "accessibility-check": '<svg width="24" height="24"><path d="M12 2a2 2 0 012 2 2 2 0 01-2 2 2 2 0 01-2-2c0-1.1.9-2 2-2zm8 7h-5v12c0 .6-.4 1-1 1a1 1 0 01-1-1v-5c0-.6-.4-1-1-1a1 1 0 00-1 1v5c0 .6-.4 1-1 1a1 1 0 01-1-1V9H4a1 1 0 110-2h16c.6 0 1 .4 1 1s-.4 1-1 1z" fill-rule="nonzero"/></svg>',
      "action-next": '<svg width="24" height="24"><path fill-rule="nonzero" d="M5.7 7.3a1 1 0 00-1.4 1.4l7.7 7.7 7.7-7.7a1 1 0 10-1.4-1.4L12 13.6 5.7 7.3z"/></svg>',
      "action-prev": '<svg width="24" height="24"><path fill-rule="nonzero" d="M18.3 15.7a1 1 0 001.4-1.4L12 6.6l-7.7 7.7a1 1 0 001.4 1.4L12 9.4l6.3 6.3z"/></svg>',
      "align-center": '<svg width="24" height="24"><path d="M5 5h14c.6 0 1 .4 1 1s-.4 1-1 1H5a1 1 0 110-2zm3 4h8c.6 0 1 .4 1 1s-.4 1-1 1H8a1 1 0 110-2zm0 8h8c.6 0 1 .4 1 1s-.4 1-1 1H8a1 1 0 010-2zm-3-4h14c.6 0 1 .4 1 1s-.4 1-1 1H5a1 1 0 010-2z" fill-rule="evenodd"/></svg>',
      "align-justify": '<svg width="24" height="24"><path d="M5 5h14c.6 0 1 .4 1 1s-.4 1-1 1H5a1 1 0 110-2zm0 4h14c.6 0 1 .4 1 1s-.4 1-1 1H5a1 1 0 110-2zm0 4h14c.6 0 1 .4 1 1s-.4 1-1 1H5a1 1 0 010-2zm0 4h14c.6 0 1 .4 1 1s-.4 1-1 1H5a1 1 0 010-2z" fill-rule="evenodd"/></svg>',
      "align-left": '<svg width="24" height="24"><path d="M5 5h14c.6 0 1 .4 1 1s-.4 1-1 1H5a1 1 0 110-2zm0 4h8c.6 0 1 .4 1 1s-.4 1-1 1H5a1 1 0 110-2zm0 8h8c.6 0 1 .4 1 1s-.4 1-1 1H5a1 1 0 010-2zm0-4h14c.6 0 1 .4 1 1s-.4 1-1 1H5a1 1 0 010-2z" fill-rule="evenodd"/></svg>',
      "align-none": '<svg width="24" height="24"><path d="M14.2 5L13 7H5a1 1 0 110-2h9.2zm4 0h.8a1 1 0 010 2h-2l1.2-2zm-6.4 4l-1.2 2H5a1 1 0 010-2h6.8zm4 0H19a1 1 0 010 2h-4.4l1.2-2zm-6.4 4l-1.2 2H5a1 1 0 010-2h4.4zm4 0H19a1 1 0 010 2h-6.8l1.2-2zM7 17l-1.2 2H5a1 1 0 010-2h2zm4 0h8a1 1 0 010 2H9.8l1.2-2zm5.2-13.5l1.3.7-9.7 16.3-1.3-.7 9.7-16.3z" fill-rule="evenodd"/></svg>',
      "align-right": '<svg width="24" height="24"><path d="M5 5h14c.6 0 1 .4 1 1s-.4 1-1 1H5a1 1 0 110-2zm6 4h8c.6 0 1 .4 1 1s-.4 1-1 1h-8a1 1 0 010-2zm0 8h8c.6 0 1 .4 1 1s-.4 1-1 1h-8a1 1 0 010-2zm-6-4h14c.6 0 1 .4 1 1s-.4 1-1 1H5a1 1 0 010-2z" fill-rule="evenodd"/></svg>',
      "arrow-left": '<svg width="24" height="24"><path d="M5.6 13l12 6a1 1 0 001.4-1V6a1 1 0 00-1.4-.9l-12 6a1 1 0 000 1.8z" fill-rule="evenodd"/></svg>',
      "arrow-right": '<svg width="24" height="24"><path d="M18.5 13l-12 6A1 1 0 015 18V6a1 1 0 011.4-.9l12 6a1 1 0 010 1.8z" fill-rule="evenodd"/></svg>',
      "bold": '<svg width="24" height="24"><path d="M7.8 19c-.3 0-.5 0-.6-.2l-.2-.5V5.7c0-.2 0-.4.2-.5l.6-.2h5c1.5 0 2.7.3 3.5 1 .7.6 1.1 1.4 1.1 2.5a3 3 0 01-.6 1.9c-.4.6-1 1-1.6 1.2.4.1.9.3 1.3.6s.8.7 1 1.2c.4.4.5 1 .5 1.6 0 1.3-.4 2.3-1.3 3-.8.7-2.1 1-3.8 1H7.8zm5-8.3c.6 0 1.2-.1 1.6-.5.4-.3.6-.7.6-1.3 0-1.1-.8-1.7-2.3-1.7H9.3v3.5h3.4zm.5 6c.7 0 1.3-.1 1.7-.4.4-.4.6-.9.6-1.5s-.2-1-.7-1.4c-.4-.3-1-.4-2-.4H9.4v3.8h4z" fill-rule="evenodd"/></svg>',
      "bookmark": '<svg width="24" height="24"><path d="M6 4v17l6-4 6 4V4c0-.6-.4-1-1-1H7a1 1 0 00-1 1z" fill-rule="nonzero"/></svg>',
      "border-style": '<svg width="24" height="24"><g fill-rule="evenodd"><rect width="18" height="2" x="3" y="6" rx="1"/><rect width="2.8" height="2" x="3" y="16" rx="1"/><rect width="2.8" height="2" x="6.8" y="16" rx="1"/><rect width="2.8" height="2" x="10.6" y="16" rx="1"/><rect width="2.8" height="2" x="14.4" y="16" rx="1"/><rect width="2.8" height="2" x="18.2" y="16" rx="1"/><rect width="8" height="2" x="3" y="11" rx="1"/><rect width="8" height="2" x="13" y="11" rx="1"/></g></svg>',
      "border-width": '<svg width="24" height="24"><g fill-rule="evenodd"><rect width="18" height="5" x="3" y="5" rx="1"/><rect width="18" height="3.5" x="3" y="11.5" rx="1"/><rect width="18" height="2" x="3" y="17" rx="1"/></g></svg>',
      "brightness": '<svg width="24" height="24"><path d="M12 17c.3 0 .5.1.7.3.2.2.3.4.3.7v1c0 .3-.1.5-.3.7a1 1 0 01-.7.3 1 1 0 01-.7-.3 1 1 0 01-.3-.7v-1c0-.3.1-.5.3-.7.2-.2.4-.3.7-.3zm0-10a1 1 0 01-.7-.3A1 1 0 0111 6V5c0-.3.1-.5.3-.7.2-.2.4-.3.7-.3.3 0 .5.1.7.3.2.2.3.4.3.7v1c0 .3-.1.5-.3.7a1 1 0 01-.7.3zm7 4c.3 0 .5.1.7.3.2.2.3.4.3.7 0 .3-.1.5-.3.7a1 1 0 01-.7.3h-1a1 1 0 01-.7-.3 1 1 0 01-.3-.7c0-.3.1-.5.3-.7.2-.2.4-.3.7-.3h1zM7 12c0 .3-.1.5-.3.7a1 1 0 01-.7.3H5a1 1 0 01-.7-.3A1 1 0 014 12c0-.3.1-.5.3-.7.2-.2.4-.3.7-.3h1c.3 0 .5.1.7.3.2.2.3.4.3.7zm10 3.5l.7.8c.2.1.3.4.3.6 0 .3-.1.6-.3.8a1 1 0 01-.8.3 1 1 0 01-.6-.3l-.8-.7a1 1 0 01-.3-.8c0-.2.1-.5.3-.7a1 1 0 011.4 0zm-10-7l-.7-.8a1 1 0 01-.3-.6c0-.3.1-.6.3-.8.2-.2.5-.3.8-.3.2 0 .5.1.7.3l.7.7c.2.2.3.5.3.8 0 .2-.1.5-.3.7a1 1 0 01-.7.3 1 1 0 01-.8-.3zm10 0a1 1 0 01-.8.3 1 1 0 01-.7-.3 1 1 0 01-.3-.7c0-.3.1-.6.3-.8l.8-.7c.1-.2.4-.3.6-.3.3 0 .6.1.8.3.2.2.3.5.3.8 0 .2-.1.5-.3.7l-.7.7zm-10 7c.2-.2.5-.3.8-.3.2 0 .5.1.7.3a1 1 0 010 1.4l-.8.8a1 1 0 01-.6.3 1 1 0 01-.8-.3 1 1 0 01-.3-.8c0-.2.1-.5.3-.6l.7-.8zM12 8a4 4 0 013.7 2.4 4 4 0 010 3.2A4 4 0 0112 16a4 4 0 01-3.7-2.4 4 4 0 010-3.2A4 4 0 0112 8zm0 6.5c.7 0 1.3-.2 1.8-.7.5-.5.7-1.1.7-1.8s-.2-1.3-.7-1.8c-.5-.5-1.1-.7-1.8-.7s-1.3.2-1.8.7c-.5.5-.7 1.1-.7 1.8s.2 1.3.7 1.8c.5.5 1.1.7 1.8.7z" fill-rule="evenodd"/></svg>',
      "browse": '<svg width="24" height="24"><path d="M19 4a2 2 0 012 2v12a2 2 0 01-2 2h-4v-2h4V8H5v10h4v2H5a2 2 0 01-2-2V6c0-1.1.9-2 2-2h14zm-8 9.4l-2.3 2.3a1 1 0 11-1.4-1.4l4-4a1 1 0 011.4 0l4 4a1 1 0 01-1.4 1.4L13 13.4V20a1 1 0 01-2 0v-6.6z" fill-rule="nonzero"/></svg>',
      "cancel": '<svg width="24" height="24"><path d="M12 4.6a7.4 7.4 0 110 14.8 7.4 7.4 0 010-14.8zM12 3a9 9 0 100 18 9 9 0 000-18zm0 8L14.8 8l1 1.1-2.7 2.8 2.7 2.7-1.1 1.1-2.7-2.7-2.7 2.7-1-1.1 2.6-2.7-2.7-2.7 1-1.1 2.8 2.7z" fill-rule="nonzero"/></svg>',
      "cell-background-color": '<svg width="24" height="24"><path d="M15.7 2l1.6 1.6-2.7 2.6 5.9 5.8c.7.7.7 1.7 0 2.4l-6.3 6.1a1.7 1.7 0 01-2.4 0l-6.3-6.1c-.7-.7-.7-1.7 0-2.4L15.7 2zM18 12l-4.5-4L9 12h9zM4 16s2 2.4 2 3.8C6 21 5.1 22 4 22s-2-1-2-2.2C2 18.4 4 16 4 16z"/></svg>',
      "cell-border-color": '<svg width="24" height="24"><g fill-rule="evenodd"><path fill-rule="nonzero" d="M5 13v5h2v2H5a2 2 0 01-2-2v-5h2zm8-7V4h6a2 2 0 012 2h-8z" opacity=".2"/><path fill-rule="nonzero" d="M13 4v2H5v7H3V6c0-1.1.9-2 2-2h8zm-2.6 14.1l.1-.1.1.1.2.3.2.2.2.2c.4.6.8 1.2.8 1.7 0 .8-.7 1.5-1.5 1.5S9 21.3 9 20.5c0-.5.4-1.1.8-1.7l.2-.2.2-.2.2-.3z"/><path d="M13 11l-2 2H5v-2h6V6h2z"/><path fill-rule="nonzero" d="M18.4 8l1 1-1.8 1.9 4 4c.5.4.5 1.1 0 1.6l-4.3 4.2a1.2 1.2 0 01-1.6 0l-4.4-4.2c-.4-.5-.4-1.2 0-1.7l7-6.8zm1.6 7l-3-3-3 3h6z"/></g></svg>',
      "change-case": '<svg width="24" height="24"><path d="M18.4 18.2v-.6c-.5.8-1.3 1.2-2.4 1.2-2.2 0-3.3-1.6-3.3-4.8 0-3.1 1-4.7 3.3-4.7 1.1 0 1.8.3 2.4 1.1v-.6c0-.5.4-.8.8-.8s.8.3.8.8v8.4c0 .5-.4.8-.8.8a.8.8 0 01-.8-.8zm-2-7.4c-1.3 0-1.8.9-1.8 3.2 0 2.4.5 3.3 1.7 3.3 1.3 0 1.8-.9 1.8-3.2 0-2.4-.5-3.3-1.7-3.3zM10 15.7H5.5l-.8 2.6a1 1 0 01-1 .7h-.2a.7.7 0 01-.7-1l4-12a1 1 0 012 0l4 12a.7.7 0 01-.8 1h-.2a1 1 0 01-1-.7l-.8-2.6zm-.3-1.5l-2-6.5-1.9 6.5h3.9z" fill-rule="evenodd"/></svg>',
      "character-count": '<svg width="24" height="24"><path d="M4 11.5h16v1H4v-1zm4.8-6.8V10H7.7V5.8h-1v-1h2zM11 8.3V9h2v1h-3V7.7l2-1v-.9h-2v-1h3v2.4l-2 1zm6.3-3.4V10h-3.1V9h2.1V8h-2.1V6.8h2.1v-1h-2.1v-1h3.1zM5.8 16.4c0-.5.2-.8.5-1 .2-.2.6-.3 1.2-.3l.8.1c.2 0 .4.2.5.3l.4.4v2.8l.2.3H8.2v-.1-.2l-.6.3H7c-.4 0-.7 0-1-.2a1 1 0 01-.3-.9c0-.3 0-.6.3-.8.3-.2.7-.4 1.2-.4l.6-.2h.3v-.2l-.1-.2a.8.8 0 00-.5-.1 1 1 0 00-.4 0l-.3.4h-1zm2.3.8h-.2l-.2.1-.4.1a1 1 0 00-.4.2l-.2.2.1.3.5.1h.4l.4-.4v-.6zm2-3.4h1.2v1.7l.5-.3h.5c.5 0 .9.1 1.2.5.3.4.5.8.5 1.4 0 .6-.2 1.1-.5 1.5-.3.4-.7.6-1.3.6l-.6-.1-.4-.4v.4h-1.1v-5.4zm1.1 3.3c0 .3 0 .6.2.8a.7.7 0 001.2 0l.2-.8c0-.4 0-.6-.2-.8a.7.7 0 00-.6-.3l-.6.3-.2.8zm6.1-.5c0-.2 0-.3-.2-.4a.8.8 0 00-.5-.2c-.3 0-.5.1-.6.3l-.2.9c0 .3 0 .6.2.8.1.2.3.3.6.3.2 0 .4 0 .5-.2l.2-.4h1.1c0 .5-.3.8-.6 1.1a2 2 0 01-1.3.4c-.5 0-1-.2-1.3-.6a2 2 0 01-.5-1.4c0-.6.1-1.1.5-1.5.3-.4.8-.5 1.4-.5.5 0 1 0 1.2.3.4.3.5.7.5 1.2h-1v-.1z" fill-rule="evenodd"/></svg>',
      "checklist-rtl": '<svg width="24" height="24"><path d="M5 17h8c.6 0 1 .4 1 1s-.4 1-1 1H5a1 1 0 010-2zm0-6h8c.6 0 1 .4 1 1s-.4 1-1 1H5a1 1 0 010-2zm0-6h8c.6 0 1 .4 1 1s-.4 1-1 1H5a1 1 0 110-2zm14.2 11c.2-.4.6-.5.9-.3.3.2.4.6.2 1L18 20c-.2.3-.7.4-1 0l-1.3-1.3a.7.7 0 010-1c.3-.2.7-.2 1 0l.7.9 1.7-2.8zm0-6c.2-.4.6-.5.9-.3.3.2.4.6.2 1L18 14c-.2.3-.7.4-1 0l-1.3-1.3a.7.7 0 010-1c.3-.2.7-.2 1 0l.7.9 1.7-2.8zm0-6c.2-.4.6-.5.9-.3.3.2.4.6.2 1L18 8c-.2.3-.7.4-1 0l-1.3-1.3a.7.7 0 010-1c.3-.2.7-.2 1 0l.7.9 1.7-2.8z" fill-rule="evenodd"/></svg>',
      "checklist": '<svg width="24" height="24"><path d="M11 17h8c.6 0 1 .4 1 1s-.4 1-1 1h-8a1 1 0 010-2zm0-6h8c.6 0 1 .4 1 1s-.4 1-1 1h-8a1 1 0 010-2zm0-6h8a1 1 0 010 2h-8a1 1 0 010-2zM7.2 16c.2-.4.6-.5.9-.3.3.2.4.6.2 1L6 20c-.2.3-.7.4-1 0l-1.3-1.3a.7.7 0 010-1c.3-.2.7-.2 1 0l.7.9 1.7-2.8zm0-6c.2-.4.6-.5.9-.3.3.2.4.6.2 1L6 14c-.2.3-.7.4-1 0l-1.3-1.3a.7.7 0 010-1c.3-.2.7-.2 1 0l.7.9 1.7-2.8zm0-6c.2-.4.6-.5.9-.3.3.2.4.6.2 1L6 8c-.2.3-.7.4-1 0L3.8 6.9a.7.7 0 010-1c.3-.2.7-.2 1 0l.7.9 1.7-2.8z" fill-rule="evenodd"/></svg>',
      "checkmark": '<svg width="24" height="24"><path d="M18.2 5.4a1 1 0 011.6 1.2l-8 12a1 1 0 01-1.5.1l-5-5a1 1 0 111.4-1.4l4.1 4.1 7.4-11z" fill-rule="nonzero"/></svg>',
      "chevron-down": '<svg width="10" height="10"><path d="M8.7 2.2c.3-.3.8-.3 1 0 .4.4.4.9 0 1.2L5.7 7.8c-.3.3-.9.3-1.2 0L.2 3.4a.8.8 0 010-1.2c.3-.3.8-.3 1.1 0L5 6l3.7-3.8z" fill-rule="nonzero"/></svg>',
      "chevron-left": '<svg width="10" height="10"><path d="M7.8 1.3L4 5l3.8 3.7c.3.3.3.8 0 1-.4.4-.9.4-1.2 0L2.2 5.7a.8.8 0 010-1.2L6.6.2C7 0 7.4 0 7.8.2c.3.3.3.8 0 1.1z" fill-rule="nonzero"/></svg>',
      "chevron-right": '<svg width="10" height="10"><path d="M2.2 1.3a.8.8 0 010-1c.4-.4.9-.4 1.2 0l4.4 4.1c.3.4.3.9 0 1.2L3.4 9.8c-.3.3-.8.3-1.2 0a.8.8 0 010-1.1L6 5 2.2 1.3z" fill-rule="nonzero"/></svg>',
      "chevron-up": '<svg width="10" height="10"><path d="M8.7 7.8L5 4 1.3 7.8c-.3.3-.8.3-1 0a.8.8 0 010-1.2l4.1-4.4c.3-.3.9-.3 1.2 0l4.2 4.4c.3.3.3.9 0 1.2-.3.3-.8.3-1.1 0z" fill-rule="nonzero"/></svg>',
      "close": '<svg width="24" height="24"><path d="M17.3 8.2L13.4 12l3.9 3.8a1 1 0 01-1.5 1.5L12 13.4l-3.8 3.9a1 1 0 01-1.5-1.5l3.9-3.8-3.9-3.8a1 1 0 011.5-1.5l3.8 3.9 3.8-3.9a1 1 0 011.5 1.5z" fill-rule="evenodd"/></svg>',
      "code-sample": '<svg width="24" height="26"><path d="M7.1 11a2.8 2.8 0 01-.8 2 2.8 2.8 0 01.8 2v1.7c0 .3.1.6.4.8.2.3.5.4.8.4.3 0 .4.2.4.4v.8c0 .2-.1.4-.4.4-.7 0-1.4-.3-2-.8-.5-.6-.8-1.3-.8-2V15c0-.3-.1-.6-.4-.8-.2-.3-.5-.4-.8-.4a.4.4 0 01-.4-.4v-.8c0-.2.2-.4.4-.4.3 0 .6-.1.8-.4.3-.2.4-.5.4-.8V9.3c0-.7.3-1.4.8-2 .6-.5 1.3-.8 2-.8.3 0 .4.2.4.4v.8c0 .2-.1.4-.4.4-.3 0-.6.1-.8.4-.3.2-.4.5-.4.8V11zm9.8 0V9.3c0-.3-.1-.6-.4-.8-.2-.3-.5-.4-.8-.4a.4.4 0 01-.4-.4V7c0-.2.1-.4.4-.4.7 0 1.4.3 2 .8.5.6.8 1.3.8 2V11c0 .3.1.6.4.8.2.3.5.4.8.4.2 0 .4.2.4.4v.8c0 .2-.2.4-.4.4-.3 0-.6.1-.8.4-.3.2-.4.5-.4.8v1.7c0 .7-.3 1.4-.8 2-.6.5-1.3.8-2 .8a.4.4 0 01-.4-.4v-.8c0-.2.1-.4.4-.4.3 0 .6-.1.8-.4.3-.2.4-.5.4-.8V15a2.8 2.8 0 01.8-2 2.8 2.8 0 01-.8-2zm-3.3-.4c0 .4-.1.8-.5 1.1-.3.3-.7.5-1.1.5-.4 0-.8-.2-1.1-.5-.4-.3-.5-.7-.5-1.1 0-.5.1-.9.5-1.2.3-.3.7-.4 1.1-.4.4 0 .8.1 1.1.4.4.3.5.7.5 1.2zM12 13c.4 0 .8.1 1.1.5.4.3.5.7.5 1.1 0 1-.1 1.6-.5 2a3 3 0 01-1.1 1c-.4.3-.8.4-1.1.4a.5.5 0 01-.5-.5V17a3 3 0 001-.2l.6-.6c-.6 0-1-.2-1.3-.5-.2-.3-.3-.7-.3-1 0-.5.1-1 .5-1.2.3-.4.7-.5 1.1-.5z" fill-rule="evenodd"/></svg>',
      "color-levels": '<svg width="24" height="24"><path d="M17.5 11.4A9 9 0 0118 14c0 .5 0 1-.2 1.4 0 .4-.3.9-.5 1.3a6.2 6.2 0 01-3.7 3 5.7 5.7 0 01-3.2 0A5.9 5.9 0 017.6 18a6.2 6.2 0 01-1.4-2.6 6.7 6.7 0 010-2.8c0-.4.1-.9.3-1.3a13.6 13.6 0 012.3-4A20 20 0 0112 4a26.4 26.4 0 013.2 3.4 18.2 18.2 0 012.3 4zm-2 4.5c.4-.7.5-1.4.5-2a7.3 7.3 0 00-1-3.2c.2.6.2 1.2.2 1.9a4.5 4.5 0 01-1.3 3 5.3 5.3 0 01-2.3 1.5 4.9 4.9 0 01-2 .1 4.3 4.3 0 002.4.8 4 4 0 002-.6 4 4 0 001.5-1.5z" fill-rule="evenodd"/></svg>',
      "color-picker": '<svg width="24" height="24"><path d="M12 3a9 9 0 000 18 1.5 1.5 0 001.1-2.5c-.2-.3-.4-.6-.4-1 0-.8.7-1.5 1.5-1.5H16a5 5 0 005-5c0-4.4-4-8-9-8zm-5.5 9a1.5 1.5 0 110-3 1.5 1.5 0 010 3zm3-4a1.5 1.5 0 110-3 1.5 1.5 0 010 3zm5 0a1.5 1.5 0 110-3 1.5 1.5 0 010 3zm3 4a1.5 1.5 0 110-3 1.5 1.5 0 010 3z" fill-rule="nonzero"/></svg>',
      "color-swatch-remove-color": '<svg width="24" height="24"><path stroke="#000" stroke-width="2" d="M21 3L3 21" fill-rule="evenodd"/></svg>',
      "color-swatch": '<svg width="24" height="24"><rect x="3" y="3" width="18" height="18" rx="1" fill-rule="evenodd"/></svg>',
      "comment-add": '<svg width="24" height="24"><g fill-rule="nonzero"><path d="M9 19l3-2h7c.6 0 1-.4 1-1V6c0-.6-.4-1-1-1H5a1 1 0 00-1 1v10c0 .6.4 1 1 1h4v2zm-2 4v-4H5a3 3 0 01-3-3V6a3 3 0 013-3h14a3 3 0 013 3v10a3 3 0 01-3 3h-6.4L7 23z"/><path d="M13 10h2a1 1 0 010 2h-2v2a1 1 0 01-2 0v-2H9a1 1 0 010-2h2V8a1 1 0 012 0v2z"/></g></svg>',
      "comment": '<svg width="24" height="24"><path fill-rule="nonzero" d="M9 19l3-2h7c.6 0 1-.4 1-1V6c0-.6-.4-1-1-1H5a1 1 0 00-1 1v10c0 .6.4 1 1 1h4v2zm-2 4v-4H5a3 3 0 01-3-3V6a3 3 0 013-3h14a3 3 0 013 3v10a3 3 0 01-3 3h-6.4L7 23z"/></svg>',
      "contrast": '<svg width="24" height="24"><path d="M12 4a7.8 7.8 0 015.7 2.3A8 8 0 1112 4zm-6 8a6 6 0 006 6V6a6 6 0 00-6 6z" fill-rule="evenodd"/></svg>',
      "copy": '<svg width="24" height="24"><path d="M16 3H6a2 2 0 00-2 2v11h2V5h10V3zm1 4a2 2 0 012 2v10a2 2 0 01-2 2h-7a2 2 0 01-2-2V9c0-1.2.9-2 2-2h7zm0 12V9h-7v10h7z" fill-rule="nonzero"/></svg>',
      "crop": '<svg width="24" height="24"><path d="M17 8v7h2c.6 0 1 .4 1 1s-.4 1-1 1h-2v2c0 .6-.4 1-1 1a1 1 0 01-1-1v-2H7V9H5a1 1 0 110-2h2V5c0-.6.4-1 1-1s1 .4 1 1v2h7l3-3 1 1-3 3zM9 9v5l5-5H9zm1 6h5v-5l-5 5z" fill-rule="evenodd"/></svg>',
      "cut-column": '<svg width="24" height="24"><path fill-rule="evenodd" d="M7.2 4.5c.9 0 1.6.4 2.2 1A3.7 3.7 0 0110.5 8v.5l1 1 4-4 1-.5a3.3 3.3 0 012 0c.4 0 .7.3 1 .5L17 8h4v13h-6V10l-1.5 1.5.5.5v4l-2.5-2.5-1 1v.5c0 .4 0 .8-.3 1.2-.2.5-.4.9-.8 1.2-.6.7-1.3 1-2.2 1-.8.2-1.5 0-2-.6l-.5-.8-.2-1c0-.4 0-.8.3-1.2A3.9 3.9 0 017 12.7c.5-.2 1-.3 1.5-.2l1-1-1-1c-.5 0-1 0-1.5-.2-.5-.1-1-.4-1.4-.9-.4-.3-.6-.7-.8-1.2L4.5 7c0-.4 0-.7.2-1 0-.3.3-.6.5-.8.5-.5 1.2-.8 2-.7zm12.3 5h-3v10h3v-10zM8 13.8h-.3l-.4.2a2.8 2.8 0 00-.7.4v.1a2.8 2.8 0 00-.6.8l-.1.4v.7l.2.5.5.2h.7a2.6 2.6 0 00.8-.3 2.4 2.4 0 00.7-.7 2.5 2.5 0 00.3-.8 1.5 1.5 0 000-.8 1 1 0 00-.2-.4 1 1 0 00-.5-.2H8zm3.5-3.7c-.4 0-.7.1-1 .4-.3.3-.4.6-.4 1s.1.7.4 1c.3.3.6.4 1 .4s.7-.1 1-.4c.3-.3.4-.6.4-1s-.1-.7-.4-1c-.3-.3-.6-.4-1-.4zM7 5.8h-.4a1 1 0 00-.5.3 1 1 0 00-.2.5v.7a2.5 2.5 0 00.3.8l.2.3h.1l.4.4.4.2.4.1h.7L9 9l.2-.4a1.6 1.6 0 000-.8 2.6 2.6 0 00-.3-.8A2.5 2.5 0 007.7 6l-.4-.1H7z"/></svg>',
      "cut-row": '<svg width="24" height="24"><path fill-rule="evenodd" d="M22 3v5H9l3 3 2-2h4l-4 4 1 1h.5c.4 0 .8 0 1.2.3.5.2.9.4 1.2.8.7.6 1 1.3 1 2.2.2.8 0 1.5-.6 2l-.8.5-1 .2c-.4 0-.8 0-1.2-.3a3.9 3.9 0 01-2.1-2.2c-.2-.5-.3-1-.2-1.5l-1-1-1 1c0 .5 0 1-.2 1.5-.1.5-.4 1-.9 1.4-.3.4-.7.6-1.2.8l-1.2.3c-.4 0-.7 0-1-.2-.3 0-.6-.3-.8-.5-.5-.5-.8-1.2-.7-2 0-.9.4-1.6 1-2.2A3.7 3.7 0 018.6 14H9l1-1-4-4-.5-1a3.3 3.3 0 010-2c0-.4.3-.7.5-1l2 2V3h14zM8.5 15.3h-.3a2.6 2.6 0 00-.8.4 2.5 2.5 0 00-.9 1.1l-.1.4v.7l.2.5.5.2h.7a2.5 2.5 0 00.8-.3L9 18V18l.4-.4.2-.4.1-.4v-.3-.4a1 1 0 00-.2-.5 1 1 0 00-.4-.2h-.5zm7 0H15a1 1 0 00-.4.3 1 1 0 00-.2.5 1.5 1.5 0 000 .7v.4a2.8 2.8 0 00.5.7h.1a2.8 2.8 0 00.8.6l.4.1h.7l.5-.2.2-.5v-.4-.3a2.6 2.6 0 00-.3-.8 2.4 2.4 0 00-.7-.7 2.5 2.5 0 00-.8-.3h-.3zM12 11.6c-.4 0-.7.1-1 .4-.3.3-.4.6-.4 1s.1.7.4 1c.3.3.6.4 1 .4s.7-.1 1-.4c.3-.3.4-.6.4-1s-.1-.7-.4-1c-.3-.3-.6-.4-1-.4zm8.5-7.1h-11v2h11v-2z"/></svg>',
      "cut": '<svg width="24" height="24"><path d="M18 15c.6.7 1 1.4 1 2.3 0 .8-.2 1.5-.7 2l-.8.5-1 .2c-.4 0-.8 0-1.2-.3a3.9 3.9 0 01-2.1-2.2c-.2-.5-.3-1-.2-1.5l-1-1-1 1c0 .5 0 1-.2 1.5-.1.5-.4 1-.9 1.4-.3.4-.7.6-1.2.8l-1.2.3c-.4 0-.7 0-1-.2-.3 0-.6-.3-.8-.5-.5-.5-.8-1.2-.7-2 0-.9.4-1.6 1-2.2A3.7 3.7 0 018.6 14H9l1-1-4-4-.5-1a3.3 3.3 0 010-2c0-.4.3-.7.5-1l6 6 6-6 .5 1a3.3 3.3 0 010 2c0 .4-.3.7-.5 1l-4 4 1 1h.5c.4 0 .8 0 1.2.3.5.2.9.4 1.2.8zm-8.5 2.2l.1-.4v-.3-.4a1 1 0 00-.2-.5 1 1 0 00-.4-.2 1.6 1.6 0 00-.8 0 2.6 2.6 0 00-.8.3 2.5 2.5 0 00-.9 1.1l-.1.4v.7l.2.5.5.2h.7a2.5 2.5 0 00.8-.3 2.8 2.8 0 001-1zm2.5-2.8c.4 0 .7-.1 1-.4.3-.3.4-.6.4-1s-.1-.7-.4-1c-.3-.3-.6-.4-1-.4s-.7.1-1 .4c-.3.3-.4.6-.4 1s.1.7.4 1c.3.3.6.4 1 .4zm5.4 4l.2-.5v-.4-.3a2.6 2.6 0 00-.3-.8 2.4 2.4 0 00-.7-.7 2.5 2.5 0 00-.8-.3 1.5 1.5 0 00-.8 0 1 1 0 00-.4.2 1 1 0 00-.2.5 1.5 1.5 0 000 .7v.4l.3.4.3.4a2.8 2.8 0 00.8.5l.4.1h.7l.5-.2z" fill-rule="evenodd"/></svg>',
      "document-properties": '<svg width="24" height="24"><path d="M14.4 3H7a2 2 0 00-2 2v14c0 1.1.9 2 2 2h10a2 2 0 002-2V7.6L14.4 3zM17 19H7V5h6v4h4v10z" fill-rule="nonzero"/></svg>',
      "drag": '<svg width="24" height="24"><path d="M13 5h2v2h-2V5zm0 4h2v2h-2V9zM9 9h2v2H9V9zm4 4h2v2h-2v-2zm-4 0h2v2H9v-2zm0 4h2v2H9v-2zm4 0h2v2h-2v-2zM9 5h2v2H9V5z" fill-rule="evenodd"/></svg>',
      "duplicate-column": '<svg width="24" height="24"><path d="M17 6v16h-7V6h7zm-2 2h-3v12h3V8zm-2-6v2H8v15H6V2h7z"/></svg>',
      "duplicate-row": '<svg width="24" height="24"><path d="M22 11v7H6v-7h16zm-2 2H8v3h12v-3zm-1-6v2H4v5H2V7h17z"/></svg>',
      "duplicate": '<svg width="24" height="24"><g fill-rule="nonzero"><path d="M16 3v2H6v11H4V5c0-1.1.9-2 2-2h10zm3 8h-2V9h-7v10h9a2 2 0 01-2 2h-7a2 2 0 01-2-2V9c0-1.2.9-2 2-2h7a2 2 0 012 2v2z"/><path d="M17 14h1a1 1 0 010 2h-1v1a1 1 0 01-2 0v-1h-1a1 1 0 010-2h1v-1a1 1 0 012 0v1z"/></g></svg>',
      "edit-block": '<svg width="24" height="24"><path fill-rule="nonzero" d="M19.8 8.8l-9.4 9.4c-.2.2-.5.4-.9.4l-5.4 1.2 1.2-5.4.5-.8 9.4-9.4c.7-.7 1.8-.7 2.5 0l2.1 2.1c.7.7.7 1.8 0 2.5zm-2-.2l1-.9v-.3l-2.2-2.2a.3.3 0 00-.3 0l-1 1L18 8.5zm-1 1l-2.5-2.4-6 6 2.5 2.5 6-6zm-7 7.1l-2.6-2.4-.3.3-.1.2-.7 3 3.1-.6h.1l.4-.5z"/></svg>',
      "edit-image": '<svg width="24" height="24"><path d="M18 16h2V7a2 2 0 00-2-2H7v2h11v9zM6 17h15a1 1 0 010 2h-1v1a1 1 0 01-2 0v-1H6a2 2 0 01-2-2V7H3a1 1 0 110-2h1V4a1 1 0 112 0v13zm3-5.3l1.3 2 3-4.7 3.7 6H7l2-3.3z" fill-rule="nonzero"/></svg>',
      "embed-page": '<svg width="24" height="24"><path d="M19 6V5H5v14h2A13 13 0 0119 6zm0 1.4c-.8.8-1.6 2.4-2.2 4.6H19V7.4zm0 5.6h-2.4c-.4 1.8-.6 3.8-.6 6h3v-6zm-4 6c0-2.2.2-4.2.6-6H13c-.7 1.8-1.1 3.8-1.1 6h3zm-4 0c0-2.2.4-4.2 1-6H9.6A12 12 0 008 19h3zM4 3h16c.6 0 1 .4 1 1v16c0 .6-.4 1-1 1H4a1 1 0 01-1-1V4c0-.6.4-1 1-1zm11.8 9c.4-1.9 1-3.4 1.8-4.5a9.2 9.2 0 00-4 4.5h2.2zm-3.4 0a12 12 0 012.8-4 12 12 0 00-5 4h2.2z" fill-rule="nonzero"/></svg>',
      "embed": '<svg width="24" height="24"><path d="M4 3h16c.6 0 1 .4 1 1v16c0 .6-.4 1-1 1H4a1 1 0 01-1-1V4c0-.6.4-1 1-1zm1 2v14h14V5H5zm4.8 2.6l5.6 4a.5.5 0 010 .8l-5.6 4A.5.5 0 019 16V8a.5.5 0 01.8-.4z" fill-rule="nonzero"/></svg>',
      "emoji": '<svg width="24" height="24"><path d="M9 11c.6 0 1-.4 1-1s-.4-1-1-1a1 1 0 00-1 1c0 .6.4 1 1 1zm6 0c.6 0 1-.4 1-1s-.4-1-1-1a1 1 0 00-1 1c0 .6.4 1 1 1zm-3 5.5c2.1 0 4-1.5 4.4-3.5H7.6c.5 2 2.3 3.5 4.4 3.5zM12 4a8 8 0 100 16 8 8 0 000-16zm0 14.5a6.5 6.5 0 110-13 6.5 6.5 0 010 13z" fill-rule="nonzero"/></svg>',
      "export": '<svg width="24" height="24"><g fill-rule="nonzero"><path d="M14.4 3L18 7v1h-5V5H7v14h9a1 1 0 012 0c0 1-.8 2-1.9 2H7c-1 0-2-.8-2-1.9V5c0-1 .8-2 1.9-2h7.5z"/><path d="M18.1 12c.5 0 .9.4.9 1 0 .5-.3 1-.8 1h-7.3c-.5 0-.9-.4-.9-1 0-.5.3-1 .8-1h7.3z"/><path d="M16.4 9.2a1 1 0 011.4.2l2.4 3.6-2.4 3.6a1 1 0 01-1.7-1v-.2l1.7-2.4-1.6-2.4a1 1 0 01.2-1.4z"/></g></svg>',
      "fill": '<svg width="24" height="26"><path d="M16.6 12l-9-9-1.4 1.4 2.4 2.4-5.2 5.1c-.5.6-.5 1.6 0 2.2L9 19.6a1.5 1.5 0 002.2 0l5.5-5.5c.5-.6.5-1.6 0-2.2zM5.2 13L10 8.2l4.8 4.8H5.2zM19 14.5s-2 2.2-2 3.5c0 1.1.9 2 2 2a2 2 0 002-2c0-1.3-2-3.5-2-3.5z" fill-rule="nonzero"/></svg>',
      "flip-horizontally": '<svg width="24" height="24"><path d="M14 19h2v-2h-2v2zm4-8h2V9h-2v2zM4 7v10c0 1.1.9 2 2 2h3v-2H6V7h3V5H6a2 2 0 00-2 2zm14-2v2h2a2 2 0 00-2-2zm-7 16h2V3h-2v18zm7-6h2v-2h-2v2zm-4-8h2V5h-2v2zm4 12a2 2 0 002-2h-2v2z" fill-rule="nonzero"/></svg>',
      "flip-vertically": '<svg width="24" height="24"><path d="M5 14v2h2v-2H5zm8 4v2h2v-2h-2zm4-14H7a2 2 0 00-2 2v3h2V6h10v3h2V6a2 2 0 00-2-2zm2 14h-2v2a2 2 0 002-2zM3 11v2h18v-2H3zm6 7v2h2v-2H9zm8-4v2h2v-2h-2zM5 18c0 1.1.9 2 2 2v-2H5z" fill-rule="nonzero"/></svg>',
      "format-painter": '<svg width="24" height="24"><path d="M18 5V4c0-.5-.4-1-1-1H5a1 1 0 00-1 1v4c0 .6.5 1 1 1h12c.6 0 1-.4 1-1V7h1v4H9v9c0 .6.4 1 1 1h2c.6 0 1-.4 1-1v-7h8V5h-3z" fill-rule="nonzero"/></svg>',
      "format": '<svg width="24" height="24"><path fill-rule="evenodd" d="M17 5a1 1 0 010 2h-4v11a1 1 0 01-2 0V7H7a1 1 0 110-2h10z"/></svg>',
      "fullscreen": '<svg width="24" height="24"><path d="M15.3 10l-1.2-1.3 2.9-3h-2.3a.9.9 0 110-1.7H19c.5 0 .9.4.9.9v4.4a.9.9 0 11-1.8 0V7l-2.9 3zm0 4l3 3v-2.3a.9.9 0 111.7 0V19c0 .5-.4.9-.9.9h-4.4a.9.9 0 110-1.8H17l-3-2.9 1.3-1.2zM10 15.4l-2.9 3h2.3a.9.9 0 110 1.7H5a.9.9 0 01-.9-.9v-4.4a.9.9 0 111.8 0V17l2.9-3 1.2 1.3zM8.7 10L5.7 7v2.3a.9.9 0 01-1.7 0V5c0-.5.4-.9.9-.9h4.4a.9.9 0 010 1.8H7l3 2.9-1.3 1.2z" fill-rule="nonzero"/></svg>',
      "gallery": '<svg width="24" height="24"><path fill-rule="nonzero" d="M5 15.7l2.3-2.2c.3-.3.7-.3 1 0L11 16l5.1-5c.3-.4.8-.4 1 0l2 1.9V8H5v7.7zM5 18V19h3l1.8-1.9-2-2L5 17.9zm14-3l-2.5-2.4-6.4 6.5H19v-4zM4 6h16c.6 0 1 .4 1 1v13c0 .6-.4 1-1 1H4a1 1 0 01-1-1V7c0-.6.4-1 1-1zm6 7a2 2 0 110-4 2 2 0 010 4zM4.5 4h15a.5.5 0 110 1h-15a.5.5 0 010-1zm2-2h11a.5.5 0 110 1h-11a.5.5 0 010-1z"/></svg>',
      "gamma": '<svg width="24" height="24"><path d="M4 3h16c.6 0 1 .4 1 1v16c0 .6-.4 1-1 1H4a1 1 0 01-1-1V4c0-.6.4-1 1-1zm1 2v14h14V5H5zm6.5 11.8V14L9.2 8.7a5.1 5.1 0 00-.4-.8l-.1-.2H8 8v-1l.3-.1.3-.1h.7a1 1 0 01.6.5l.1.3a8.5 8.5 0 01.3.6l1.9 4.6 2-5.2a1 1 0 011-.6.5.5 0 01.5.6L13 14v2.8a.7.7 0 01-1.4 0z" fill-rule="nonzero"/></svg>',
      "help": '<svg width="24" height="24"><g fill-rule="evenodd"><path d="M12 5.5a6.5 6.5 0 00-6 9 6.3 6.3 0 001.4 2l1 1a6.3 6.3 0 003.6 1 6.5 6.5 0 006-9 6.3 6.3 0 00-1.4-2l-1-1a6.3 6.3 0 00-3.6-1zM12 4a7.8 7.8 0 015.7 2.3A8 8 0 1112 4z"/><path d="M9.6 9.7a.7.7 0 01-.7-.8c0-1.1 1.5-1.8 3.2-1.8 1.8 0 3.2.8 3.2 2.4 0 1.4-.4 2.1-1.5 2.8-.2 0-.3.1-.3.2a2 2 0 00-.8.8.8.8 0 01-1.4-.6c.3-.7.8-1 1.3-1.5l.4-.2c.7-.4.8-.6.8-1.5 0-.5-.6-.9-1.7-.9-.5 0-1 .1-1.4.3-.2 0-.3.1-.3.2v-.2c0 .4-.4.8-.8.8z" fill-rule="nonzero"/><circle cx="12" cy="16" r="1"/></g></svg>',
      "highlight-bg-color": '<svg width="24" height="24"><g fill-rule="evenodd"><path id="tox-icon-highlight-bg-color__color" d="M3 18h18v3H3z"/><path fill-rule="nonzero" d="M7.7 16.7H3l3.3-3.3-.7-.8L10.2 8l4 4.1-4 4.2c-.2.2-.6.2-.8 0l-.6-.7-1.1 1.1zm5-7.5L11 7.4l3-2.9a2 2 0 012.6 0L18 6c.7.7.7 2 0 2.7l-2.9 2.9-1.8-1.8-.5-.6"/></g></svg>',
      "home": '<svg width="24" height="24"><path fill-rule="nonzero" d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z"/></svg>',
      "horizontal-rule": '<svg width="24" height="24"><path d="M4 11h16v2H4z" fill-rule="evenodd"/></svg>',
      "image-options": '<svg width="24" height="24"><path d="M6 10a2 2 0 00-2 2c0 1.1.9 2 2 2a2 2 0 002-2 2 2 0 00-2-2zm12 0a2 2 0 00-2 2c0 1.1.9 2 2 2a2 2 0 002-2 2 2 0 00-2-2zm-6 0a2 2 0 00-2 2c0 1.1.9 2 2 2a2 2 0 002-2 2 2 0 00-2-2z" fill-rule="nonzero"/></svg>',
      "image": '<svg width="24" height="24"><path d="M5 15.7l3.3-3.2c.3-.3.7-.3 1 0L12 15l4.1-4c.3-.4.8-.4 1 0l2 1.9V5H5v10.7zM5 18V19h3l2.8-2.9-2-2L5 17.9zm14-3l-2.5-2.4-6.4 6.5H19v-4zM4 3h16c.6 0 1 .4 1 1v16c0 .6-.4 1-1 1H4a1 1 0 01-1-1V4c0-.6.4-1 1-1zm6 8a2 2 0 100-4 2 2 0 000 4z" fill-rule="nonzero"/></svg>',
      "indent": '<svg width="24" height="24"><path d="M7 5h12c.6 0 1 .4 1 1s-.4 1-1 1H7a1 1 0 110-2zm5 4h7c.6 0 1 .4 1 1s-.4 1-1 1h-7a1 1 0 010-2zm0 4h7c.6 0 1 .4 1 1s-.4 1-1 1h-7a1 1 0 010-2zm-5 4h12a1 1 0 010 2H7a1 1 0 010-2zm-2.6-3.8L6.2 12l-1.8-1.2a1 1 0 011.2-1.6l3 2a1 1 0 010 1.6l-3 2a1 1 0 11-1.2-1.6z" fill-rule="evenodd"/></svg>',
      "info": '<svg width="24" height="24"><path d="M12 4a7.8 7.8 0 015.7 2.3A8 8 0 1112 4zm-1 3v2h2V7h-2zm3 10v-1h-1v-5h-3v1h1v4h-1v1h4z" fill-rule="evenodd"/></svg>',
      "insert-character": '<svg width="24" height="24"><path d="M15 18h4l1-2v4h-6v-3.3l1.4-1a6 6 0 001.8-2.9 6.3 6.3 0 00-.1-4.1 5.8 5.8 0 00-3-3.2c-.6-.3-1.3-.5-2.1-.5a5.1 5.1 0 00-3.9 1.8 6.3 6.3 0 00-1.3 6 6.2 6.2 0 001.8 3l1.4.9V20H4v-4l1 2h4v-.5l-2-1L5.4 15A6.5 6.5 0 014 11c0-1 .2-1.9.6-2.7A7 7 0 016.3 6C7.1 5.4 8 5 9 4.5c1-.3 2-.5 3.1-.5a8.8 8.8 0 015.7 2 7 7 0 011.7 2.3 6 6 0 01.2 4.8c-.2.7-.6 1.3-1 1.9a7.6 7.6 0 01-3.6 2.5v.5z" fill-rule="evenodd"/></svg>',
      "insert-time": '<svg width="24" height="24"><g fill-rule="nonzero"><path d="M12 19a7 7 0 100-14 7 7 0 000 14zm0 2a9 9 0 110-18 9 9 0 010 18z"/><path d="M16 12h-3V7c0-.6-.4-1-1-1a1 1 0 00-1 1v7h5c.6 0 1-.4 1-1s-.4-1-1-1z"/></g></svg>',
      "invert": '<svg width="24" height="24"><path d="M18 19.3L16.5 18a5.8 5.8 0 01-3.1 1.9 6.1 6.1 0 01-5.5-1.6A5.8 5.8 0 016 14v-.3l.1-1.2A13.9 13.9 0 017.7 9l-3-3 .7-.8 2.8 2.9 9 8.9 1.5 1.6-.7.6zm0-5.5v.3l-.1 1.1-.4 1-1.2-1.2a4.3 4.3 0 00.2-1v-.2c0-.4 0-.8-.2-1.3l-.5-1.4a14.8 14.8 0 00-3-4.2L12 6a26.1 26.1 0 00-2.2 2.5l-1-1a20.9 20.9 0 012.9-3.3L12 4l1 .8a22.2 22.2 0 014 5.4c.6 1.2 1 2.4 1 3.6z" fill-rule="evenodd"/></svg>',
      "italic": '<svg width="24" height="24"><path d="M16.7 4.7l-.1.9h-.3c-.6 0-1 0-1.4.3-.3.3-.4.6-.5 1.1l-2.1 9.8v.6c0 .5.4.8 1.4.8h.2l-.2.8H8l.2-.8h.2c1.1 0 1.8-.5 2-1.5l2-9.8.1-.5c0-.6-.4-.8-1.4-.8h-.3l.2-.9h5.8z" fill-rule="evenodd"/></svg>',
      "language": '<svg width="24" height="24"><path d="M12 3a9 9 0 110 18 9 9 0 010-18zm4.3 13.3c-.5 1-1.2 2-2 2.9a7.5 7.5 0 003.2-2.1l-.2-.2a6 6 0 00-1-.6zm-8.6 0c-.5.2-.9.5-1.2.8.9 1 2 1.7 3.2 2a10 10 0 01-2-2.8zm3.6-.8c-.8 0-1.6.1-2.2.3.5 1 1.2 1.9 2.1 2.7zm1.5 0v3c.9-.8 1.6-1.7 2.1-2.7-.6-.2-1.4-.3-2.1-.3zm-6-2.7H4.5c.2 1 .5 2.1 1 3h.3l1.3-1a10 10 0 01-.3-2zm12.7 0h-2.3c0 .7-.1 1.4-.3 2l1.6 1.1c.5-1 .9-2 1-3.1zm-3.8 0h-3V14c1 0 2 .1 2.7.4.2-.5.3-1 .3-1.6zm-4.4 0h-3l.3 1.6c.8-.3 1.7-.4 2.7-.4v-1.3zm-5.5-5c-.7 1-1.1 2.2-1.3 3.5h2.3c0-1 .2-1.8.5-2.6l-1.5-1zm2.9 1.4v.1c-.2.6-.4 1.3-.4 2h3V9.4c-1 0-1.8-.1-2.6-.3zm6.6 0h-.1l-2.4.3v1.8h3l-.5-2.1zm3-1.4l-.3.1-1.3.8c.3.8.5 1.6.5 2.6h2.3a7.5 7.5 0 00-1.3-3.5zm-9 0l2 .2V5.5a9 9 0 00-2 2.2zm3.5-2.3V8c.6 0 1.3 0 1.9-.2a9 9 0 00-2-2.3zm-3-.7h-.1c-1.1.4-2.1 1-3 1.8l1.2.7a10 10 0 011.9-2.5zm4.4 0l.1.1a10 10 0 011.8 2.4l1.1-.7a7.5 7.5 0 00-3-1.8z"/></svg>',
      "line-height": '<svg width="24" height="24"><path d="M21 5a1 1 0 01.1 2H13a1 1 0 01-.1-2H21zm0 4a1 1 0 01.1 2H13a1 1 0 01-.1-2H21zm0 4a1 1 0 01.1 2H13a1 1 0 01-.1-2H21zm0 4a1 1 0 01.1 2H13a1 1 0 01-.1-2H21zM7 3.6l3.7 3.7a1 1 0 01-1.3 1.5h-.1L8 7.3v9.2l1.3-1.3a1 1 0 011.3 0h.1c.4.4.4 1 0 1.3v.1L7 20.4l-3.7-3.7a1 1 0 011.3-1.5h.1L6 16.7V7.4L4.7 8.7a1 1 0 01-1.3 0h-.1a1 1 0 010-1.3v-.1L7 3.6z"/></svg>',
      "line": '<svg width="24" height="24"><path d="M15 9l-8 8H4v-3l8-8 3 3zm1-1l-3-3 1-1h1c-.2 0 0 0 0 0l2 2s0 .2 0 0v1l-1 1zM4 18h16v2H4v-2z" fill-rule="evenodd"/></svg>',
      "link": '<svg width="24" height="24"><path d="M6.2 12.3a1 1 0 011.4 1.4l-2.1 2a2 2 0 102.7 2.8l4.8-4.8a1 1 0 000-1.4 1 1 0 111.4-1.3 2.9 2.9 0 010 4L9.6 20a3.9 3.9 0 01-5.5-5.5l2-2zm11.6-.6a1 1 0 01-1.4-1.4l2-2a2 2 0 10-2.6-2.8L11 10.3a1 1 0 000 1.4A1 1 0 119.6 13a2.9 2.9 0 010-4L14.4 4a3.9 3.9 0 015.5 5.5l-2 2z" fill-rule="nonzero"/></svg>',
      "list-bull-circle": '<svg width="48" height="48"><g fill-rule="evenodd"><path d="M11 16a2 2 0 100-4 2 2 0 000 4zm0 1a3 3 0 110-6 3 3 0 010 6zM11 26a2 2 0 100-4 2 2 0 000 4zm0 1a3 3 0 110-6 3 3 0 010 6zM11 36a2 2 0 100-4 2 2 0 000 4zm0 1a3 3 0 110-6 3 3 0 010 6z" fill-rule="nonzero"/><path opacity=".2" d="M18 12h22v4H18zM18 22h22v4H18zM18 32h22v4H18z"/></g></svg>',
      "list-bull-default": '<svg width="48" height="48"><g fill-rule="evenodd"><circle cx="11" cy="14" r="3"/><circle cx="11" cy="24" r="3"/><circle cx="11" cy="34" r="3"/><path opacity=".2" d="M18 12h22v4H18zM18 22h22v4H18zM18 32h22v4H18z"/></g></svg>',
      "list-bull-square": '<svg width="48" height="48"><g fill-rule="evenodd"><path d="M8 11h6v6H8zM8 21h6v6H8zM8 31h6v6H8z"/><path opacity=".2" d="M18 12h22v4H18zM18 22h22v4H18zM18 32h22v4H18z"/></g></svg>',
      "list-num-default-rtl": '<svg width="48" height="48"><g fill-rule="evenodd"><path opacity=".2" d="M8 12h22v4H8zM8 22h22v4H8zM8 32h22v4H8z"/><path d="M37.4 17v-4.8l-1.6 1v-1.1l1.6-1h1.2V17zM33.3 17.1c-.5 0-.8-.3-.8-.7 0-.4.3-.7.8-.7.4 0 .7.3.7.7 0 .4-.3.7-.7.7zm1.7 5.7c0-1.2 1-2 2.2-2 1.3 0 2.1.8 2.1 1.8 0 .7-.3 1.2-1.3 2.2l-1.2 1v.2h2.6v1h-4.3v-.9l2-1.9c.8-.8 1-1.1 1-1.5 0-.5-.4-.8-1-.8-.5 0-.9.3-.9.9H35zm-1.7 4.3c-.5 0-.8-.3-.8-.7 0-.4.3-.7.8-.7.4 0 .7.3.7.7 0 .4-.3.7-.7.7zm3.2 7.3v-1h.7c.6 0 1-.3 1-.8 0-.4-.4-.7-1-.7s-1 .3-1 .8H35c0-1.1 1-1.8 2.2-1.8 1.2 0 2.1.6 2.1 1.6 0 .7-.4 1.2-1 1.3v.1c.7.1 1.3.7 1.3 1.4 0 1-1 1.9-2.4 1.9-1.3 0-2.2-.8-2.3-2h1.2c0 .6.5 1 1.1 1 .6 0 1-.4 1-1 0-.5-.3-.8-1-.8h-.7zm-3.3 2.7c-.4 0-.7-.3-.7-.7 0-.4.3-.7.7-.7.5 0 .8.3.8.7 0 .4-.3.7-.8.7z"/></g></svg>',
      "list-num-default": '<svg width="48" height="48"><g fill-rule="evenodd"><path opacity=".2" d="M18 12h22v4H18zM18 22h22v4H18zM18 32h22v4H18z"/><path d="M10 17v-4.8l-1.5 1v-1.1l1.6-1h1.2V17h-1.2zm3.6.1c-.4 0-.7-.3-.7-.7 0-.4.3-.7.7-.7.5 0 .7.3.7.7 0 .4-.2.7-.7.7zm-5 5.7c0-1.2.8-2 2.1-2s2.1.8 2.1 1.8c0 .7-.3 1.2-1.4 2.2l-1.1 1v.2h2.6v1H8.6v-.9l2-1.9c.8-.8 1-1.1 1-1.5 0-.5-.4-.8-1-.8-.5 0-.9.3-.9.9H8.5zm6.3 4.3c-.5 0-.7-.3-.7-.7 0-.4.2-.7.7-.7.4 0 .7.3.7.7 0 .4-.3.7-.7.7zM10 34.4v-1h.7c.6 0 1-.3 1-.8 0-.4-.4-.7-1-.7s-1 .3-1 .8H8.6c0-1.1 1-1.8 2.2-1.8 1.3 0 2.1.6 2.1 1.6 0 .7-.4 1.2-1 1.3v.1c.8.1 1.3.7 1.3 1.4 0 1-1 1.9-2.4 1.9-1.3 0-2.2-.8-2.3-2h1.2c0 .6.5 1 1.1 1 .7 0 1-.4 1-1 0-.5-.3-.8-1-.8h-.7zm4.7 2.7c-.4 0-.7-.3-.7-.7 0-.4.3-.7.7-.7.5 0 .8.3.8.7 0 .4-.3.7-.8.7z"/></g></svg>',
      "list-num-lower-alpha-rtl": '<svg width="48" height="48"><g fill-rule="evenodd"><path opacity=".2" d="M8 12h22v4H8zM8 22h22v4H8zM8 32h22v4H8z"/><path d="M36.5 16c-.9 0-1.5-.5-1.5-1.3s.6-1.3 1.8-1.4h1v-.4c0-.4-.2-.6-.7-.6-.4 0-.7.1-.8.4h-1.1c0-.8.8-1.4 2-1.4S39 12 39 13V16h-1.2v-.6c-.3.4-.8.7-1.4.7zm.4-.8c.6 0 1-.4 1-.9V14h-1c-.5.1-.7.3-.7.6 0 .4.3.6.7.6zM33.1 16.1c-.4 0-.7-.3-.7-.7 0-.4.3-.7.7-.7.5 0 .8.3.8.7 0 .4-.3.7-.8.7zM37.7 26c-.7 0-1.2-.2-1.5-.7v.7H35v-6.3h1.2v2.5c.3-.5.8-.9 1.5-.9 1.1 0 1.8 1 1.8 2.4 0 1.5-.7 2.4-1.8 2.4zm-.5-3.6c-.6 0-1 .5-1 1.3s.4 1.4 1 1.4c.7 0 1-.6 1-1.4 0-.8-.3-1.3-1-1.3zM33.2 26.1c-.4 0-.7-.3-.7-.7 0-.4.3-.7.7-.7.5 0 .8.3.8.7 0 .4-.3.7-.8.7zm6 7h-1c-.1-.5-.4-.8-1-.8s-1 .5-1 1.4c0 1 .4 1.4 1 1.4.5 0 .9-.2 1-.7h1c0 1-.8 1.7-2 1.7-1.4 0-2.2-.9-2.2-2.4s.8-2.4 2.2-2.4c1.2 0 2 .7 2 1.7zm-6.1 3c-.5 0-.7-.3-.7-.7 0-.4.2-.7.7-.7.4 0 .7.3.7.7 0 .4-.3.7-.7.7z"/></g></svg>',
      "list-num-lower-alpha": '<svg width="48" height="48"><g fill-rule="evenodd"><path opacity=".2" d="M18 12h22v4H18zM18 22h22v4H18zM18 32h22v4H18z"/><path d="M10.3 15.2c.5 0 1-.4 1-.9V14h-1c-.5.1-.8.3-.8.6 0 .4.3.6.8.6zm-.4.9c-1 0-1.5-.6-1.5-1.4 0-.8.6-1.3 1.7-1.4h1.1v-.4c0-.4-.2-.6-.7-.6-.5 0-.8.1-.9.4h-1c0-.8.8-1.4 2-1.4 1.1 0 1.8.6 1.8 1.6V16h-1.1v-.6h-.1c-.2.4-.7.7-1.3.7zm4.6 0c-.5 0-.7-.3-.7-.7 0-.4.2-.7.7-.7.4 0 .7.3.7.7 0 .4-.3.7-.7.7zm-3.2 10c-.6 0-1.2-.3-1.4-.8v.7H8.5v-6.3H10v2.5c.3-.5.8-.9 1.4-.9 1.2 0 1.9 1 1.9 2.4 0 1.5-.7 2.4-1.9 2.4zm-.4-3.7c-.7 0-1 .5-1 1.3s.3 1.4 1 1.4c.6 0 1-.6 1-1.4 0-.8-.4-1.3-1-1.3zm4 3.7c-.5 0-.7-.3-.7-.7 0-.4.2-.7.7-.7.4 0 .7.3.7.7 0 .4-.3.7-.7.7zm-2.2 7h-1.2c0-.5-.4-.8-.9-.8-.6 0-1 .5-1 1.4 0 1 .4 1.4 1 1.4.5 0 .8-.2 1-.7h1c0 1-.8 1.7-2 1.7-1.4 0-2.2-.9-2.2-2.4s.8-2.4 2.2-2.4c1.2 0 2 .7 2 1.7zm1.8 3c-.5 0-.8-.3-.8-.7 0-.4.3-.7.8-.7.4 0 .7.3.7.7 0 .4-.3.7-.7.7z"/></g></svg>',
      "list-num-lower-greek-rtl": '<svg width="48" height="48"><g fill-rule="evenodd"><path opacity=".2" d="M8 12h22v4H8zM8 22h22v4H8zM8 32h22v4H8z"/><path d="M37.4 16c-1.2 0-2-.8-2-2.3 0-1.5.8-2.4 2-2.4.6 0 1 .4 1.3 1v-.9H40v3.2c0 .4.1.5.4.5h.2v.9h-.6c-.6 0-1-.2-1-.7h-.2c-.2.4-.7.8-1.3.8zm.3-1c.6 0 1-.5 1-1.3s-.4-1.3-1-1.3-1 .5-1 1.3.4 1.4 1 1.4zM33.3 16.1c-.5 0-.8-.3-.8-.7 0-.4.3-.7.8-.7.4 0 .7.3.7.7 0 .4-.3.7-.7.7zM36 21.9c0-1.5.8-2.3 2.1-2.3 1.2 0 2 .6 2 1.6 0 .6-.3 1-.9 1.3.9.3 1.3.8 1.3 1.7 0 1.2-.7 1.9-1.8 1.9-.6 0-1.1-.3-1.4-.8v2.2H36V22zm1.8 1.2v-1h.3c.5 0 .9-.2.9-.7 0-.5-.3-.8-.9-.8-.5 0-.8.3-.8 1v2.2c0 .8.4 1.3 1 1.3s1-.4 1-1-.4-1-1.2-1h-.3zM33.3 26.1c-.5 0-.8-.3-.8-.7 0-.4.3-.7.8-.7.4 0 .7.3.7.7 0 .4-.3.7-.7.7zM37.1 34.6L34.8 30h1.4l1.7 3.5 1.7-3.5h1.1l-2.2 4.6v.1c.5.8.7 1.4.7 1.8 0 .4-.2.8-.4 1-.2.2-.6.3-1 .3-.9 0-1.3-.4-1.3-1.2 0-.5.2-1 .5-1.7l.1-.2zm.7 1a2 2 0 00-.4.9c0 .3.1.4.4.4.3 0 .4-.1.4-.4 0-.2-.1-.6-.4-1zM33.3 36.1c-.5 0-.8-.3-.8-.7 0-.4.3-.7.8-.7.4 0 .7.3.7.7 0 .4-.3.7-.7.7z"/></g></svg>',
      "list-num-lower-greek": '<svg width="48" height="48"><g fill-rule="evenodd"><path opacity=".2" d="M18 12h22v4H18zM18 22h22v4H18zM18 32h22v4H18z"/><path d="M10.5 15c.7 0 1-.5 1-1.3s-.3-1.3-1-1.3c-.5 0-.9.5-.9 1.3s.4 1.4 1 1.4zm-.3 1c-1.1 0-1.8-.8-1.8-2.3 0-1.5.7-2.4 1.8-2.4.7 0 1.1.4 1.3 1h.1v-.9h1.2v3.2c0 .4.1.5.4.5h.2v.9h-.6c-.6 0-1-.2-1.1-.7h-.1c-.2.4-.7.8-1.4.8zm5 .1c-.5 0-.8-.3-.8-.7 0-.4.3-.7.7-.7.5 0 .8.3.8.7 0 .4-.3.7-.8.7zm-4.9 7v-1h.3c.6 0 1-.2 1-.7 0-.5-.4-.8-1-.8-.5 0-.8.3-.8 1v2.2c0 .8.4 1.3 1.1 1.3.6 0 1-.4 1-1s-.5-1-1.3-1h-.3zM8.6 22c0-1.5.7-2.3 2-2.3 1.2 0 2 .6 2 1.6 0 .6-.3 1-.8 1.3.8.3 1.3.8 1.3 1.7 0 1.2-.8 1.9-1.9 1.9-.6 0-1.1-.3-1.3-.8v2.2H8.5V22zm6.2 4.2c-.4 0-.7-.3-.7-.7 0-.4.3-.7.7-.7.5 0 .7.3.7.7 0 .4-.2.7-.7.7zm-4.5 8.5L8 30h1.4l1.7 3.5 1.7-3.5h1.1l-2.2 4.6v.1c.5.8.7 1.4.7 1.8 0 .4-.1.8-.4 1-.2.2-.6.3-1 .3-.9 0-1.3-.4-1.3-1.2 0-.5.2-1 .5-1.7l.1-.2zm.7 1a2 2 0 00-.4.9c0 .3.1.4.4.4.3 0 .4-.1.4-.4 0-.2-.1-.6-.4-1zm4.5.5c-.5 0-.8-.3-.8-.7 0-.4.3-.7.8-.7.4 0 .7.3.7.7 0 .4-.3.7-.7.7z"/></g></svg>',
      "list-num-lower-roman-rtl": '<svg width="48" height="48"><g fill-rule="evenodd"><path opacity=".2" d="M8 12h22v4H8zM8 22h22v4H8zM8 32h22v4H8z"/><path d="M32.9 16v-1.2h-1.3V16H33zm0 10v-1.2h-1.3V26H33zm0 10v-1.2h-1.3V36H33z"/><path fill-rule="nonzero" d="M36 21h-1.5v5H36zM36 31h-1.5v5H36zM39 21h-1.5v5H39zM39 31h-1.5v5H39zM42 31h-1.5v5H42zM36 11h-1.5v5H36zM36 19h-1.5v1H36zM36 29h-1.5v1H36zM39 19h-1.5v1H39zM39 29h-1.5v1H39zM42 29h-1.5v1H42zM36 9h-1.5v1H36z"/></g></svg>',
      "list-num-lower-roman": '<svg width="48" height="48"><g fill-rule="evenodd"><path opacity=".2" d="M18 12h22v4H18zM18 22h22v4H18zM18 32h22v4H18z"/><path d="M15.1 16v-1.2h1.3V16H15zm0 10v-1.2h1.3V26H15zm0 10v-1.2h1.3V36H15z"/><path fill-rule="nonzero" d="M12 21h1.5v5H12zM12 31h1.5v5H12zM9 21h1.5v5H9zM9 31h1.5v5H9zM6 31h1.5v5H6zM12 11h1.5v5H12zM12 19h1.5v1H12zM12 29h1.5v1H12zM9 19h1.5v1H9zM9 29h1.5v1H9zM6 29h1.5v1H6zM12 9h1.5v1H12z"/></g></svg>',
      "list-num-upper-alpha-rtl": '<svg width="48" height="48"><g fill-rule="evenodd"><path opacity=".2" d="M8 12h22v4H8zM8 22h22v4H8zM8 32h22v4H8z"/><path d="M39.3 17l-.5-1.4h-2l-.5 1.4H35l2-6h1.6l2 6h-1.3zm-1.6-4.7l-.7 2.3h1.6l-.8-2.3zM33.4 17c-.4 0-.7-.3-.7-.7 0-.4.3-.7.7-.7.5 0 .7.3.7.7 0 .4-.2.7-.7.7zm4.7 9.9h-2.7v-6H38c1.2 0 1.9.6 1.9 1.5 0 .6-.5 1.2-1 1.3.7.1 1.3.7 1.3 1.5 0 1-.8 1.7-2 1.7zm-1.4-5v1.5h1c.6 0 1-.3 1-.8 0-.4-.4-.7-1-.7h-1zm0 4h1.1c.7 0 1.1-.3 1.1-.8 0-.6-.4-.9-1.1-.9h-1.1V26zM33 27.1c-.5 0-.8-.3-.8-.7 0-.4.3-.7.8-.7.4 0 .7.3.7.7 0 .4-.3.7-.7.7zm4.9 10c-1.8 0-2.8-1.1-2.8-3.1s1-3.1 2.8-3.1c1.4 0 2.5.9 2.6 2.2h-1.3c0-.7-.6-1.1-1.3-1.1-1 0-1.6.7-1.6 2s.6 2 1.6 2c.7 0 1.2-.4 1.4-1h1.2c-.1 1.3-1.2 2.2-2.6 2.2zm-4.5 0c-.5 0-.8-.3-.8-.7 0-.4.3-.7.8-.7.4 0 .7.3.7.7 0 .4-.3.7-.7.7z"/></g></svg>',
      "list-num-upper-alpha": '<svg width="48" height="48"><g fill-rule="evenodd"><path opacity=".2" d="M18 12h22v4H18zM18 22h22v4H18zM18 32h22v4H18z"/><path d="M12.6 17l-.5-1.4h-2L9.5 17H8.3l2-6H12l2 6h-1.3zM11 12.3l-.7 2.3h1.6l-.8-2.3zm4.7 4.8c-.4 0-.7-.3-.7-.7 0-.4.3-.7.7-.7.5 0 .7.3.7.7 0 .4-.2.7-.7.7zM11.4 27H8.7v-6h2.6c1.2 0 1.9.6 1.9 1.5 0 .6-.5 1.2-1 1.3.7.1 1.3.7 1.3 1.5 0 1-.8 1.7-2 1.7zM10 22v1.5h1c.6 0 1-.3 1-.8 0-.4-.4-.7-1-.7h-1zm0 4H11c.7 0 1.1-.3 1.1-.8 0-.6-.4-.9-1.1-.9H10V26zm5.4 1.1c-.5 0-.8-.3-.8-.7 0-.4.3-.7.8-.7.4 0 .7.3.7.7 0 .4-.3.7-.7.7zm-4.1 10c-1.8 0-2.8-1.1-2.8-3.1s1-3.1 2.8-3.1c1.4 0 2.5.9 2.6 2.2h-1.3c0-.7-.6-1.1-1.3-1.1-1 0-1.6.7-1.6 2s.6 2 1.6 2c.7 0 1.2-.4 1.4-1h1.2c-.1 1.3-1.2 2.2-2.6 2.2zm4.5 0c-.5 0-.8-.3-.8-.7 0-.4.3-.7.8-.7.4 0 .7.3.7.7 0 .4-.3.7-.7.7z"/></g></svg>',
      "list-num-upper-roman-rtl": '<svg width="48" height="48"><g fill-rule="evenodd"><path opacity=".2" d="M8 12h22v4H8zM8 22h22v4H8zM8 32h22v4H8z"/><path d="M31.6 17v-1.2H33V17h-1.3zm0 10v-1.2H33V27h-1.3zm0 10v-1.2H33V37h-1.3z"/><path fill-rule="nonzero" d="M34.5 20H36v7h-1.5zM34.5 30H36v7h-1.5zM37.5 20H39v7h-1.5zM37.5 30H39v7h-1.5zM40.5 30H42v7h-1.5zM34.5 10H36v7h-1.5z"/></g></svg>',
      "list-num-upper-roman": '<svg width="48" height="48"><g fill-rule="evenodd"><path opacity=".2" d="M18 12h22v4H18zM18 22h22v4H18zM18 32h22v4H18z"/><path d="M15.1 17v-1.2h1.3V17H15zm0 10v-1.2h1.3V27H15zm0 10v-1.2h1.3V37H15z"/><path fill-rule="nonzero" d="M12 20h1.5v7H12zM12 30h1.5v7H12zM9 20h1.5v7H9zM9 30h1.5v7H9zM6 30h1.5v7H6zM12 10h1.5v7H12z"/></g></svg>',
      "lock": '<svg width="24" height="24"><path d="M16.3 11c.2 0 .3 0 .5.2l.2.6v7.4c0 .3 0 .4-.2.6l-.6.2H7.8c-.3 0-.4 0-.6-.2a.7.7 0 01-.2-.6v-7.4c0-.3 0-.4.2-.6l.5-.2H8V8c0-.8.3-1.5.9-2.1.6-.6 1.3-.9 2.1-.9h2c.8 0 1.5.3 2.1.9.6.6.9 1.3.9 2.1v3h.3zM10 8v3h4V8a1 1 0 00-.3-.7A1 1 0 0013 7h-2a1 1 0 00-.7.3 1 1 0 00-.3.7z" fill-rule="evenodd"/></svg>',
      "ltr": '<svg width="24" height="24"><path d="M11 5h7a1 1 0 010 2h-1v11a1 1 0 01-2 0V7h-2v11a1 1 0 01-2 0v-6c-.5 0-1 0-1.4-.3A3.4 3.4 0 017.8 10a3.3 3.3 0 010-2.8 3.4 3.4 0 011.8-1.8L11 5zM4.4 16.2L6.2 15l-1.8-1.2a1 1 0 011.2-1.6l3 2a1 1 0 010 1.6l-3 2a1 1 0 11-1.2-1.6z" fill-rule="evenodd"/></svg>',
      "more-drawer": '<svg width="24" height="24"><path d="M6 10a2 2 0 00-2 2c0 1.1.9 2 2 2a2 2 0 002-2 2 2 0 00-2-2zm12 0a2 2 0 00-2 2c0 1.1.9 2 2 2a2 2 0 002-2 2 2 0 00-2-2zm-6 0a2 2 0 00-2 2c0 1.1.9 2 2 2a2 2 0 002-2 2 2 0 00-2-2z" fill-rule="nonzero"/></svg>',
      "new-document": '<svg width="24" height="24"><path d="M14.4 3H7a2 2 0 00-2 2v14c0 1.1.9 2 2 2h10a2 2 0 002-2V7.6L14.4 3zM17 19H7V5h6v4h4v10z" fill-rule="nonzero"/></svg>',
      "new-tab": '<svg width="24" height="24"><path d="M15 13l2-2v8H5V7h8l-2 2H7v8h8v-4zm4-8v5.5l-2-2-5.6 5.5H10v-1.4L15.5 7l-2-2H19z" fill-rule="evenodd"/></svg>',
      "non-breaking": '<svg width="24" height="24"><path d="M11 11H8a1 1 0 110-2h3V6c0-.6.4-1 1-1s1 .4 1 1v3h3c.6 0 1 .4 1 1s-.4 1-1 1h-3v3c0 .6-.4 1-1 1a1 1 0 01-1-1v-3zm10 4v5H3v-5c0-.6.4-1 1-1s1 .4 1 1v3h14v-3c0-.6.4-1 1-1s1 .4 1 1z" fill-rule="evenodd"/></svg>',
      "notice": '<svg width="24" height="24"><path d="M17.8 9.8L15.4 4 20 8.5v7L15.5 20h-7L4 15.5v-7L8.5 4h7l2.3 5.8zm0 0l2.2 5.7-2.3-5.8zM13 17v-2h-2v2h2zm0-4V7h-2v6h2z" fill-rule="evenodd"/></svg>',
      "ordered-list-rtl": '<svg width="24" height="24"><path d="M6 17h8a1 1 0 010 2H6a1 1 0 010-2zm0-6h8a1 1 0 010 2H6a1 1 0 010-2zm0-6h8a1 1 0 010 2H6a1 1 0 110-2zm13-1v3.5a.5.5 0 11-1 0V5h-.5a.5.5 0 110-1H19zm-1 8.8l.2.2h1.3a.5.5 0 110 1h-1.6a1 1 0 01-.9-1V13c0-.4.3-.8.6-1l1.2-.4.2-.3a.2.2 0 00-.2-.2h-1.3a.5.5 0 01-.5-.5c0-.3.2-.5.5-.5h1.6c.5 0 .9.4.9 1v.1c0 .4-.3.8-.6 1l-1.2.4-.2.3zm2 4.2v2c0 .6-.4 1-1 1h-1.5a.5.5 0 010-1h1.2a.3.3 0 100-.6h-1.3a.4.4 0 110-.8h1.3a.3.3 0 000-.6h-1.2a.5.5 0 110-1H19c.6 0 1 .4 1 1z" fill-rule="evenodd"/></svg>',
      "ordered-list": '<svg width="24" height="24"><path d="M10 17h8c.6 0 1 .4 1 1s-.4 1-1 1h-8a1 1 0 010-2zm0-6h8c.6 0 1 .4 1 1s-.4 1-1 1h-8a1 1 0 010-2zm0-6h8c.6 0 1 .4 1 1s-.4 1-1 1h-8a1 1 0 110-2zM6 4v3.5c0 .3-.2.5-.5.5a.5.5 0 01-.5-.5V5h-.5a.5.5 0 010-1H6zm-1 8.8l.2.2h1.3c.3 0 .5.2.5.5s-.2.5-.5.5H4.9a1 1 0 01-.9-1V13c0-.4.3-.8.6-1l1.2-.4.2-.3a.2.2 0 00-.2-.2H4.5a.5.5 0 01-.5-.5c0-.3.2-.5.5-.5h1.6c.5 0 .9.4.9 1v.1c0 .4-.3.8-.6 1l-1.2.4-.2.3zM7 17v2c0 .6-.4 1-1 1H4.5a.5.5 0 010-1h1.2c.2 0 .3-.1.3-.3 0-.2-.1-.3-.3-.3H4.4a.4.4 0 110-.8h1.3c.2 0 .3-.1.3-.3 0-.2-.1-.3-.3-.3H4.5a.5.5 0 110-1H6c.6 0 1 .4 1 1z" fill-rule="evenodd"/></svg>',
      "orientation": '<svg width="24" height="24"><path d="M7.3 6.4L1 13l6.4 6.5 6.5-6.5-6.5-6.5zM3.7 13l3.6-3.7L11 13l-3.7 3.7-3.6-3.7zM12 6l2.8 2.7c.3.3.3.8 0 1-.3.4-.9.4-1.2 0L9.2 5.7a.8.8 0 010-1.2L13.6.2c.3-.3.9-.3 1.2 0 .3.3.3.8 0 1.1L12 4h1a9 9 0 11-4.3 16.9l1.5-1.5A7 7 0 1013 6h-1z" fill-rule="nonzero"/></svg>',
      "outdent": '<svg width="24" height="24"><path d="M7 5h12c.6 0 1 .4 1 1s-.4 1-1 1H7a1 1 0 110-2zm5 4h7c.6 0 1 .4 1 1s-.4 1-1 1h-7a1 1 0 010-2zm0 4h7c.6 0 1 .4 1 1s-.4 1-1 1h-7a1 1 0 010-2zm-5 4h12a1 1 0 010 2H7a1 1 0 010-2zm1.6-3.8a1 1 0 01-1.2 1.6l-3-2a1 1 0 010-1.6l3-2a1 1 0 011.2 1.6L6.8 12l1.8 1.2z" fill-rule="evenodd"/></svg>',
      "page-break": '<svg width="24" height="24"><g fill-rule="evenodd"><path d="M5 11c.6 0 1 .4 1 1s-.4 1-1 1a1 1 0 010-2zm3 0h1c.6 0 1 .4 1 1s-.4 1-1 1H8a1 1 0 010-2zm4 0c.6 0 1 .4 1 1s-.4 1-1 1a1 1 0 010-2zm3 0h1c.6 0 1 .4 1 1s-.4 1-1 1h-1a1 1 0 010-2zm4 0c.6 0 1 .4 1 1s-.4 1-1 1a1 1 0 010-2zM7 3v5h10V3c0-.6.4-1 1-1s1 .4 1 1v7H5V3c0-.6.4-1 1-1s1 .4 1 1zM6 22a1 1 0 01-1-1v-7h14v7c0 .6-.4 1-1 1a1 1 0 01-1-1v-5H7v5c0 .6-.4 1-1 1z"/></g></svg>',
      "paragraph": '<svg width="24" height="24"><path fill-rule="evenodd" d="M10 5h7a1 1 0 010 2h-1v11a1 1 0 01-2 0V7h-2v11a1 1 0 01-2 0v-6c-.5 0-1 0-1.4-.3A3.4 3.4 0 016.8 10a3.3 3.3 0 010-2.8 3.4 3.4 0 011.8-1.8L10 5z"/></svg>',
      "paste-column-after": '<svg width="24" height="24"><path fill-rule="evenodd" d="M12 1a3 3 0 012.8 2H18c1 0 2 .8 2 1.9V7h-2V5h-2v1c0 .6-.4 1-1 1H9a1 1 0 01-1-1V5H6v13h7v2H6c-1 0-2-.8-2-1.9V5c0-1 .8-2 1.9-2H9.2A3 3 0 0112 1zm8 7v12h-6V8h6zm-1.5 1.5h-3v9h3v-9zM12 3a1 1 0 100 2 1 1 0 000-2z"/></svg>',
      "paste-column-before": '<svg width="24" height="24"><path fill-rule="evenodd" d="M12 1a3 3 0 012.8 2H18c1 0 2 .8 2 1.9V18c0 1-.8 2-1.9 2H11v-2h7V5h-2v1c0 .6-.4 1-1 1H9a1 1 0 01-1-1V5H6v2H4V5c0-1 .8-2 1.9-2H9.2A3 3 0 0112 1zm-2 7v12H4V8h6zM8.5 9.5h-3v9h3v-9zM12 3a1 1 0 100 2 1 1 0 000-2z"/></svg>',
      "paste-row-after": '<svg width="24" height="24"><path fill-rule="evenodd" d="M12 1a3 3 0 012.8 2H18c1 0 2 .8 2 1.9V11h-2V5h-2v1c0 .6-.4 1-1 1H9a1 1 0 01-1-1V5H6v13h14c0 1-.8 2-1.9 2H6c-1 0-2-.8-2-1.9V5c0-1 .8-2 1.9-2H9.2A3 3 0 0112 1zm10 11v5H8v-5h14zm-1.5 1.5h-11v2h11v-2zM12 3a1 1 0 100 2 1 1 0 000-2z"/></svg>',
      "paste-row-before": '<svg width="24" height="24"><path fill-rule="evenodd" d="M12 1a3 3 0 012.8 2H18c1 0 2 .8 2 1.9V7h-2V5h-2v1c0 .6-.4 1-1 1H9a1 1 0 01-1-1V5H6v13h12v-4h2v4c0 1-.8 2-1.9 2H6c-1 0-2-.8-2-1.9V5c0-1 .8-2 1.9-2H9.2A3 3 0 0112 1zm10 7v5H8V8h14zm-1.5 1.5h-11v2h11v-2zM12 3a1 1 0 100 2 1 1 0 000-2z"/></svg>',
      "paste-text": '<svg width="24" height="24"><path d="M18 9V5h-2v1c0 .6-.4 1-1 1H9a1 1 0 01-1-1V5H6v13h3V9h9zM9 20H6a2 2 0 01-2-2V5c0-1.1.9-2 2-2h3.2A3 3 0 0112 1a3 3 0 012.8 2H18a2 2 0 012 2v4h1v12H9v-1zm1.5-9.5v9h9v-9h-9zM12 3a1 1 0 00-1 1c0 .5.4 1 1 1s1-.5 1-1-.4-1-1-1zm0 9h6v2h-.5l-.5-1h-1v4h.8v1h-3.6v-1h.8v-4h-1l-.5 1H12v-2z" fill-rule="nonzero"/></svg>',
      "paste": '<svg width="24" height="24"><path d="M18 9V5h-2v1c0 .6-.4 1-1 1H9a1 1 0 01-1-1V5H6v13h3V9h9zM9 20H6a2 2 0 01-2-2V5c0-1.1.9-2 2-2h3.2A3 3 0 0112 1a3 3 0 012.8 2H18a2 2 0 012 2v4h1v12H9v-1zm1.5-9.5v9h9v-9h-9zM12 3a1 1 0 00-1 1c0 .5.4 1 1 1s1-.5 1-1-.4-1-1-1z" fill-rule="nonzero"/></svg>',
      "permanent-pen": '<svg width="24" height="24"><path d="M10.5 17.5L8 20H3v-3l3.5-3.5a2 2 0 010-3L14 3l1 1-7.3 7.3a1 1 0 000 1.4l3.6 3.6c.4.4 1 .4 1.4 0L20 9l1 1-7.6 7.6a2 2 0 01-2.8 0l-.1-.1z" fill-rule="nonzero"/></svg>',
      "plus": '<svg width="24" height="24"><path d="M12 4c.5 0 1 .4 1 .9V11h6a1 1 0 01.1 2H13v6a1 1 0 01-2 .1V13H5a1 1 0 01-.1-2H11V5c0-.6.4-1 1-1z"/></svg>',
      "preferences": '<svg width="24" height="24"><path d="M20.1 13.5l-1.9.2a5.8 5.8 0 01-.6 1.5l1.2 1.5c.4.4.3 1 0 1.4l-.7.7a1 1 0 01-1.4 0l-1.5-1.2a6.2 6.2 0 01-1.5.6l-.2 1.9c0 .5-.5.9-1 .9h-1a1 1 0 01-1-.9l-.2-1.9a5.8 5.8 0 01-1.5-.6l-1.5 1.2a1 1 0 01-1.4 0l-.7-.7a1 1 0 010-1.4l1.2-1.5a6.2 6.2 0 01-.6-1.5l-1.9-.2a1 1 0 01-.9-1v-1c0-.5.4-1 .9-1l1.9-.2a5.8 5.8 0 01.6-1.5L5.2 7.3a1 1 0 010-1.4l.7-.7a1 1 0 011.4 0l1.5 1.2a6.2 6.2 0 011.5-.6l.2-1.9c0-.5.5-.9 1-.9h1c.5 0 1 .4 1 .9l.2 1.9a5.8 5.8 0 011.5.6l1.5-1.2a1 1 0 011.4 0l.7.7c.3.4.4 1 0 1.4l-1.2 1.5a6.2 6.2 0 01.6 1.5l1.9.2c.5 0 .9.5.9 1v1c0 .5-.4 1-.9 1zM12 15a3 3 0 100-6 3 3 0 000 6z" fill-rule="evenodd"/></svg>',
      "preview": '<svg width="24" height="24"><path d="M3.5 12.5c.5.8 1.1 1.6 1.8 2.3 2 2 4.2 3.2 6.7 3.2s4.7-1.2 6.7-3.2a16.2 16.2 0 002.1-2.8 15.7 15.7 0 00-2.1-2.8c-2-2-4.2-3.2-6.7-3.2a9.3 9.3 0 00-6.7 3.2A16.2 16.2 0 003.2 12c0 .2.2.3.3.5zm-2.4-1l.7-1.2L4 7.8C6.2 5.4 8.9 4 12 4c3 0 5.8 1.4 8.1 3.8a18.2 18.2 0 012.8 3.7v1l-.7 1.2-2.1 2.5c-2.3 2.4-5 3.8-8.1 3.8-3 0-5.8-1.4-8.1-3.8a18.2 18.2 0 01-2.8-3.7 1 1 0 010-1zm12-3.3a2 2 0 102.7 2.6 4 4 0 11-2.6-2.6z" fill-rule="nonzero"/></svg>',
      "print": '<svg width="24" height="24"><path d="M18 8H6a3 3 0 00-3 3v6h2v3h14v-3h2v-6a3 3 0 00-3-3zm-1 10H7v-4h10v4zm.5-5c-.8 0-1.5-.7-1.5-1.5s.7-1.5 1.5-1.5 1.5.7 1.5 1.5-.7 1.5-1.5 1.5zm.5-8H6v2h12V5z" fill-rule="nonzero"/></svg>',
      "quote": '<svg width="24" height="24"><path d="M7.5 17h.9c.4 0 .7-.2.9-.6L11 13V8c0-.6-.4-1-1-1H6a1 1 0 00-1 1v4c0 .6.4 1 1 1h2l-1.3 2.7a1 1 0 00.8 1.3zm8 0h.9c.4 0 .7-.2.9-.6L19 13V8c0-.6-.4-1-1-1h-4a1 1 0 00-1 1v4c0 .6.4 1 1 1h2l-1.3 2.7a1 1 0 00.8 1.3z" fill-rule="nonzero"/></svg>',
      "redo": '<svg width="24" height="24"><path d="M17.6 10H12c-2.8 0-4.4 1.4-4.9 3.5-.4 2 .3 4 1.4 4.6a1 1 0 11-1 1.8c-2-1.2-2.9-4.1-2.3-6.8.6-3 3-5.1 6.8-5.1h5.6l-3.3-3.3a1 1 0 111.4-1.4l5 5a1 1 0 010 1.4l-5 5a1 1 0 01-1.4-1.4l3.3-3.3z" fill-rule="nonzero"/></svg>',
      "reload": '<svg width="24" height="24"><g fill-rule="nonzero"><path d="M5 22.1l-1.2-4.7v-.2a1 1 0 011-1l5 .4a1 1 0 11-.2 2l-2.2-.2a7.8 7.8 0 008.4.2 7.5 7.5 0 003.5-6.4 1 1 0 112 0 9.5 9.5 0 01-4.5 8 9.9 9.9 0 01-10.2 0l.4 1.4a1 1 0 11-2 .5zM13.6 7.4c0-.5.5-1 1-.9l2.8.2a8 8 0 00-9.5-1 7.5 7.5 0 00-3.6 7 1 1 0 01-2 0 9.5 9.5 0 014.5-8.6 10 10 0 0110.9.3l-.3-1a1 1 0 012-.5l1.1 4.8a1 1 0 01-1 1.2l-5-.4a1 1 0 01-.9-1z"/></g></svg>',
      "remove-formatting": '<svg width="24" height="24"><path d="M13.2 6a1 1 0 010 .2l-2.6 10a1 1 0 01-1 .8h-.2a.8.8 0 01-.8-1l2.6-10H8a1 1 0 110-2h9a1 1 0 010 2h-3.8zM5 18h7a1 1 0 010 2H5a1 1 0 010-2zm13 1.5L16.5 18 15 19.5a.7.7 0 01-1-1l1.5-1.5-1.5-1.5a.7.7 0 011-1l1.5 1.5 1.5-1.5a.7.7 0 011 1L17.5 17l1.5 1.5a.7.7 0 01-1 1z" fill-rule="evenodd"/></svg>',
      "remove": '<svg width="24" height="24"><path d="M16 7h3a1 1 0 010 2h-1v9a3 3 0 01-3 3H9a3 3 0 01-3-3V9H5a1 1 0 110-2h3V6a3 3 0 013-3h2a3 3 0 013 3v1zm-2 0V6c0-.6-.4-1-1-1h-2a1 1 0 00-1 1v1h4zm2 2H8v9c0 .6.4 1 1 1h6c.6 0 1-.4 1-1V9zm-7 3a1 1 0 012 0v4a1 1 0 01-2 0v-4zm4 0a1 1 0 012 0v4a1 1 0 01-2 0v-4z" fill-rule="nonzero"/></svg>',
      "resize-handle": '<svg width="10" height="10"><g fill-rule="nonzero"><path d="M8.1 1.1A.5.5 0 119 2l-7 7A.5.5 0 111 8l7-7zM8.1 5.1A.5.5 0 119 6l-3 3A.5.5 0 115 8l3-3z"/></g></svg>',
      "resize": '<svg width="24" height="24"><path d="M4 5c0-.3.1-.5.3-.7.2-.2.4-.3.7-.3h6c.3 0 .5.1.7.3.2.2.3.4.3.7 0 .3-.1.5-.3.7a1 1 0 01-.7.3H7.4L18 16.6V13c0-.3.1-.5.3-.7.2-.2.4-.3.7-.3.3 0 .5.1.7.3.2.2.3.4.3.7v6c0 .3-.1.5-.3.7a1 1 0 01-.7.3h-6a1 1 0 01-.7-.3 1 1 0 01-.3-.7c0-.3.1-.5.3-.7.2-.2.4-.3.7-.3h3.6L6 7.4V11c0 .3-.1.5-.3.7a1 1 0 01-.7.3 1 1 0 01-.7-.3A1 1 0 014 11V5z" fill-rule="evenodd"/></svg>',
      "restore-draft": '<svg width="24" height="24"><g fill-rule="evenodd"><path d="M17 13c0 .6-.4 1-1 1h-4V8c0-.6.4-1 1-1s1 .4 1 1v4h2c.6 0 1 .4 1 1z"/><path d="M4.7 10H9a1 1 0 010 2H3a1 1 0 01-1-1V5a1 1 0 112 0v3l2.5-2.4a9.2 9.2 0 0110.8-1.5A9 9 0 0113.4 21c-2.4.1-4.7-.7-6.5-2.2a1 1 0 111.3-1.5 7.2 7.2 0 0011.6-3.7 7 7 0 00-3.5-7.7A7.2 7.2 0 008 7L4.7 10z" fill-rule="nonzero"/></g></svg>',
      "rotate-left": '<svg width="24" height="24"><path d="M4.7 10H9a1 1 0 010 2H3a1 1 0 01-1-1V5a1 1 0 112 0v3l2.5-2.4a9.2 9.2 0 0110.8-1.5A9 9 0 0113.4 21c-2.4.1-4.7-.7-6.5-2.2a1 1 0 111.3-1.5 7.2 7.2 0 0011.6-3.7 7 7 0 00-3.5-7.7A7.2 7.2 0 008 7L4.7 10z" fill-rule="nonzero"/></svg>',
      "rotate-right": '<svg width="24" height="24"><path d="M20 8V5a1 1 0 012 0v6c0 .6-.4 1-1 1h-6a1 1 0 010-2h4.3L16 7A7.2 7.2 0 007.7 6a7 7 0 003 13.1c1.9.1 3.7-.5 5-1.7a1 1 0 011.4 1.5A9.2 9.2 0 012.2 14c-.9-3.9 1-8 4.5-9.9 3.5-1.9 8-1.3 10.8 1.5L20 8z" fill-rule="nonzero"/></svg>',
      "rtl": '<svg width="24" height="24"><path d="M8 5h8v2h-2v12h-2V7h-2v12H8v-7c-.5 0-1 0-1.4-.3A3.4 3.4 0 014.8 10a3.3 3.3 0 010-2.8 3.4 3.4 0 011.8-1.8L8 5zm12 11.2a1 1 0 11-1 1.6l-3-2a1 1 0 010-1.6l3-2a1 1 0 111 1.6L18.4 15l1.8 1.2z" fill-rule="evenodd"/></svg>',
      "save": '<svg width="24" height="24"><path d="M5 16h14a2 2 0 012 2v2a2 2 0 01-2 2H5a2 2 0 01-2-2v-2c0-1.1.9-2 2-2zm0 2v2h14v-2H5zm10 0h2v2h-2v-2zm-4-6.4L8.7 9.3a1 1 0 10-1.4 1.4l4 4c.4.4 1 .4 1.4 0l4-4a1 1 0 10-1.4-1.4L13 11.6V4a1 1 0 00-2 0v7.6z" fill-rule="nonzero"/></svg>',
      "search": '<svg width="24" height="24"><path d="M16 17.3a8 8 0 111.4-1.4l4.3 4.4a1 1 0 01-1.4 1.4l-4.4-4.3zm-5-.3a6 6 0 100-12 6 6 0 000 12z" fill-rule="nonzero"/></svg>',
      "select-all": '<svg width="24" height="24"><path d="M3 5h2V3a2 2 0 00-2 2zm0 8h2v-2H3v2zm4 8h2v-2H7v2zM3 9h2V7H3v2zm10-6h-2v2h2V3zm6 0v2h2a2 2 0 00-2-2zM5 21v-2H3c0 1.1.9 2 2 2zm-2-4h2v-2H3v2zM9 3H7v2h2V3zm2 18h2v-2h-2v2zm8-8h2v-2h-2v2zm0 8a2 2 0 002-2h-2v2zm0-12h2V7h-2v2zm0 8h2v-2h-2v2zm-4 4h2v-2h-2v2zm0-16h2V3h-2v2zM7 17h10V7H7v10zm2-8h6v6H9V9z" fill-rule="nonzero"/></svg>',
      "selected": '<svg width="24" height="24"><path fill-rule="nonzero" d="M6 4h12a2 2 0 012 2v12a2 2 0 01-2 2H6a2 2 0 01-2-2V6c0-1.1.9-2 2-2zm3.6 10.9L7 12.3a.7.7 0 00-1 1L9.6 17 18 8.6a.7.7 0 000-1 .7.7 0 00-1 0l-7.4 7.3z"/></svg>',
      "settings": '<svg width="24" height="24"><path d="M11 6h8c.6 0 1 .4 1 1s-.4 1-1 1h-8v.3c0 .2 0 .3-.2.5l-.6.2H7.8c-.3 0-.4 0-.6-.2a.7.7 0 01-.2-.6V8H5a1 1 0 110-2h2v-.3c0-.2 0-.3.2-.5l.5-.2h2.5c.3 0 .4 0 .6.2l.2.5V6zM8 8h2V6H8v2zm9 2.8v.2h2c.6 0 1 .4 1 1s-.4 1-1 1h-2v.3c0 .2 0 .3-.2.5l-.6.2h-2.4c-.3 0-.4 0-.6-.2a.7.7 0 01-.2-.6V13H5a1 1 0 010-2h8v-.3c0-.2 0-.3.2-.5l.6-.2h2.4c.3 0 .4 0 .6.2l.2.6zM14 13h2v-2h-2v2zm-3 2.8v.2h8c.6 0 1 .4 1 1s-.4 1-1 1h-8v.3c0 .2 0 .3-.2.5l-.6.2H7.8c-.3 0-.4 0-.6-.2a.7.7 0 01-.2-.6V18H5a1 1 0 010-2h2v-.3c0-.2 0-.3.2-.5l.5-.2h2.5c.3 0 .4 0 .6.2l.2.6zM8 18h2v-2H8v2z" fill-rule="evenodd"/></svg>',
      "sharpen": '<svg width="24" height="24"><path d="M16 6l4 4-8 9-8-9 4-4h8zm-4 10.2l5.5-6.2-.1-.1H12v-.3h5.1l-.2-.2H12V9h4.6l-.2-.2H12v-.3h4.1l-.2-.2H12V8h3.6l-.2-.2H8.7L6.5 10l.1.1H12v.3H6.9l.2.2H12v.3H7.3l.2.2H12v.3H7.7l.3.2h4v.3H8.2l.2.2H12v.3H8.6l.3.2H12v.3H9l.3.2H12v.3H9.5l.2.2H12v.3h-2l.2.2H12v.3h-1.6l.2.2H12v.3h-1.1l.2.2h.9v.3h-.7l.2.2h.5v.3h-.3l.3.2z" fill-rule="evenodd"/></svg>',
      "sourcecode": '<svg width="24" height="24"><g fill-rule="nonzero"><path d="M9.8 15.7c.3.3.3.8 0 1-.3.4-.9.4-1.2 0l-4.4-4.1a.8.8 0 010-1.2l4.4-4.2c.3-.3.9-.3 1.2 0 .3.3.3.8 0 1.1L6 12l3.8 3.7zM14.2 15.7c-.3.3-.3.8 0 1 .4.4.9.4 1.2 0l4.4-4.1c.3-.3.3-.9 0-1.2l-4.4-4.2a.8.8 0 00-1.2 0c-.3.3-.3.8 0 1.1L18 12l-3.8 3.7z"/></g></svg>',
      "spell-check": '<svg width="24" height="24"><path d="M6 8v3H5V5c0-.3.1-.5.3-.7.2-.2.4-.3.7-.3h2c.3 0 .5.1.7.3.2.2.3.4.3.7v6H8V8H6zm0-3v2h2V5H6zm13 0h-3v5h3v1h-3a1 1 0 01-.7-.3 1 1 0 01-.3-.7V5c0-.3.1-.5.3-.7.2-.2.4-.3.7-.3h3v1zm-5 1.5l-.1.7c-.1.2-.3.3-.6.3.3 0 .5.1.6.3l.1.7V10c0 .3-.1.5-.3.7a1 1 0 01-.7.3h-3V4h3c.3 0 .5.1.7.3.2.2.3.4.3.7v1.5zM13 10V8h-2v2h2zm0-3V5h-2v2h2zm3 5l1 1-6.5 7L7 15.5l1.3-1 2.2 2.2L16 12z" fill-rule="evenodd"/></svg>',
      "strike-through": '<svg width="24" height="24"><g fill-rule="evenodd"><path d="M15.6 8.5c-.5-.7-1-1.1-1.3-1.3-.6-.4-1.3-.6-2-.6-2.7 0-2.8 1.7-2.8 2.1 0 1.6 1.8 2 3.2 2.3 4.4.9 4.6 2.8 4.6 3.9 0 1.4-.7 4.1-5 4.1A6.2 6.2 0 017 16.4l1.5-1.1c.4.6 1.6 2 3.7 2 1.6 0 2.5-.4 3-1.2.4-.8.3-2-.8-2.6-.7-.4-1.6-.7-2.9-1-1-.2-3.9-.8-3.9-3.6C7.6 6 10.3 5 12.4 5c2.9 0 4.2 1.6 4.7 2.4l-1.5 1.1z"/><path d="M5 11h14a1 1 0 010 2H5a1 1 0 010-2z" fill-rule="nonzero"/></g></svg>',
      "subscript": '<svg width="24" height="24"><path d="M10.4 10l4.6 4.6-1.4 1.4L9 11.4 4.4 16 3 14.6 7.6 10 3 5.4 4.4 4 9 8.6 13.6 4 15 5.4 10.4 10zM21 19h-5v-1l1-.8 1.7-1.6c.3-.4.5-.8.5-1.2 0-.3 0-.6-.2-.7-.2-.2-.5-.3-.9-.3a2 2 0 00-.8.2l-.7.3-.4-1.1 1-.6 1.2-.2c.8 0 1.4.3 1.8.7.4.4.6.9.6 1.5s-.2 1.1-.5 1.6a8 8 0 01-1.3 1.3l-.6.6h2.6V19z" fill-rule="nonzero"/></svg>',
      "superscript": '<svg width="24" height="24"><path d="M15 9.4L10.4 14l4.6 4.6-1.4 1.4L9 15.4 4.4 20 3 18.6 7.6 14 3 9.4 4.4 8 9 12.6 13.6 8 15 9.4zm5.9 1.6h-5v-1l1-.8 1.7-1.6c.3-.5.5-.9.5-1.3 0-.3 0-.5-.2-.7-.2-.2-.5-.3-.9-.3l-.8.2-.7.4-.4-1.2c.2-.2.5-.4 1-.5.3-.2.8-.2 1.2-.2.8 0 1.4.2 1.8.6.4.4.6 1 .6 1.6 0 .5-.2 1-.5 1.5l-1.3 1.4-.6.5h2.6V11z" fill-rule="nonzero"/></svg>',
      "table-caption": '<svg width="24" height="24"><g fill-rule="nonzero"><rect width="12" height="2" x="3" y="4" rx="1"/><path d="M19 8a2 2 0 012 2v8a2 2 0 01-2 2H5a2 2 0 01-2-2v-8c0-1.1.9-2 2-2h14zM5 15v3h6v-3H5zm14 0h-6v3h6v-3zm0-5h-6v3h6v-3zM5 13h6v-3H5v3z"/></g></svg>',
      "table-cell-classes": '<svg width="24" height="24"><g fill-rule="evenodd"><path fill-rule="nonzero" d="M13 4v9H3V6c0-1.1.9-2 2-2h8zm-2 2H5v5h6V6z"/><path fill-rule="nonzero" d="M13 4h6a2 2 0 012 2v7h-8v-2h6V6h-6V4z" opacity=".2"/><path d="M18 20l-2.6 1.6.7-3-2.4-2 3.1-.2 1.2-2.9 1.2 2.9 3 .2-2.3 2 .7 3z"/><path fill-rule="nonzero" d="M3 13v5c0 1.1.9 2 2 2h8v-7h-2v5H5v-5H3z" opacity=".2"/></g></svg>',
      "table-cell-properties": '<svg width="24" height="24"><path fill-rule="nonzero" d="M19 4a2 2 0 012 2v12a2 2 0 01-2 2H5a2 2 0 01-2-2V6c0-1.1.9-2 2-2h14zm-8 9H5v5h6v-5zm8 0h-6v5h6v-5zm-8-7H5v5h6V6z"/></svg>',
      "table-cell-select-all": '<svg width="24" height="24"><g fill-rule="evenodd"><path fill-rule="nonzero" d="M19 4a2 2 0 012 2v12a2 2 0 01-2 2H5a2 2 0 01-2-2V6c0-1.1.9-2 2-2h14zm0 2H5v12h14V6z"/><path d="M13 6v5h6v2h-6v5h-2v-5H5v-2h6V6h2z" opacity=".2"/></g></svg>',
      "table-cell-select-inner": '<svg width="24" height="24"><g fill-rule="evenodd"><path fill-rule="nonzero" d="M19 4a2 2 0 012 2v12a2 2 0 01-2 2H5a2 2 0 01-2-2V6c0-1.1.9-2 2-2h14zm0 2H5v12h14V6z" opacity=".2"/><path d="M13 6v5h6v2h-6v5h-2v-5H5v-2h6V6h2z"/></g></svg>',
      "table-classes": '<svg width="24" height="24"><g fill-rule="evenodd"><path fill-rule="nonzero" d="M19 4a2 2 0 012 2v7h-8v7H5a2 2 0 01-2-2V6c0-1.1.9-2 2-2h14zm-8 9H5v5h6v-5zm8-7h-6v5h6V6zm-8 0H5v5h6V6z"/><path d="M18 20l-2.6 1.6.7-3-2.4-2 3.1-.2 1.2-2.9 1.2 2.9 3 .2-2.3 2 .7 3z"/></g></svg>',
      "table-delete-column": '<svg width="24" height="24"><path fill-rule="nonzero" d="M19 4a2 2 0 012 2v12a2 2 0 01-2 2H5a2 2 0 01-2-2V6c0-1.1.9-2 2-2h14zm-4 4h-2V6h-2v2H9V6H5v12h4v-2h2v2h2v-2h2v2h4V6h-4v2zm.3.5l1 1.2-3 2.3 3 2.3-1 1.2L12 13l-3.3 2.6-1-1.2 3-2.3-3-2.3 1-1.2L12 11l3.3-2.5z"/></svg>',
      "table-delete-row": '<svg width="24" height="24"><path fill-rule="nonzero" d="M19 4a2 2 0 012 2v12a2 2 0 01-2 2H5a2 2 0 01-2-2V6c0-1.1.9-2 2-2h14zm0 2H5v3h2.5v2H5v2h2.5v2H5v3h14v-3h-2.5v-2H19v-2h-2.5V9H19V6zm-4.7 1.8l1.2 1L13 12l2.6 3.3-1.2 1-2.3-3-2.3 3-1.2-1L11 12 8.5 8.7l1.2-1 2.3 3 2.3-3z"/></svg>',
      "table-delete-table": '<svg width="24" height="24"><g fill-rule="nonzero"><path d="M19 4a2 2 0 012 2v12a2 2 0 01-2 2H5a2 2 0 01-2-2V6c0-1.1.9-2 2-2h14zM5 6v12h14V6H5z"/><path d="M14.4 8.6l1 1-2.3 2.4 2.3 2.4-1 1-2.4-2.3-2.4 2.3-1-1 2.3-2.4-2.3-2.4 1-1 2.4 2.3z"/></g></svg>',
      "table-insert-column-after": '<svg width="24" height="24"><path fill-rule="nonzero" d="M20 4c.6 0 1 .4 1 1v2a1 1 0 01-2 0V6h-8v12h8v-1a1 1 0 012 0v2c0 .5-.4 1-.9 1H5a2 2 0 01-2-2V6c0-1.1.9-2 2-2h15zM9 13H5v5h4v-5zm7-5c.5 0 1 .4 1 .9V11h2a1 1 0 01.1 2H17v2a1 1 0 01-2 .1V13h-2a1 1 0 01-.1-2H15V9c0-.6.4-1 1-1zM9 6H5v5h4V6z"/></svg>',
      "table-insert-column-before": '<svg width="24" height="24"><path fill-rule="nonzero" d="M19 4a2 2 0 012 2v12a2 2 0 01-2 2H4a1 1 0 01-1-1v-2a1 1 0 012 0v1h8V6H5v1a1 1 0 11-2 0V5c0-.6.4-1 1-1h15zm0 9h-4v5h4v-5zM8 8c.5 0 1 .4 1 .9V11h2a1 1 0 01.1 2H9v2a1 1 0 01-2 .1V13H5a1 1 0 01-.1-2H7V9c0-.6.4-1 1-1zm11-2h-4v5h4V6z"/></svg>',
      "table-insert-row-above": '<svg width="24" height="24"><path fill-rule="nonzero" d="M6 4a1 1 0 110 2H5v6h14V6h-1a1 1 0 010-2h2c.6 0 1 .4 1 1v13a2 2 0 01-2 2H5a2 2 0 01-2-2V5c0-.6.4-1 1-1h2zm5 10H5v4h6v-4zm8 0h-6v4h6v-4zM12 3c.5 0 1 .4 1 .9V6h2a1 1 0 010 2h-2v2a1 1 0 01-2 .1V8H9a1 1 0 010-2h2V4c0-.6.4-1 1-1z"/></svg>',
      "table-insert-row-after": '<svg width="24" height="24"><path fill-rule="nonzero" d="M12 13c.5 0 1 .4 1 .9V16h2a1 1 0 01.1 2H13v2a1 1 0 01-2 .1V18H9a1 1 0 01-.1-2H11v-2c0-.6.4-1 1-1zm6 7a1 1 0 010-2h1v-6H5v6h1a1 1 0 010 2H4a1 1 0 01-1-1V6c0-1.1.9-2 2-2h14a2 2 0 012 2v13c0 .5-.4 1-.9 1H18zM11 6H5v4h6V6zm8 0h-6v4h6V6z"/></svg>',
      "table-left-header": '<svg width="24" height="24"><path d="M19 4a2 2 0 012 2v12a2 2 0 01-2 2H5a2 2 0 01-2-2V6c0-1.1.9-2 2-2h14zm0 9h-4v5h4v-5zm-6 0H9v5h4v-5zm0-7H9v5h4V6zm6 0h-4v5h4V6z"/></svg>',
      "table-merge-cells": '<svg width="24" height="24"><path fill-rule="nonzero" d="M19 4a2 2 0 012 2v12a2 2 0 01-2 2H5a2 2 0 01-2-2V6c0-1.1.9-2 2-2h14zM5 15.5V18h3v-2.5H5zm14-5h-9V18h9v-7.5zM19 6h-4v2.5h4V6zM8 6H5v2.5h3V6zm5 0h-3v2.5h3V6zm-8 7.5h3v-3H5v3z"/></svg>',
      "table-row-numbering-rtl": '<svg width="24" height="24"><path d="M6 4a2 2 0 00-2 2v13c0 1.1.9 2 2 2h12a2 2 0 002-2V6a2 2 0 00-2-2H6zm0 12h8v3H6v-3zm11 0c.6 0 1 .4 1 1v1a1 1 0 01-2 0v-1c0-.6.4-1 1-1zM6 11h8v3H6v-3zm11 0c.6 0 1 .4 1 1v1a1 1 0 01-2 0v-1c0-.6.4-1 1-1zM6 6h8v3H6V6zm11 0c.6 0 1 .4 1 1v1a1 1 0 11-2 0V7c0-.6.4-1 1-1z"/></svg>',
      "table-row-numbering": '<svg width="24" height="24"><path d="M18 4a2 2 0 012 2v13a2 2 0 01-2 2H6a2 2 0 01-2-2V6c0-1.1.9-2 2-2h12zm0 12h-8v3h8v-3zM7 16a1 1 0 00-1 1v1a1 1 0 002 0v-1c0-.6-.4-1-1-1zm11-5h-8v3h8v-3zM7 11a1 1 0 00-1 1v1a1 1 0 002 0v-1c0-.6-.4-1-1-1zm11-5h-8v3h8V6zM7 6a1 1 0 00-1 1v1a1 1 0 102 0V7c0-.6-.4-1-1-1z"/></svg>',
      "table-row-properties": '<svg width="24" height="24"><path fill-rule="nonzero" d="M19 4a2 2 0 012 2v12a2 2 0 01-2 2H5a2 2 0 01-2-2V6c0-1.1.9-2 2-2h14zM5 15v3h6v-3H5zm14 0h-6v3h6v-3zm0-9h-6v3h6V6zM5 9h6V6H5v3z"/></svg>',
      "table-split-cells": '<svg width="24" height="24"><path fill-rule="nonzero" d="M19 4a2 2 0 012 2v12a2 2 0 01-2 2H5a2 2 0 01-2-2V6c0-1.1.9-2 2-2h14zM8 15.5H5V18h3v-2.5zm11-5h-9V18h9v-7.5zm-2.5 1l1 1-2 2 2 2-1 1-2-2-2 2-1-1 2-2-2-2 1-1 2 2 2-2zm-8.5-1H5v3h3v-3zM19 6h-4v2.5h4V6zM8 6H5v2.5h3V6zm5 0h-3v2.5h3V6z"/></svg>',
      "table-top-header": '<svg width="24" height="24"><path d="M19 4a2 2 0 012 2v12a2 2 0 01-2 2H5a2 2 0 01-2-2V6c0-1.1.9-2 2-2h14zm-8 11H5v3h6v-3zm8 0h-6v3h6v-3zm0-5h-6v3h6v-3zM5 13h6v-3H5v3z"/></svg>',
      "table": '<svg width="24" height="24"><path fill-rule="nonzero" d="M19 4a2 2 0 012 2v12a2 2 0 01-2 2H5a2 2 0 01-2-2V6c0-1.1.9-2 2-2h14zM5 14v4h6v-4H5zm14 0h-6v4h6v-4zm0-6h-6v4h6V8zM5 12h6V8H5v4z"/></svg>',
      "template": '<svg width="24" height="24"><path d="M19 19v-1H5v1h14zM9 16v-4a5 5 0 116 0v4h4a2 2 0 012 2v3H3v-3c0-1.1.9-2 2-2h4zm4 0v-5l.8-.6a3 3 0 10-3.6 0l.8.6v5h2z" fill-rule="nonzero"/></svg>',
      "temporary-placeholder": '<svg width="24" height="24"><g fill-rule="evenodd"><path d="M9 7.6V6h2.5V4.5a.5.5 0 111 0V6H15v1.6a8 8 0 11-6 0zm-2.6 5.3a.5.5 0 00.3.6c.3 0 .6 0 .6-.3l.1-.2a5 5 0 013.3-2.8c.3-.1.4-.4.4-.6-.1-.3-.4-.5-.6-.4a6 6 0 00-4.1 3.7z"/><circle cx="14" cy="4" r="1"/><circle cx="12" cy="2" r="1"/><circle cx="10" cy="4" r="1"/></g></svg>',
      "text-color": '<svg width="24" height="24"><g fill-rule="evenodd"><path id="tox-icon-text-color__color" d="M3 18h18v3H3z"/><path d="M8.7 16h-.8a.5.5 0 01-.5-.6l2.7-9c.1-.3.3-.4.5-.4h2.8c.2 0 .4.1.5.4l2.7 9a.5.5 0 01-.5.6h-.8a.5.5 0 01-.4-.4l-.7-2.2c0-.3-.3-.4-.5-.4h-3.4c-.2 0-.4.1-.5.4l-.7 2.2c0 .3-.2.4-.4.4zm2.6-7.6l-.6 2a.5.5 0 00.5.6h1.6a.5.5 0 00.5-.6l-.6-2c0-.3-.3-.4-.5-.4h-.4c-.2 0-.4.1-.5.4z"/></g></svg>',
      "toc": '<svg width="24" height="24"><path d="M5 5c.6 0 1 .4 1 1s-.4 1-1 1a1 1 0 110-2zm3 0h11c.6 0 1 .4 1 1s-.4 1-1 1H8a1 1 0 110-2zm-3 8c.6 0 1 .4 1 1s-.4 1-1 1a1 1 0 010-2zm3 0h11c.6 0 1 .4 1 1s-.4 1-1 1H8a1 1 0 010-2zm0-4c.6 0 1 .4 1 1s-.4 1-1 1a1 1 0 110-2zm3 0h8c.6 0 1 .4 1 1s-.4 1-1 1h-8a1 1 0 010-2zm-3 8c.6 0 1 .4 1 1s-.4 1-1 1a1 1 0 010-2zm3 0h8c.6 0 1 .4 1 1s-.4 1-1 1h-8a1 1 0 010-2z" fill-rule="evenodd"/></svg>',
      "translate": '<svg width="24" height="24"><path d="M12.7 14.3l-.3.7-.4.7-2.2-2.2-3.1 3c-.3.4-.8.4-1 0a.7.7 0 010-1l3.1-3A12.4 12.4 0 016.7 9H8a10.1 10.1 0 001.7 2.4c.5-.5 1-1.1 1.4-1.8l.9-2H4.7a.7.7 0 110-1.5h4.4v-.7c0-.4.3-.8.7-.8.4 0 .7.4.7.8v.7H15c.4 0 .8.3.8.7 0 .4-.4.8-.8.8h-1.4a12.3 12.3 0 01-1 2.4 13.5 13.5 0 01-1.7 2.3l1.9 1.8zm4.3-3l2.7 7.3a.5.5 0 01-.4.7 1 1 0 01-1-.7l-.6-1.5h-3.4l-.6 1.5a1 1 0 01-1 .7.5.5 0 01-.4-.7l2.7-7.4a1 1 0 012 0zm-2.2 4.4h2.4L16 12.5l-1.2 3.2z" fill-rule="evenodd"/></svg>',
      "underline": '<svg width="24" height="24"><path d="M16 5c.6 0 1 .4 1 1v5.5a4 4 0 01-.4 1.8l-1 1.4a5.3 5.3 0 01-5.5 1 5 5 0 01-1.6-1c-.5-.4-.8-.9-1.1-1.4a4 4 0 01-.4-1.8V6c0-.6.4-1 1-1s1 .4 1 1v5.5c0 .3 0 .6.2 1l.6.7a3.3 3.3 0 002.2.8 3.4 3.4 0 002.2-.8c.3-.2.4-.5.6-.8l.2-.9V6c0-.6.4-1 1-1zM8 17h8c.6 0 1 .4 1 1s-.4 1-1 1H8a1 1 0 010-2z" fill-rule="evenodd"/></svg>',
      "undo": '<svg width="24" height="24"><path d="M6.4 8H12c3.7 0 6.2 2 6.8 5.1.6 2.7-.4 5.6-2.3 6.8a1 1 0 01-1-1.8c1.1-.6 1.8-2.7 1.4-4.6-.5-2.1-2.1-3.5-4.9-3.5H6.4l3.3 3.3a1 1 0 11-1.4 1.4l-5-5a1 1 0 010-1.4l5-5a1 1 0 011.4 1.4L6.4 8z" fill-rule="nonzero"/></svg>',
      "unlink": '<svg width="24" height="24"><path d="M6.2 12.3a1 1 0 011.4 1.4l-2 2a2 2 0 102.6 2.8l4.8-4.8a1 1 0 000-1.4 1 1 0 111.4-1.3 2.9 2.9 0 010 4L9.6 20a3.9 3.9 0 01-5.5-5.5l2-2zm11.6-.6a1 1 0 01-1.4-1.4l2.1-2a2 2 0 10-2.7-2.8L11 10.3a1 1 0 000 1.4A1 1 0 119.6 13a2.9 2.9 0 010-4L14.4 4a3.9 3.9 0 015.5 5.5l-2 2zM7.6 6.3a.8.8 0 01-1 1.1L3.3 4.2a.7.7 0 111-1l3.2 3.1zM5.1 8.6a.8.8 0 010 1.5H3a.8.8 0 010-1.5H5zm5-3.5a.8.8 0 01-1.5 0V3a.8.8 0 011.5 0V5zm6 11.8a.8.8 0 011-1l3.2 3.2a.8.8 0 01-1 1L16 17zm-2.2 2a.8.8 0 011.5 0V21a.8.8 0 01-1.5 0V19zm5-3.5a.7.7 0 110-1.5H21a.8.8 0 010 1.5H19z" fill-rule="nonzero"/></svg>',
      "unlock": '<svg width="24" height="24"><path d="M16 5c.8 0 1.5.3 2.1.9.6.6.9 1.3.9 2.1v3h-2V8a1 1 0 00-.3-.7A1 1 0 0016 7h-2a1 1 0 00-.7.3 1 1 0 00-.3.7v3h.3c.2 0 .3 0 .5.2l.2.6v7.4c0 .3 0 .4-.2.6l-.6.2H4.8c-.3 0-.4 0-.6-.2a.7.7 0 01-.2-.6v-7.4c0-.3 0-.4.2-.6l.5-.2H11V8c0-.8.3-1.5.9-2.1.6-.6 1.3-.9 2.1-.9h2z" fill-rule="evenodd"/></svg>',
      "unordered-list": '<svg width="24" height="24"><path d="M11 5h8c.6 0 1 .4 1 1s-.4 1-1 1h-8a1 1 0 010-2zm0 6h8c.6 0 1 .4 1 1s-.4 1-1 1h-8a1 1 0 010-2zm0 6h8c.6 0 1 .4 1 1s-.4 1-1 1h-8a1 1 0 010-2zM4.5 6c0-.4.1-.8.4-1 .3-.4.7-.5 1.1-.5.4 0 .8.1 1 .4.4.3.5.7.5 1.1 0 .4-.1.8-.4 1-.3.4-.7.5-1.1.5-.4 0-.8-.1-1-.4-.4-.3-.5-.7-.5-1.1zm0 6c0-.4.1-.8.4-1 .3-.4.7-.5 1.1-.5.4 0 .8.1 1 .4.4.3.5.7.5 1.1 0 .4-.1.8-.4 1-.3.4-.7.5-1.1.5-.4 0-.8-.1-1-.4-.4-.3-.5-.7-.5-1.1zm0 6c0-.4.1-.8.4-1 .3-.4.7-.5 1.1-.5.4 0 .8.1 1 .4.4.3.5.7.5 1.1 0 .4-.1.8-.4 1-.3.4-.7.5-1.1.5-.4 0-.8-.1-1-.4-.4-.3-.5-.7-.5-1.1z" fill-rule="evenodd"/></svg>',
      "unselected": '<svg width="24" height="24"><path fill-rule="nonzero" d="M6 4h12a2 2 0 012 2v12a2 2 0 01-2 2H6a2 2 0 01-2-2V6c0-1.1.9-2 2-2zm0 1a1 1 0 00-1 1v12c0 .6.4 1 1 1h12c.6 0 1-.4 1-1V6c0-.6-.4-1-1-1H6z"/></svg>',
      "upload": '<svg width="24" height="24"><path d="M18 19v-2a1 1 0 012 0v3c0 .6-.4 1-1 1H5a1 1 0 01-1-1v-3a1 1 0 012 0v2h12zM11 6.4L8.7 8.7a1 1 0 01-1.4-1.4l4-4a1 1 0 011.4 0l4 4a1 1 0 11-1.4 1.4L13 6.4V16a1 1 0 01-2 0V6.4z" fill-rule="nonzero"/></svg>',
      "user": '<svg width="24" height="24"><path d="M12 24a12 12 0 110-24 12 12 0 010 24zm-8.7-5.3a11 11 0 0017.4 0C19.4 16.3 14.6 15 12 15c-2.6 0-7.4 1.3-8.7 3.7zM12 13c2.2 0 4-2 4-4.5S14.2 4 12 4 8 6 8 8.5 9.8 13 12 13z" fill-rule="nonzero"/></svg>',
      "vertical-align": '<svg width="24" height="24"><g fill-rule="nonzero"><rect width="18" height="2" x="3" y="11" rx="1"/><path d="M12 2c.6 0 1 .4 1 1v4l2-1.3a1 1 0 011.2 1.5l-.1.1-4.1 3-4-3a1 1 0 011-1.7l2 1.5V3c0-.6.4-1 1-1zm0 11.8l4 2.9a1 1 0 01-1 1.7l-2-1.5V21c0 .5-.4 1-.9 1H12a1 1 0 01-1-1v-4l-2 1.3a1 1 0 01-1.2-.1l-.1-.1a1 1 0 01.1-1.3l.1-.1 4.1-3z"/></g></svg>',
      "visualblocks": '<svg width="24" height="24"><path d="M9 19v2H7v-2h2zm-4 0v2a2 2 0 01-2-2h2zm8 0v2h-2v-2h2zm8 0a2 2 0 01-2 2v-2h2zm-4 0v2h-2v-2h2zM15 7a1 1 0 010 2v7a1 1 0 01-2 0V9h-1v7a1 1 0 01-2 0v-4a2.5 2.5 0 01-.2-5H15zM5 15v2H3v-2h2zm16 0v2h-2v-2h2zM5 11v2H3v-2h2zm16 0v2h-2v-2h2zM5 7v2H3V7h2zm16 0v2h-2V7h2zM5 3v2H3c0-1.1.9-2 2-2zm8 0v2h-2V3h2zm6 0a2 2 0 012 2h-2V3zM9 3v2H7V3h2zm8 0v2h-2V3h2z" fill-rule="evenodd"/></svg>',
      "visualchars": '<svg width="24" height="24"><path d="M10 5h7a1 1 0 010 2h-1v11a1 1 0 01-2 0V7h-2v11a1 1 0 01-2 0v-6c-.5 0-1 0-1.4-.3A3.4 3.4 0 016.8 10a3.3 3.3 0 010-2.8 3.4 3.4 0 011.8-1.8L10 5z" fill-rule="evenodd"/></svg>',
      "warning": '<svg width="24" height="24"><path d="M19.8 18.3c.2.5.3.9 0 1.2-.1.3-.5.5-1 .5H5.2c-.5 0-.9-.2-1-.5-.3-.3-.2-.7 0-1.2L11 4.7l.5-.5.5-.2c.2 0 .3 0 .5.2.2 0 .3.3.5.5l6.8 13.6zM12 18c.3 0 .5-.1.7-.3.2-.2.3-.4.3-.7a1 1 0 00-.3-.7 1 1 0 00-.7-.3 1 1 0 00-.7.3 1 1 0 00-.3.7c0 .3.1.5.3.7.2.2.4.3.7.3zm.7-3l.3-4a1 1 0 00-.3-.7 1 1 0 00-.7-.3 1 1 0 00-.7.3 1 1 0 00-.3.7l.3 4h1.4z" fill-rule="evenodd"/></svg>',
      "zoom-in": '<svg width="24" height="24"><path d="M16 17.3a8 8 0 111.4-1.4l4.3 4.4a1 1 0 01-1.4 1.4l-4.4-4.3zm-5-.3a6 6 0 100-12 6 6 0 000 12zm-1-9a1 1 0 012 0v6a1 1 0 01-2 0V8zm-2 4a1 1 0 010-2h6a1 1 0 010 2H8z" fill-rule="nonzero"/></svg>',
      "zoom-out": '<svg width="24" height="24"><path d="M16 17.3a8 8 0 111.4-1.4l4.3 4.4a1 1 0 01-1.4 1.4l-4.4-4.3zm-5-.3a6 6 0 100-12 6 6 0 000 12zm-3-5a1 1 0 010-2h6a1 1 0 010 2H8z" fill-rule="nonzero"/></svg>'
    }
  });

  // ../../node_modules/tinymce/plugins/print/index.js
  require_plugin();

  // ../../node_modules/tinymce/plugins/preview/index.js
  require_plugin2();

  // ../../node_modules/tinymce/plugins/paste/index.js
  require_plugin3();

  // ../../node_modules/tinymce/plugins/importcss/index.js
  require_plugin4();

  // ../../node_modules/tinymce/plugins/autolink/index.js
  require_plugin5();

  // ../../node_modules/tinymce/plugins/autosave/index.js
  require_plugin6();

  // ../../node_modules/tinymce/plugins/save/index.js
  require_plugin7();

  // ../../node_modules/tinymce/plugins/directionality/index.js
  require_plugin8();

  // ../../node_modules/tinymce/plugins/code/index.js
  require_plugin9();

  // ../../node_modules/tinymce/plugins/visualblocks/index.js
  require_plugin10();

  // ../../node_modules/tinymce/plugins/visualchars/index.js
  require_plugin11();

  // ../../node_modules/tinymce/plugins/fullscreen/index.js
  require_plugin12();

  // ../../node_modules/tinymce/plugins/image/index.js
  require_plugin13();

  // ../../node_modules/tinymce/plugins/link/index.js
  require_plugin14();

  // ../../node_modules/tinymce/plugins/media/index.js
  require_plugin15();

  // ../../node_modules/tinymce/plugins/table/index.js
  require_plugin16();

  // ../../node_modules/tinymce/plugins/charmap/index.js
  require_plugin17();

  // ../../node_modules/tinymce/plugins/hr/index.js
  require_plugin18();

  // ../../node_modules/tinymce/plugins/pagebreak/index.js
  require_plugin19();

  // ../../node_modules/tinymce/plugins/nonbreaking/index.js
  require_plugin20();

  // ../../node_modules/tinymce/plugins/anchor/index.js
  require_plugin21();

  // ../../node_modules/tinymce/plugins/advlist/index.js
  require_plugin22();

  // ../../node_modules/tinymce/plugins/lists/index.js
  require_plugin23();

  // ../../node_modules/tinymce/plugins/textpattern/index.js
  require_plugin24();

  // ../../node_modules/tinymce/plugins/noneditable/index.js
  require_plugin25();

  // ../../node_modules/tinymce/plugins/help/index.js
  require_plugin26();

  // ../../node_modules/tinymce/plugins/quickbars/index.js
  require_plugin27();

  // controllers/tinymce_controller.js
  var tinymce_controller_default = class extends Controller {
    initialize() {
      this.defaults = {
        relative_urls: false,
        skin: false,
        content_css: false,
        plugins: "print preview paste importcss autolink autosave save directionality code visualblocks visualchars fullscreen image link media table charmap hr pagebreak nonbreaking anchor advlist lists textpattern noneditable help charmap quickbars",
        menubar: "file edit view insert format tools table",
        toolbar: "undo redo | bold italic underline strikethrough | fontselect fontsizeselect formatselect | alignleft aligncenter alignright alignjustify | outdent indent |  numlist bullist preview | forecolor backcolor removeformat | pagebreak | charmap | insertfile image media link anchor | ltr rtl fullscreen",
        toolbar_sticky: true,
        suffix: ".min"
      };
    }
    connect() {
      let config = Object.assign({ target: this.inputTarget }, this.defaults);
      import_tinymce.default.init(config);
    }
    disconnect() {
      import_tinymce.default.remove();
    }
  };
  __publicField(tinymce_controller_default, "targets", ["input"]);

  // controllers/turbo_controller.js
  var turbo_controller_exports = {};
  __export(turbo_controller_exports, {
    default: () => turbo_controller_default
  });
  var turbo_controller_default = class extends Controller {
    initialize() {
      this.element.setAttribute("data-action", "click->turbo#click");
    }
    click(e2) {
      e2.preventDefault();
      this.url = this.element.getAttribute("href");
      fetch(this.url, {
        headers: {
          Accept: "text/vnd.turbo-stream.html"
        }
      }).then((r2) => r2.text()).then((html) => turbo_es2017_esm_exports.renderStreamMessage(html));
    }
  };

  // rails:/var/www/thefarm/production/releases/20241022180807/app/javascript/controllers/**/*_controller.js
  var modules = [{ name: "additional-employees", module: additional_employees_controller_exports, filename: "./additional_employees_controller.js" }, { name: "additional-insureds", module: additional_insureds_controller_exports, filename: "./additional_insureds_controller.js" }, { name: "application-detail-options", module: application_detail_options_controller_exports, filename: "./application_detail_options_controller.js" }, { name: "application-details", module: application_details_controller_exports, filename: "./application_details_controller.js" }, { name: "application-steps", module: application_steps_controller_exports, filename: "./application_steps_controller.js" }, { name: "doc-type-fields", module: doc_type_fields_controller_exports, filename: "./doc_type_fields_controller.js" }, { name: "documents", module: documents_controller_exports, filename: "./documents_controller.js" }, { name: "endorsements", module: endorsements_controller_exports, filename: "./endorsements_controller.js" }, { name: "fmodal", module: fmodal_controller_exports, filename: "./fmodal_controller.js" }, { name: "membership-application", module: membership_application_controller_exports, filename: "./membership_application_controller.js" }, { name: "modal", module: modal_controller_exports, filename: "./modal_controller.js" }, { name: "notes", module: notes_controller_exports, filename: "./notes_controller.js" }, { name: "password", module: password_controller_exports, filename: "./password_controller.js" }, { name: "policy", module: policy_controller_exports, filename: "./policy_controller.js" }, { name: "refresh", module: refresh_controller_exports, filename: "./refresh_controller.js" }, { name: "tables", module: tables_controller_exports, filename: "./tables_controller.js" }, { name: "tinymce", module: tinymce_controller_exports, filename: "./tinymce_controller.js" }, { name: "turbo", module: turbo_controller_exports, filename: "./turbo_controller.js" }];
  var controller_default = modules;

  // controllers/index.js
  var import_js = __toESM(require_honeybadger());
  controller_default.forEach((controller) => {
    application.register(controller.name, controller.module.default);
  });
  import_js.default.configure({
    apiKey: "hbp_ueBmJ37QpuL8Q5oeZQ5f84nmmuwjUx13wtyS",
    environment: document.head.querySelector("meta[name=rails_env]").content
  });
  application.handleError = (error3, message, detail) => {
    console.warn(message, detail);
    import_js.default.notify(error3);
  };

  // ../../node_modules/bootstrap/dist/js/bootstrap.esm.js
  var bootstrap_esm_exports = {};
  __export(bootstrap_esm_exports, {
    Alert: () => Alert,
    Button: () => Button,
    Carousel: () => Carousel,
    Collapse: () => Collapse,
    Dropdown: () => Dropdown,
    Modal: () => Modal,
    Offcanvas: () => Offcanvas,
    Popover: () => Popover,
    ScrollSpy: () => ScrollSpy,
    Tab: () => Tab,
    Toast: () => Toast,
    Tooltip: () => Tooltip
  });
  var MAX_UID = 1e6;
  var MILLISECONDS_MULTIPLIER = 1e3;
  var TRANSITION_END = "transitionend";
  var toType = (obj) => {
    if (obj === null || obj === void 0) {
      return `${obj}`;
    }
    return {}.toString.call(obj).match(/\s([a-z]+)/i)[1].toLowerCase();
  };
  var getUID = (prefix) => {
    do {
      prefix += Math.floor(Math.random() * MAX_UID);
    } while (document.getElementById(prefix));
    return prefix;
  };
  var getSelector = (element) => {
    let selector = element.getAttribute("data-bs-target");
    if (!selector || selector === "#") {
      let hrefAttr = element.getAttribute("href");
      if (!hrefAttr || !hrefAttr.includes("#") && !hrefAttr.startsWith(".")) {
        return null;
      }
      if (hrefAttr.includes("#") && !hrefAttr.startsWith("#")) {
        hrefAttr = `#${hrefAttr.split("#")[1]}`;
      }
      selector = hrefAttr && hrefAttr !== "#" ? hrefAttr.trim() : null;
    }
    return selector;
  };
  var getSelectorFromElement = (element) => {
    const selector = getSelector(element);
    if (selector) {
      return document.querySelector(selector) ? selector : null;
    }
    return null;
  };
  var getElementFromSelector = (element) => {
    const selector = getSelector(element);
    return selector ? document.querySelector(selector) : null;
  };
  var getTransitionDurationFromElement = (element) => {
    if (!element) {
      return 0;
    }
    let {
      transitionDuration,
      transitionDelay
    } = window.getComputedStyle(element);
    const floatTransitionDuration = Number.parseFloat(transitionDuration);
    const floatTransitionDelay = Number.parseFloat(transitionDelay);
    if (!floatTransitionDuration && !floatTransitionDelay) {
      return 0;
    }
    transitionDuration = transitionDuration.split(",")[0];
    transitionDelay = transitionDelay.split(",")[0];
    return (Number.parseFloat(transitionDuration) + Number.parseFloat(transitionDelay)) * MILLISECONDS_MULTIPLIER;
  };
  var triggerTransitionEnd = (element) => {
    element.dispatchEvent(new Event(TRANSITION_END));
  };
  var isElement2 = (obj) => {
    if (!obj || typeof obj !== "object") {
      return false;
    }
    if (typeof obj.jquery !== "undefined") {
      obj = obj[0];
    }
    return typeof obj.nodeType !== "undefined";
  };
  var getElement = (obj) => {
    if (isElement2(obj)) {
      return obj.jquery ? obj[0] : obj;
    }
    if (typeof obj === "string" && obj.length > 0) {
      return document.querySelector(obj);
    }
    return null;
  };
  var typeCheckConfig = (componentName, config, configTypes) => {
    Object.keys(configTypes).forEach((property) => {
      const expectedTypes = configTypes[property];
      const value = config[property];
      const valueType = value && isElement2(value) ? "element" : toType(value);
      if (!new RegExp(expectedTypes).test(valueType)) {
        throw new TypeError(`${componentName.toUpperCase()}: Option "${property}" provided type "${valueType}" but expected type "${expectedTypes}".`);
      }
    });
  };
  var isVisible = (element) => {
    if (!isElement2(element) || element.getClientRects().length === 0) {
      return false;
    }
    return getComputedStyle(element).getPropertyValue("visibility") === "visible";
  };
  var isDisabled = (element) => {
    if (!element || element.nodeType !== Node.ELEMENT_NODE) {
      return true;
    }
    if (element.classList.contains("disabled")) {
      return true;
    }
    if (typeof element.disabled !== "undefined") {
      return element.disabled;
    }
    return element.hasAttribute("disabled") && element.getAttribute("disabled") !== "false";
  };
  var findShadowRoot = (element) => {
    if (!document.documentElement.attachShadow) {
      return null;
    }
    if (typeof element.getRootNode === "function") {
      const root = element.getRootNode();
      return root instanceof ShadowRoot ? root : null;
    }
    if (element instanceof ShadowRoot) {
      return element;
    }
    if (!element.parentNode) {
      return null;
    }
    return findShadowRoot(element.parentNode);
  };
  var noop = () => {
  };
  var reflow = (element) => {
    element.offsetHeight;
  };
  var getjQuery = () => {
    const {
      jQuery: jQuery2
    } = window;
    if (jQuery2 && !document.body.hasAttribute("data-bs-no-jquery")) {
      return jQuery2;
    }
    return null;
  };
  var DOMContentLoadedCallbacks = [];
  var onDOMContentLoaded = (callback2) => {
    if (document.readyState === "loading") {
      if (!DOMContentLoadedCallbacks.length) {
        document.addEventListener("DOMContentLoaded", () => {
          DOMContentLoadedCallbacks.forEach((callback3) => callback3());
        });
      }
      DOMContentLoadedCallbacks.push(callback2);
    } else {
      callback2();
    }
  };
  var isRTL = () => document.documentElement.dir === "rtl";
  var defineJQueryPlugin = (plugin) => {
    onDOMContentLoaded(() => {
      const $2 = getjQuery();
      if ($2) {
        const name = plugin.NAME;
        const JQUERY_NO_CONFLICT = $2.fn[name];
        $2.fn[name] = plugin.jQueryInterface;
        $2.fn[name].Constructor = plugin;
        $2.fn[name].noConflict = () => {
          $2.fn[name] = JQUERY_NO_CONFLICT;
          return plugin.jQueryInterface;
        };
      }
    });
  };
  var execute = (callback2) => {
    if (typeof callback2 === "function") {
      callback2();
    }
  };
  var executeAfterTransition = (callback2, transitionElement, waitForTransition = true) => {
    if (!waitForTransition) {
      execute(callback2);
      return;
    }
    const durationPadding = 5;
    const emulatedDuration = getTransitionDurationFromElement(transitionElement) + durationPadding;
    let called = false;
    const handler = ({
      target
    }) => {
      if (target !== transitionElement) {
        return;
      }
      called = true;
      transitionElement.removeEventListener(TRANSITION_END, handler);
      execute(callback2);
    };
    transitionElement.addEventListener(TRANSITION_END, handler);
    setTimeout(() => {
      if (!called) {
        triggerTransitionEnd(transitionElement);
      }
    }, emulatedDuration);
  };
  var getNextActiveElement = (list, activeElement, shouldGetNext, isCycleAllowed) => {
    let index = list.indexOf(activeElement);
    if (index === -1) {
      return list[!shouldGetNext && isCycleAllowed ? list.length - 1 : 0];
    }
    const listLength = list.length;
    index += shouldGetNext ? 1 : -1;
    if (isCycleAllowed) {
      index = (index + listLength) % listLength;
    }
    return list[Math.max(0, Math.min(index, listLength - 1))];
  };
  var namespaceRegex = /[^.]*(?=\..*)\.|.*/;
  var stripNameRegex = /\..*/;
  var stripUidRegex = /::\d+$/;
  var eventRegistry = {};
  var uidEvent = 1;
  var customEvents = {
    mouseenter: "mouseover",
    mouseleave: "mouseout"
  };
  var customEventsRegex = /^(mouseenter|mouseleave)/i;
  var nativeEvents = /* @__PURE__ */ new Set(["click", "dblclick", "mouseup", "mousedown", "contextmenu", "mousewheel", "DOMMouseScroll", "mouseover", "mouseout", "mousemove", "selectstart", "selectend", "keydown", "keypress", "keyup", "orientationchange", "touchstart", "touchmove", "touchend", "touchcancel", "pointerdown", "pointermove", "pointerup", "pointerleave", "pointercancel", "gesturestart", "gesturechange", "gestureend", "focus", "blur", "change", "reset", "select", "submit", "focusin", "focusout", "load", "unload", "beforeunload", "resize", "move", "DOMContentLoaded", "readystatechange", "error", "abort", "scroll"]);
  function getUidEvent(element, uid2) {
    return uid2 && `${uid2}::${uidEvent++}` || element.uidEvent || uidEvent++;
  }
  function getEvent(element) {
    const uid2 = getUidEvent(element);
    element.uidEvent = uid2;
    eventRegistry[uid2] = eventRegistry[uid2] || {};
    return eventRegistry[uid2];
  }
  function bootstrapHandler(element, fn3) {
    return function handler(event) {
      event.delegateTarget = element;
      if (handler.oneOff) {
        EventHandler.off(element, event.type, fn3);
      }
      return fn3.apply(element, [event]);
    };
  }
  function bootstrapDelegationHandler(element, selector, fn3) {
    return function handler(event) {
      const domElements = element.querySelectorAll(selector);
      for (let {
        target
      } = event; target && target !== this; target = target.parentNode) {
        for (let i2 = domElements.length; i2--; ) {
          if (domElements[i2] === target) {
            event.delegateTarget = target;
            if (handler.oneOff) {
              EventHandler.off(element, event.type, selector, fn3);
            }
            return fn3.apply(target, [event]);
          }
        }
      }
      return null;
    };
  }
  function findHandler(events, handler, delegationSelector = null) {
    const uidEventList = Object.keys(events);
    for (let i2 = 0, len = uidEventList.length; i2 < len; i2++) {
      const event = events[uidEventList[i2]];
      if (event.originalHandler === handler && event.delegationSelector === delegationSelector) {
        return event;
      }
    }
    return null;
  }
  function normalizeParams(originalTypeEvent, handler, delegationFn) {
    const delegation = typeof handler === "string";
    const originalHandler = delegation ? delegationFn : handler;
    let typeEvent = getTypeEvent(originalTypeEvent);
    const isNative = nativeEvents.has(typeEvent);
    if (!isNative) {
      typeEvent = originalTypeEvent;
    }
    return [delegation, originalHandler, typeEvent];
  }
  function addHandler(element, originalTypeEvent, handler, delegationFn, oneOff) {
    if (typeof originalTypeEvent !== "string" || !element) {
      return;
    }
    if (!handler) {
      handler = delegationFn;
      delegationFn = null;
    }
    if (customEventsRegex.test(originalTypeEvent)) {
      const wrapFn = (fn4) => {
        return function(event) {
          if (!event.relatedTarget || event.relatedTarget !== event.delegateTarget && !event.delegateTarget.contains(event.relatedTarget)) {
            return fn4.call(this, event);
          }
        };
      };
      if (delegationFn) {
        delegationFn = wrapFn(delegationFn);
      } else {
        handler = wrapFn(handler);
      }
    }
    const [delegation, originalHandler, typeEvent] = normalizeParams(originalTypeEvent, handler, delegationFn);
    const events = getEvent(element);
    const handlers = events[typeEvent] || (events[typeEvent] = {});
    const previousFn = findHandler(handlers, originalHandler, delegation ? handler : null);
    if (previousFn) {
      previousFn.oneOff = previousFn.oneOff && oneOff;
      return;
    }
    const uid2 = getUidEvent(originalHandler, originalTypeEvent.replace(namespaceRegex, ""));
    const fn3 = delegation ? bootstrapDelegationHandler(element, handler, delegationFn) : bootstrapHandler(element, handler);
    fn3.delegationSelector = delegation ? handler : null;
    fn3.originalHandler = originalHandler;
    fn3.oneOff = oneOff;
    fn3.uidEvent = uid2;
    handlers[uid2] = fn3;
    element.addEventListener(typeEvent, fn3, delegation);
  }
  function removeHandler(element, events, typeEvent, handler, delegationSelector) {
    const fn3 = findHandler(events[typeEvent], handler, delegationSelector);
    if (!fn3) {
      return;
    }
    element.removeEventListener(typeEvent, fn3, Boolean(delegationSelector));
    delete events[typeEvent][fn3.uidEvent];
  }
  function removeNamespacedHandlers(element, events, typeEvent, namespace) {
    const storeElementEvent = events[typeEvent] || {};
    Object.keys(storeElementEvent).forEach((handlerKey) => {
      if (handlerKey.includes(namespace)) {
        const event = storeElementEvent[handlerKey];
        removeHandler(element, events, typeEvent, event.originalHandler, event.delegationSelector);
      }
    });
  }
  function getTypeEvent(event) {
    event = event.replace(stripNameRegex, "");
    return customEvents[event] || event;
  }
  var EventHandler = {
    on(element, event, handler, delegationFn) {
      addHandler(element, event, handler, delegationFn, false);
    },
    one(element, event, handler, delegationFn) {
      addHandler(element, event, handler, delegationFn, true);
    },
    off(element, originalTypeEvent, handler, delegationFn) {
      if (typeof originalTypeEvent !== "string" || !element) {
        return;
      }
      const [delegation, originalHandler, typeEvent] = normalizeParams(originalTypeEvent, handler, delegationFn);
      const inNamespace = typeEvent !== originalTypeEvent;
      const events = getEvent(element);
      const isNamespace = originalTypeEvent.startsWith(".");
      if (typeof originalHandler !== "undefined") {
        if (!events || !events[typeEvent]) {
          return;
        }
        removeHandler(element, events, typeEvent, originalHandler, delegation ? handler : null);
        return;
      }
      if (isNamespace) {
        Object.keys(events).forEach((elementEvent) => {
          removeNamespacedHandlers(element, events, elementEvent, originalTypeEvent.slice(1));
        });
      }
      const storeElementEvent = events[typeEvent] || {};
      Object.keys(storeElementEvent).forEach((keyHandlers) => {
        const handlerKey = keyHandlers.replace(stripUidRegex, "");
        if (!inNamespace || originalTypeEvent.includes(handlerKey)) {
          const event = storeElementEvent[keyHandlers];
          removeHandler(element, events, typeEvent, event.originalHandler, event.delegationSelector);
        }
      });
    },
    trigger(element, event, args) {
      if (typeof event !== "string" || !element) {
        return null;
      }
      const $2 = getjQuery();
      const typeEvent = getTypeEvent(event);
      const inNamespace = event !== typeEvent;
      const isNative = nativeEvents.has(typeEvent);
      let jQueryEvent;
      let bubbles = true;
      let nativeDispatch = true;
      let defaultPrevented = false;
      let evt = null;
      if (inNamespace && $2) {
        jQueryEvent = $2.Event(event, args);
        $2(element).trigger(jQueryEvent);
        bubbles = !jQueryEvent.isPropagationStopped();
        nativeDispatch = !jQueryEvent.isImmediatePropagationStopped();
        defaultPrevented = jQueryEvent.isDefaultPrevented();
      }
      if (isNative) {
        evt = document.createEvent("HTMLEvents");
        evt.initEvent(typeEvent, bubbles, true);
      } else {
        evt = new CustomEvent(event, {
          bubbles,
          cancelable: true
        });
      }
      if (typeof args !== "undefined") {
        Object.keys(args).forEach((key) => {
          Object.defineProperty(evt, key, {
            get() {
              return args[key];
            }
          });
        });
      }
      if (defaultPrevented) {
        evt.preventDefault();
      }
      if (nativeDispatch) {
        element.dispatchEvent(evt);
      }
      if (evt.defaultPrevented && typeof jQueryEvent !== "undefined") {
        jQueryEvent.preventDefault();
      }
      return evt;
    }
  };
  var elementMap = /* @__PURE__ */ new Map();
  var Data = {
    set(element, key, instance) {
      if (!elementMap.has(element)) {
        elementMap.set(element, /* @__PURE__ */ new Map());
      }
      const instanceMap = elementMap.get(element);
      if (!instanceMap.has(key) && instanceMap.size !== 0) {
        console.error(`Bootstrap doesn't allow more than one instance per element. Bound instance: ${Array.from(instanceMap.keys())[0]}.`);
        return;
      }
      instanceMap.set(key, instance);
    },
    get(element, key) {
      if (elementMap.has(element)) {
        return elementMap.get(element).get(key) || null;
      }
      return null;
    },
    remove(element, key) {
      if (!elementMap.has(element)) {
        return;
      }
      const instanceMap = elementMap.get(element);
      instanceMap.delete(key);
      if (instanceMap.size === 0) {
        elementMap.delete(element);
      }
    }
  };
  var VERSION = "5.1.3";
  var BaseComponent = class {
    constructor(element) {
      element = getElement(element);
      if (!element) {
        return;
      }
      this._element = element;
      Data.set(this._element, this.constructor.DATA_KEY, this);
    }
    dispose() {
      Data.remove(this._element, this.constructor.DATA_KEY);
      EventHandler.off(this._element, this.constructor.EVENT_KEY);
      Object.getOwnPropertyNames(this).forEach((propertyName) => {
        this[propertyName] = null;
      });
    }
    _queueCallback(callback2, element, isAnimated = true) {
      executeAfterTransition(callback2, element, isAnimated);
    }
    static getInstance(element) {
      return Data.get(getElement(element), this.DATA_KEY);
    }
    static getOrCreateInstance(element, config = {}) {
      return this.getInstance(element) || new this(element, typeof config === "object" ? config : null);
    }
    static get VERSION() {
      return VERSION;
    }
    static get NAME() {
      throw new Error('You have to implement the static method "NAME", for each component!');
    }
    static get DATA_KEY() {
      return `bs.${this.NAME}`;
    }
    static get EVENT_KEY() {
      return `.${this.DATA_KEY}`;
    }
  };
  var enableDismissTrigger = (component, method = "hide") => {
    const clickEvent = `click.dismiss${component.EVENT_KEY}`;
    const name = component.NAME;
    EventHandler.on(document, clickEvent, `[data-bs-dismiss="${name}"]`, function(event) {
      if (["A", "AREA"].includes(this.tagName)) {
        event.preventDefault();
      }
      if (isDisabled(this)) {
        return;
      }
      const target = getElementFromSelector(this) || this.closest(`.${name}`);
      const instance = component.getOrCreateInstance(target);
      instance[method]();
    });
  };
  var NAME$d = "alert";
  var DATA_KEY$c = "bs.alert";
  var EVENT_KEY$c = `.${DATA_KEY$c}`;
  var EVENT_CLOSE = `close${EVENT_KEY$c}`;
  var EVENT_CLOSED = `closed${EVENT_KEY$c}`;
  var CLASS_NAME_FADE$5 = "fade";
  var CLASS_NAME_SHOW$8 = "show";
  var Alert = class extends BaseComponent {
    static get NAME() {
      return NAME$d;
    }
    close() {
      const closeEvent = EventHandler.trigger(this._element, EVENT_CLOSE);
      if (closeEvent.defaultPrevented) {
        return;
      }
      this._element.classList.remove(CLASS_NAME_SHOW$8);
      const isAnimated = this._element.classList.contains(CLASS_NAME_FADE$5);
      this._queueCallback(() => this._destroyElement(), this._element, isAnimated);
    }
    _destroyElement() {
      this._element.remove();
      EventHandler.trigger(this._element, EVENT_CLOSED);
      this.dispose();
    }
    static jQueryInterface(config) {
      return this.each(function() {
        const data = Alert.getOrCreateInstance(this);
        if (typeof config !== "string") {
          return;
        }
        if (data[config] === void 0 || config.startsWith("_") || config === "constructor") {
          throw new TypeError(`No method named "${config}"`);
        }
        data[config](this);
      });
    }
  };
  enableDismissTrigger(Alert, "close");
  defineJQueryPlugin(Alert);
  var NAME$c = "button";
  var DATA_KEY$b = "bs.button";
  var EVENT_KEY$b = `.${DATA_KEY$b}`;
  var DATA_API_KEY$7 = ".data-api";
  var CLASS_NAME_ACTIVE$3 = "active";
  var SELECTOR_DATA_TOGGLE$5 = '[data-bs-toggle="button"]';
  var EVENT_CLICK_DATA_API$6 = `click${EVENT_KEY$b}${DATA_API_KEY$7}`;
  var Button = class extends BaseComponent {
    static get NAME() {
      return NAME$c;
    }
    toggle() {
      this._element.setAttribute("aria-pressed", this._element.classList.toggle(CLASS_NAME_ACTIVE$3));
    }
    static jQueryInterface(config) {
      return this.each(function() {
        const data = Button.getOrCreateInstance(this);
        if (config === "toggle") {
          data[config]();
        }
      });
    }
  };
  EventHandler.on(document, EVENT_CLICK_DATA_API$6, SELECTOR_DATA_TOGGLE$5, (event) => {
    event.preventDefault();
    const button = event.target.closest(SELECTOR_DATA_TOGGLE$5);
    const data = Button.getOrCreateInstance(button);
    data.toggle();
  });
  defineJQueryPlugin(Button);
  function normalizeData(val) {
    if (val === "true") {
      return true;
    }
    if (val === "false") {
      return false;
    }
    if (val === Number(val).toString()) {
      return Number(val);
    }
    if (val === "" || val === "null") {
      return null;
    }
    return val;
  }
  function normalizeDataKey(key) {
    return key.replace(/[A-Z]/g, (chr) => `-${chr.toLowerCase()}`);
  }
  var Manipulator = {
    setDataAttribute(element, key, value) {
      element.setAttribute(`data-bs-${normalizeDataKey(key)}`, value);
    },
    removeDataAttribute(element, key) {
      element.removeAttribute(`data-bs-${normalizeDataKey(key)}`);
    },
    getDataAttributes(element) {
      if (!element) {
        return {};
      }
      const attributes = {};
      Object.keys(element.dataset).filter((key) => key.startsWith("bs")).forEach((key) => {
        let pureKey = key.replace(/^bs/, "");
        pureKey = pureKey.charAt(0).toLowerCase() + pureKey.slice(1, pureKey.length);
        attributes[pureKey] = normalizeData(element.dataset[key]);
      });
      return attributes;
    },
    getDataAttribute(element, key) {
      return normalizeData(element.getAttribute(`data-bs-${normalizeDataKey(key)}`));
    },
    offset(element) {
      const rect = element.getBoundingClientRect();
      return {
        top: rect.top + window.pageYOffset,
        left: rect.left + window.pageXOffset
      };
    },
    position(element) {
      return {
        top: element.offsetTop,
        left: element.offsetLeft
      };
    }
  };
  var NODE_TEXT = 3;
  var SelectorEngine = {
    find(selector, element = document.documentElement) {
      return [].concat(...Element.prototype.querySelectorAll.call(element, selector));
    },
    findOne(selector, element = document.documentElement) {
      return Element.prototype.querySelector.call(element, selector);
    },
    children(element, selector) {
      return [].concat(...element.children).filter((child) => child.matches(selector));
    },
    parents(element, selector) {
      const parents = [];
      let ancestor = element.parentNode;
      while (ancestor && ancestor.nodeType === Node.ELEMENT_NODE && ancestor.nodeType !== NODE_TEXT) {
        if (ancestor.matches(selector)) {
          parents.push(ancestor);
        }
        ancestor = ancestor.parentNode;
      }
      return parents;
    },
    prev(element, selector) {
      let previous = element.previousElementSibling;
      while (previous) {
        if (previous.matches(selector)) {
          return [previous];
        }
        previous = previous.previousElementSibling;
      }
      return [];
    },
    next(element, selector) {
      let next = element.nextElementSibling;
      while (next) {
        if (next.matches(selector)) {
          return [next];
        }
        next = next.nextElementSibling;
      }
      return [];
    },
    focusableChildren(element) {
      const focusables = ["a", "button", "input", "textarea", "select", "details", "[tabindex]", '[contenteditable="true"]'].map((selector) => `${selector}:not([tabindex^="-"])`).join(", ");
      return this.find(focusables, element).filter((el) => !isDisabled(el) && isVisible(el));
    }
  };
  var NAME$b = "carousel";
  var DATA_KEY$a = "bs.carousel";
  var EVENT_KEY$a = `.${DATA_KEY$a}`;
  var DATA_API_KEY$6 = ".data-api";
  var ARROW_LEFT_KEY = "ArrowLeft";
  var ARROW_RIGHT_KEY = "ArrowRight";
  var TOUCHEVENT_COMPAT_WAIT = 500;
  var SWIPE_THRESHOLD = 40;
  var Default$a = {
    interval: 5e3,
    keyboard: true,
    slide: false,
    pause: "hover",
    wrap: true,
    touch: true
  };
  var DefaultType$a = {
    interval: "(number|boolean)",
    keyboard: "boolean",
    slide: "(boolean|string)",
    pause: "(string|boolean)",
    wrap: "boolean",
    touch: "boolean"
  };
  var ORDER_NEXT = "next";
  var ORDER_PREV = "prev";
  var DIRECTION_LEFT = "left";
  var DIRECTION_RIGHT = "right";
  var KEY_TO_DIRECTION = {
    [ARROW_LEFT_KEY]: DIRECTION_RIGHT,
    [ARROW_RIGHT_KEY]: DIRECTION_LEFT
  };
  var EVENT_SLIDE = `slide${EVENT_KEY$a}`;
  var EVENT_SLID = `slid${EVENT_KEY$a}`;
  var EVENT_KEYDOWN = `keydown${EVENT_KEY$a}`;
  var EVENT_MOUSEENTER = `mouseenter${EVENT_KEY$a}`;
  var EVENT_MOUSELEAVE = `mouseleave${EVENT_KEY$a}`;
  var EVENT_TOUCHSTART = `touchstart${EVENT_KEY$a}`;
  var EVENT_TOUCHMOVE = `touchmove${EVENT_KEY$a}`;
  var EVENT_TOUCHEND = `touchend${EVENT_KEY$a}`;
  var EVENT_POINTERDOWN = `pointerdown${EVENT_KEY$a}`;
  var EVENT_POINTERUP = `pointerup${EVENT_KEY$a}`;
  var EVENT_DRAG_START = `dragstart${EVENT_KEY$a}`;
  var EVENT_LOAD_DATA_API$2 = `load${EVENT_KEY$a}${DATA_API_KEY$6}`;
  var EVENT_CLICK_DATA_API$5 = `click${EVENT_KEY$a}${DATA_API_KEY$6}`;
  var CLASS_NAME_CAROUSEL = "carousel";
  var CLASS_NAME_ACTIVE$2 = "active";
  var CLASS_NAME_SLIDE = "slide";
  var CLASS_NAME_END = "carousel-item-end";
  var CLASS_NAME_START = "carousel-item-start";
  var CLASS_NAME_NEXT = "carousel-item-next";
  var CLASS_NAME_PREV = "carousel-item-prev";
  var CLASS_NAME_POINTER_EVENT = "pointer-event";
  var SELECTOR_ACTIVE$1 = ".active";
  var SELECTOR_ACTIVE_ITEM = ".active.carousel-item";
  var SELECTOR_ITEM = ".carousel-item";
  var SELECTOR_ITEM_IMG = ".carousel-item img";
  var SELECTOR_NEXT_PREV = ".carousel-item-next, .carousel-item-prev";
  var SELECTOR_INDICATORS = ".carousel-indicators";
  var SELECTOR_INDICATOR = "[data-bs-target]";
  var SELECTOR_DATA_SLIDE = "[data-bs-slide], [data-bs-slide-to]";
  var SELECTOR_DATA_RIDE = '[data-bs-ride="carousel"]';
  var POINTER_TYPE_TOUCH = "touch";
  var POINTER_TYPE_PEN = "pen";
  var Carousel = class extends BaseComponent {
    constructor(element, config) {
      super(element);
      this._items = null;
      this._interval = null;
      this._activeElement = null;
      this._isPaused = false;
      this._isSliding = false;
      this.touchTimeout = null;
      this.touchStartX = 0;
      this.touchDeltaX = 0;
      this._config = this._getConfig(config);
      this._indicatorsElement = SelectorEngine.findOne(SELECTOR_INDICATORS, this._element);
      this._touchSupported = "ontouchstart" in document.documentElement || navigator.maxTouchPoints > 0;
      this._pointerEvent = Boolean(window.PointerEvent);
      this._addEventListeners();
    }
    static get Default() {
      return Default$a;
    }
    static get NAME() {
      return NAME$b;
    }
    next() {
      this._slide(ORDER_NEXT);
    }
    nextWhenVisible() {
      if (!document.hidden && isVisible(this._element)) {
        this.next();
      }
    }
    prev() {
      this._slide(ORDER_PREV);
    }
    pause(event) {
      if (!event) {
        this._isPaused = true;
      }
      if (SelectorEngine.findOne(SELECTOR_NEXT_PREV, this._element)) {
        triggerTransitionEnd(this._element);
        this.cycle(true);
      }
      clearInterval(this._interval);
      this._interval = null;
    }
    cycle(event) {
      if (!event) {
        this._isPaused = false;
      }
      if (this._interval) {
        clearInterval(this._interval);
        this._interval = null;
      }
      if (this._config && this._config.interval && !this._isPaused) {
        this._updateInterval();
        this._interval = setInterval((document.visibilityState ? this.nextWhenVisible : this.next).bind(this), this._config.interval);
      }
    }
    to(index) {
      this._activeElement = SelectorEngine.findOne(SELECTOR_ACTIVE_ITEM, this._element);
      const activeIndex = this._getItemIndex(this._activeElement);
      if (index > this._items.length - 1 || index < 0) {
        return;
      }
      if (this._isSliding) {
        EventHandler.one(this._element, EVENT_SLID, () => this.to(index));
        return;
      }
      if (activeIndex === index) {
        this.pause();
        this.cycle();
        return;
      }
      const order2 = index > activeIndex ? ORDER_NEXT : ORDER_PREV;
      this._slide(order2, this._items[index]);
    }
    _getConfig(config) {
      config = {
        ...Default$a,
        ...Manipulator.getDataAttributes(this._element),
        ...typeof config === "object" ? config : {}
      };
      typeCheckConfig(NAME$b, config, DefaultType$a);
      return config;
    }
    _handleSwipe() {
      const absDeltax = Math.abs(this.touchDeltaX);
      if (absDeltax <= SWIPE_THRESHOLD) {
        return;
      }
      const direction = absDeltax / this.touchDeltaX;
      this.touchDeltaX = 0;
      if (!direction) {
        return;
      }
      this._slide(direction > 0 ? DIRECTION_RIGHT : DIRECTION_LEFT);
    }
    _addEventListeners() {
      if (this._config.keyboard) {
        EventHandler.on(this._element, EVENT_KEYDOWN, (event) => this._keydown(event));
      }
      if (this._config.pause === "hover") {
        EventHandler.on(this._element, EVENT_MOUSEENTER, (event) => this.pause(event));
        EventHandler.on(this._element, EVENT_MOUSELEAVE, (event) => this.cycle(event));
      }
      if (this._config.touch && this._touchSupported) {
        this._addTouchEventListeners();
      }
    }
    _addTouchEventListeners() {
      const hasPointerPenTouch = (event) => {
        return this._pointerEvent && (event.pointerType === POINTER_TYPE_PEN || event.pointerType === POINTER_TYPE_TOUCH);
      };
      const start4 = (event) => {
        if (hasPointerPenTouch(event)) {
          this.touchStartX = event.clientX;
        } else if (!this._pointerEvent) {
          this.touchStartX = event.touches[0].clientX;
        }
      };
      const move = (event) => {
        this.touchDeltaX = event.touches && event.touches.length > 1 ? 0 : event.touches[0].clientX - this.touchStartX;
      };
      const end2 = (event) => {
        if (hasPointerPenTouch(event)) {
          this.touchDeltaX = event.clientX - this.touchStartX;
        }
        this._handleSwipe();
        if (this._config.pause === "hover") {
          this.pause();
          if (this.touchTimeout) {
            clearTimeout(this.touchTimeout);
          }
          this.touchTimeout = setTimeout((event2) => this.cycle(event2), TOUCHEVENT_COMPAT_WAIT + this._config.interval);
        }
      };
      SelectorEngine.find(SELECTOR_ITEM_IMG, this._element).forEach((itemImg) => {
        EventHandler.on(itemImg, EVENT_DRAG_START, (event) => event.preventDefault());
      });
      if (this._pointerEvent) {
        EventHandler.on(this._element, EVENT_POINTERDOWN, (event) => start4(event));
        EventHandler.on(this._element, EVENT_POINTERUP, (event) => end2(event));
        this._element.classList.add(CLASS_NAME_POINTER_EVENT);
      } else {
        EventHandler.on(this._element, EVENT_TOUCHSTART, (event) => start4(event));
        EventHandler.on(this._element, EVENT_TOUCHMOVE, (event) => move(event));
        EventHandler.on(this._element, EVENT_TOUCHEND, (event) => end2(event));
      }
    }
    _keydown(event) {
      if (/input|textarea/i.test(event.target.tagName)) {
        return;
      }
      const direction = KEY_TO_DIRECTION[event.key];
      if (direction) {
        event.preventDefault();
        this._slide(direction);
      }
    }
    _getItemIndex(element) {
      this._items = element && element.parentNode ? SelectorEngine.find(SELECTOR_ITEM, element.parentNode) : [];
      return this._items.indexOf(element);
    }
    _getItemByOrder(order2, activeElement) {
      const isNext = order2 === ORDER_NEXT;
      return getNextActiveElement(this._items, activeElement, isNext, this._config.wrap);
    }
    _triggerSlideEvent(relatedTarget, eventDirectionName) {
      const targetIndex = this._getItemIndex(relatedTarget);
      const fromIndex = this._getItemIndex(SelectorEngine.findOne(SELECTOR_ACTIVE_ITEM, this._element));
      return EventHandler.trigger(this._element, EVENT_SLIDE, {
        relatedTarget,
        direction: eventDirectionName,
        from: fromIndex,
        to: targetIndex
      });
    }
    _setActiveIndicatorElement(element) {
      if (this._indicatorsElement) {
        const activeIndicator = SelectorEngine.findOne(SELECTOR_ACTIVE$1, this._indicatorsElement);
        activeIndicator.classList.remove(CLASS_NAME_ACTIVE$2);
        activeIndicator.removeAttribute("aria-current");
        const indicators = SelectorEngine.find(SELECTOR_INDICATOR, this._indicatorsElement);
        for (let i2 = 0; i2 < indicators.length; i2++) {
          if (Number.parseInt(indicators[i2].getAttribute("data-bs-slide-to"), 10) === this._getItemIndex(element)) {
            indicators[i2].classList.add(CLASS_NAME_ACTIVE$2);
            indicators[i2].setAttribute("aria-current", "true");
            break;
          }
        }
      }
    }
    _updateInterval() {
      const element = this._activeElement || SelectorEngine.findOne(SELECTOR_ACTIVE_ITEM, this._element);
      if (!element) {
        return;
      }
      const elementInterval = Number.parseInt(element.getAttribute("data-bs-interval"), 10);
      if (elementInterval) {
        this._config.defaultInterval = this._config.defaultInterval || this._config.interval;
        this._config.interval = elementInterval;
      } else {
        this._config.interval = this._config.defaultInterval || this._config.interval;
      }
    }
    _slide(directionOrOrder, element) {
      const order2 = this._directionToOrder(directionOrOrder);
      const activeElement = SelectorEngine.findOne(SELECTOR_ACTIVE_ITEM, this._element);
      const activeElementIndex = this._getItemIndex(activeElement);
      const nextElement = element || this._getItemByOrder(order2, activeElement);
      const nextElementIndex = this._getItemIndex(nextElement);
      const isCycling = Boolean(this._interval);
      const isNext = order2 === ORDER_NEXT;
      const directionalClassName = isNext ? CLASS_NAME_START : CLASS_NAME_END;
      const orderClassName = isNext ? CLASS_NAME_NEXT : CLASS_NAME_PREV;
      const eventDirectionName = this._orderToDirection(order2);
      if (nextElement && nextElement.classList.contains(CLASS_NAME_ACTIVE$2)) {
        this._isSliding = false;
        return;
      }
      if (this._isSliding) {
        return;
      }
      const slideEvent = this._triggerSlideEvent(nextElement, eventDirectionName);
      if (slideEvent.defaultPrevented) {
        return;
      }
      if (!activeElement || !nextElement) {
        return;
      }
      this._isSliding = true;
      if (isCycling) {
        this.pause();
      }
      this._setActiveIndicatorElement(nextElement);
      this._activeElement = nextElement;
      const triggerSlidEvent = () => {
        EventHandler.trigger(this._element, EVENT_SLID, {
          relatedTarget: nextElement,
          direction: eventDirectionName,
          from: activeElementIndex,
          to: nextElementIndex
        });
      };
      if (this._element.classList.contains(CLASS_NAME_SLIDE)) {
        nextElement.classList.add(orderClassName);
        reflow(nextElement);
        activeElement.classList.add(directionalClassName);
        nextElement.classList.add(directionalClassName);
        const completeCallBack = () => {
          nextElement.classList.remove(directionalClassName, orderClassName);
          nextElement.classList.add(CLASS_NAME_ACTIVE$2);
          activeElement.classList.remove(CLASS_NAME_ACTIVE$2, orderClassName, directionalClassName);
          this._isSliding = false;
          setTimeout(triggerSlidEvent, 0);
        };
        this._queueCallback(completeCallBack, activeElement, true);
      } else {
        activeElement.classList.remove(CLASS_NAME_ACTIVE$2);
        nextElement.classList.add(CLASS_NAME_ACTIVE$2);
        this._isSliding = false;
        triggerSlidEvent();
      }
      if (isCycling) {
        this.cycle();
      }
    }
    _directionToOrder(direction) {
      if (![DIRECTION_RIGHT, DIRECTION_LEFT].includes(direction)) {
        return direction;
      }
      if (isRTL()) {
        return direction === DIRECTION_LEFT ? ORDER_PREV : ORDER_NEXT;
      }
      return direction === DIRECTION_LEFT ? ORDER_NEXT : ORDER_PREV;
    }
    _orderToDirection(order2) {
      if (![ORDER_NEXT, ORDER_PREV].includes(order2)) {
        return order2;
      }
      if (isRTL()) {
        return order2 === ORDER_PREV ? DIRECTION_LEFT : DIRECTION_RIGHT;
      }
      return order2 === ORDER_PREV ? DIRECTION_RIGHT : DIRECTION_LEFT;
    }
    static carouselInterface(element, config) {
      const data = Carousel.getOrCreateInstance(element, config);
      let {
        _config
      } = data;
      if (typeof config === "object") {
        _config = {
          ..._config,
          ...config
        };
      }
      const action = typeof config === "string" ? config : _config.slide;
      if (typeof config === "number") {
        data.to(config);
      } else if (typeof action === "string") {
        if (typeof data[action] === "undefined") {
          throw new TypeError(`No method named "${action}"`);
        }
        data[action]();
      } else if (_config.interval && _config.ride) {
        data.pause();
        data.cycle();
      }
    }
    static jQueryInterface(config) {
      return this.each(function() {
        Carousel.carouselInterface(this, config);
      });
    }
    static dataApiClickHandler(event) {
      const target = getElementFromSelector(this);
      if (!target || !target.classList.contains(CLASS_NAME_CAROUSEL)) {
        return;
      }
      const config = {
        ...Manipulator.getDataAttributes(target),
        ...Manipulator.getDataAttributes(this)
      };
      const slideIndex = this.getAttribute("data-bs-slide-to");
      if (slideIndex) {
        config.interval = false;
      }
      Carousel.carouselInterface(target, config);
      if (slideIndex) {
        Carousel.getInstance(target).to(slideIndex);
      }
      event.preventDefault();
    }
  };
  EventHandler.on(document, EVENT_CLICK_DATA_API$5, SELECTOR_DATA_SLIDE, Carousel.dataApiClickHandler);
  EventHandler.on(window, EVENT_LOAD_DATA_API$2, () => {
    const carousels = SelectorEngine.find(SELECTOR_DATA_RIDE);
    for (let i2 = 0, len = carousels.length; i2 < len; i2++) {
      Carousel.carouselInterface(carousels[i2], Carousel.getInstance(carousels[i2]));
    }
  });
  defineJQueryPlugin(Carousel);
  var NAME$a = "collapse";
  var DATA_KEY$9 = "bs.collapse";
  var EVENT_KEY$9 = `.${DATA_KEY$9}`;
  var DATA_API_KEY$5 = ".data-api";
  var Default$9 = {
    toggle: true,
    parent: null
  };
  var DefaultType$9 = {
    toggle: "boolean",
    parent: "(null|element)"
  };
  var EVENT_SHOW$5 = `show${EVENT_KEY$9}`;
  var EVENT_SHOWN$5 = `shown${EVENT_KEY$9}`;
  var EVENT_HIDE$5 = `hide${EVENT_KEY$9}`;
  var EVENT_HIDDEN$5 = `hidden${EVENT_KEY$9}`;
  var EVENT_CLICK_DATA_API$4 = `click${EVENT_KEY$9}${DATA_API_KEY$5}`;
  var CLASS_NAME_SHOW$7 = "show";
  var CLASS_NAME_COLLAPSE = "collapse";
  var CLASS_NAME_COLLAPSING = "collapsing";
  var CLASS_NAME_COLLAPSED = "collapsed";
  var CLASS_NAME_DEEPER_CHILDREN = `:scope .${CLASS_NAME_COLLAPSE} .${CLASS_NAME_COLLAPSE}`;
  var CLASS_NAME_HORIZONTAL = "collapse-horizontal";
  var WIDTH = "width";
  var HEIGHT = "height";
  var SELECTOR_ACTIVES = ".collapse.show, .collapse.collapsing";
  var SELECTOR_DATA_TOGGLE$4 = '[data-bs-toggle="collapse"]';
  var Collapse = class extends BaseComponent {
    constructor(element, config) {
      super(element);
      this._isTransitioning = false;
      this._config = this._getConfig(config);
      this._triggerArray = [];
      const toggleList = SelectorEngine.find(SELECTOR_DATA_TOGGLE$4);
      for (let i2 = 0, len = toggleList.length; i2 < len; i2++) {
        const elem = toggleList[i2];
        const selector = getSelectorFromElement(elem);
        const filterElement = SelectorEngine.find(selector).filter((foundElem) => foundElem === this._element);
        if (selector !== null && filterElement.length) {
          this._selector = selector;
          this._triggerArray.push(elem);
        }
      }
      this._initializeChildren();
      if (!this._config.parent) {
        this._addAriaAndCollapsedClass(this._triggerArray, this._isShown());
      }
      if (this._config.toggle) {
        this.toggle();
      }
    }
    static get Default() {
      return Default$9;
    }
    static get NAME() {
      return NAME$a;
    }
    toggle() {
      if (this._isShown()) {
        this.hide();
      } else {
        this.show();
      }
    }
    show() {
      if (this._isTransitioning || this._isShown()) {
        return;
      }
      let actives = [];
      let activesData;
      if (this._config.parent) {
        const children = SelectorEngine.find(CLASS_NAME_DEEPER_CHILDREN, this._config.parent);
        actives = SelectorEngine.find(SELECTOR_ACTIVES, this._config.parent).filter((elem) => !children.includes(elem));
      }
      const container = SelectorEngine.findOne(this._selector);
      if (actives.length) {
        const tempActiveData = actives.find((elem) => container !== elem);
        activesData = tempActiveData ? Collapse.getInstance(tempActiveData) : null;
        if (activesData && activesData._isTransitioning) {
          return;
        }
      }
      const startEvent = EventHandler.trigger(this._element, EVENT_SHOW$5);
      if (startEvent.defaultPrevented) {
        return;
      }
      actives.forEach((elemActive) => {
        if (container !== elemActive) {
          Collapse.getOrCreateInstance(elemActive, {
            toggle: false
          }).hide();
        }
        if (!activesData) {
          Data.set(elemActive, DATA_KEY$9, null);
        }
      });
      const dimension = this._getDimension();
      this._element.classList.remove(CLASS_NAME_COLLAPSE);
      this._element.classList.add(CLASS_NAME_COLLAPSING);
      this._element.style[dimension] = 0;
      this._addAriaAndCollapsedClass(this._triggerArray, true);
      this._isTransitioning = true;
      const complete = () => {
        this._isTransitioning = false;
        this._element.classList.remove(CLASS_NAME_COLLAPSING);
        this._element.classList.add(CLASS_NAME_COLLAPSE, CLASS_NAME_SHOW$7);
        this._element.style[dimension] = "";
        EventHandler.trigger(this._element, EVENT_SHOWN$5);
      };
      const capitalizedDimension = dimension[0].toUpperCase() + dimension.slice(1);
      const scrollSize = `scroll${capitalizedDimension}`;
      this._queueCallback(complete, this._element, true);
      this._element.style[dimension] = `${this._element[scrollSize]}px`;
    }
    hide() {
      if (this._isTransitioning || !this._isShown()) {
        return;
      }
      const startEvent = EventHandler.trigger(this._element, EVENT_HIDE$5);
      if (startEvent.defaultPrevented) {
        return;
      }
      const dimension = this._getDimension();
      this._element.style[dimension] = `${this._element.getBoundingClientRect()[dimension]}px`;
      reflow(this._element);
      this._element.classList.add(CLASS_NAME_COLLAPSING);
      this._element.classList.remove(CLASS_NAME_COLLAPSE, CLASS_NAME_SHOW$7);
      const triggerArrayLength = this._triggerArray.length;
      for (let i2 = 0; i2 < triggerArrayLength; i2++) {
        const trigger = this._triggerArray[i2];
        const elem = getElementFromSelector(trigger);
        if (elem && !this._isShown(elem)) {
          this._addAriaAndCollapsedClass([trigger], false);
        }
      }
      this._isTransitioning = true;
      const complete = () => {
        this._isTransitioning = false;
        this._element.classList.remove(CLASS_NAME_COLLAPSING);
        this._element.classList.add(CLASS_NAME_COLLAPSE);
        EventHandler.trigger(this._element, EVENT_HIDDEN$5);
      };
      this._element.style[dimension] = "";
      this._queueCallback(complete, this._element, true);
    }
    _isShown(element = this._element) {
      return element.classList.contains(CLASS_NAME_SHOW$7);
    }
    _getConfig(config) {
      config = {
        ...Default$9,
        ...Manipulator.getDataAttributes(this._element),
        ...config
      };
      config.toggle = Boolean(config.toggle);
      config.parent = getElement(config.parent);
      typeCheckConfig(NAME$a, config, DefaultType$9);
      return config;
    }
    _getDimension() {
      return this._element.classList.contains(CLASS_NAME_HORIZONTAL) ? WIDTH : HEIGHT;
    }
    _initializeChildren() {
      if (!this._config.parent) {
        return;
      }
      const children = SelectorEngine.find(CLASS_NAME_DEEPER_CHILDREN, this._config.parent);
      SelectorEngine.find(SELECTOR_DATA_TOGGLE$4, this._config.parent).filter((elem) => !children.includes(elem)).forEach((element) => {
        const selected = getElementFromSelector(element);
        if (selected) {
          this._addAriaAndCollapsedClass([element], this._isShown(selected));
        }
      });
    }
    _addAriaAndCollapsedClass(triggerArray, isOpen) {
      if (!triggerArray.length) {
        return;
      }
      triggerArray.forEach((elem) => {
        if (isOpen) {
          elem.classList.remove(CLASS_NAME_COLLAPSED);
        } else {
          elem.classList.add(CLASS_NAME_COLLAPSED);
        }
        elem.setAttribute("aria-expanded", isOpen);
      });
    }
    static jQueryInterface(config) {
      return this.each(function() {
        const _config = {};
        if (typeof config === "string" && /show|hide/.test(config)) {
          _config.toggle = false;
        }
        const data = Collapse.getOrCreateInstance(this, _config);
        if (typeof config === "string") {
          if (typeof data[config] === "undefined") {
            throw new TypeError(`No method named "${config}"`);
          }
          data[config]();
        }
      });
    }
  };
  EventHandler.on(document, EVENT_CLICK_DATA_API$4, SELECTOR_DATA_TOGGLE$4, function(event) {
    if (event.target.tagName === "A" || event.delegateTarget && event.delegateTarget.tagName === "A") {
      event.preventDefault();
    }
    const selector = getSelectorFromElement(this);
    const selectorElements = SelectorEngine.find(selector);
    selectorElements.forEach((element) => {
      Collapse.getOrCreateInstance(element, {
        toggle: false
      }).toggle();
    });
  });
  defineJQueryPlugin(Collapse);
  var NAME$9 = "dropdown";
  var DATA_KEY$8 = "bs.dropdown";
  var EVENT_KEY$8 = `.${DATA_KEY$8}`;
  var DATA_API_KEY$4 = ".data-api";
  var ESCAPE_KEY$2 = "Escape";
  var SPACE_KEY = "Space";
  var TAB_KEY$1 = "Tab";
  var ARROW_UP_KEY = "ArrowUp";
  var ARROW_DOWN_KEY = "ArrowDown";
  var RIGHT_MOUSE_BUTTON = 2;
  var REGEXP_KEYDOWN = new RegExp(`${ARROW_UP_KEY}|${ARROW_DOWN_KEY}|${ESCAPE_KEY$2}`);
  var EVENT_HIDE$4 = `hide${EVENT_KEY$8}`;
  var EVENT_HIDDEN$4 = `hidden${EVENT_KEY$8}`;
  var EVENT_SHOW$4 = `show${EVENT_KEY$8}`;
  var EVENT_SHOWN$4 = `shown${EVENT_KEY$8}`;
  var EVENT_CLICK_DATA_API$3 = `click${EVENT_KEY$8}${DATA_API_KEY$4}`;
  var EVENT_KEYDOWN_DATA_API = `keydown${EVENT_KEY$8}${DATA_API_KEY$4}`;
  var EVENT_KEYUP_DATA_API = `keyup${EVENT_KEY$8}${DATA_API_KEY$4}`;
  var CLASS_NAME_SHOW$6 = "show";
  var CLASS_NAME_DROPUP = "dropup";
  var CLASS_NAME_DROPEND = "dropend";
  var CLASS_NAME_DROPSTART = "dropstart";
  var CLASS_NAME_NAVBAR = "navbar";
  var SELECTOR_DATA_TOGGLE$3 = '[data-bs-toggle="dropdown"]';
  var SELECTOR_MENU = ".dropdown-menu";
  var SELECTOR_NAVBAR_NAV = ".navbar-nav";
  var SELECTOR_VISIBLE_ITEMS = ".dropdown-menu .dropdown-item:not(.disabled):not(:disabled)";
  var PLACEMENT_TOP = isRTL() ? "top-end" : "top-start";
  var PLACEMENT_TOPEND = isRTL() ? "top-start" : "top-end";
  var PLACEMENT_BOTTOM = isRTL() ? "bottom-end" : "bottom-start";
  var PLACEMENT_BOTTOMEND = isRTL() ? "bottom-start" : "bottom-end";
  var PLACEMENT_RIGHT = isRTL() ? "left-start" : "right-start";
  var PLACEMENT_LEFT = isRTL() ? "right-start" : "left-start";
  var Default$8 = {
    offset: [0, 2],
    boundary: "clippingParents",
    reference: "toggle",
    display: "dynamic",
    popperConfig: null,
    autoClose: true
  };
  var DefaultType$8 = {
    offset: "(array|string|function)",
    boundary: "(string|element)",
    reference: "(string|element|object)",
    display: "string",
    popperConfig: "(null|object|function)",
    autoClose: "(boolean|string)"
  };
  var Dropdown = class extends BaseComponent {
    constructor(element, config) {
      super(element);
      this._popper = null;
      this._config = this._getConfig(config);
      this._menu = this._getMenuElement();
      this._inNavbar = this._detectNavbar();
    }
    static get Default() {
      return Default$8;
    }
    static get DefaultType() {
      return DefaultType$8;
    }
    static get NAME() {
      return NAME$9;
    }
    toggle() {
      return this._isShown() ? this.hide() : this.show();
    }
    show() {
      if (isDisabled(this._element) || this._isShown(this._menu)) {
        return;
      }
      const relatedTarget = {
        relatedTarget: this._element
      };
      const showEvent = EventHandler.trigger(this._element, EVENT_SHOW$4, relatedTarget);
      if (showEvent.defaultPrevented) {
        return;
      }
      const parent = Dropdown.getParentFromElement(this._element);
      if (this._inNavbar) {
        Manipulator.setDataAttribute(this._menu, "popper", "none");
      } else {
        this._createPopper(parent);
      }
      if ("ontouchstart" in document.documentElement && !parent.closest(SELECTOR_NAVBAR_NAV)) {
        [].concat(...document.body.children).forEach((elem) => EventHandler.on(elem, "mouseover", noop));
      }
      this._element.focus();
      this._element.setAttribute("aria-expanded", true);
      this._menu.classList.add(CLASS_NAME_SHOW$6);
      this._element.classList.add(CLASS_NAME_SHOW$6);
      EventHandler.trigger(this._element, EVENT_SHOWN$4, relatedTarget);
    }
    hide() {
      if (isDisabled(this._element) || !this._isShown(this._menu)) {
        return;
      }
      const relatedTarget = {
        relatedTarget: this._element
      };
      this._completeHide(relatedTarget);
    }
    dispose() {
      if (this._popper) {
        this._popper.destroy();
      }
      super.dispose();
    }
    update() {
      this._inNavbar = this._detectNavbar();
      if (this._popper) {
        this._popper.update();
      }
    }
    _completeHide(relatedTarget) {
      const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE$4, relatedTarget);
      if (hideEvent.defaultPrevented) {
        return;
      }
      if ("ontouchstart" in document.documentElement) {
        [].concat(...document.body.children).forEach((elem) => EventHandler.off(elem, "mouseover", noop));
      }
      if (this._popper) {
        this._popper.destroy();
      }
      this._menu.classList.remove(CLASS_NAME_SHOW$6);
      this._element.classList.remove(CLASS_NAME_SHOW$6);
      this._element.setAttribute("aria-expanded", "false");
      Manipulator.removeDataAttribute(this._menu, "popper");
      EventHandler.trigger(this._element, EVENT_HIDDEN$4, relatedTarget);
    }
    _getConfig(config) {
      config = {
        ...this.constructor.Default,
        ...Manipulator.getDataAttributes(this._element),
        ...config
      };
      typeCheckConfig(NAME$9, config, this.constructor.DefaultType);
      if (typeof config.reference === "object" && !isElement2(config.reference) && typeof config.reference.getBoundingClientRect !== "function") {
        throw new TypeError(`${NAME$9.toUpperCase()}: Option "reference" provided type "object" without a required "getBoundingClientRect" method.`);
      }
      return config;
    }
    _createPopper(parent) {
      if (typeof lib_exports === "undefined") {
        throw new TypeError("Bootstrap's dropdowns require Popper (https://popper.js.org)");
      }
      let referenceElement = this._element;
      if (this._config.reference === "parent") {
        referenceElement = parent;
      } else if (isElement2(this._config.reference)) {
        referenceElement = getElement(this._config.reference);
      } else if (typeof this._config.reference === "object") {
        referenceElement = this._config.reference;
      }
      const popperConfig = this._getPopperConfig();
      const isDisplayStatic = popperConfig.modifiers.find((modifier) => modifier.name === "applyStyles" && modifier.enabled === false);
      this._popper = createPopper3(referenceElement, this._menu, popperConfig);
      if (isDisplayStatic) {
        Manipulator.setDataAttribute(this._menu, "popper", "static");
      }
    }
    _isShown(element = this._element) {
      return element.classList.contains(CLASS_NAME_SHOW$6);
    }
    _getMenuElement() {
      return SelectorEngine.next(this._element, SELECTOR_MENU)[0];
    }
    _getPlacement() {
      const parentDropdown = this._element.parentNode;
      if (parentDropdown.classList.contains(CLASS_NAME_DROPEND)) {
        return PLACEMENT_RIGHT;
      }
      if (parentDropdown.classList.contains(CLASS_NAME_DROPSTART)) {
        return PLACEMENT_LEFT;
      }
      const isEnd = getComputedStyle(this._menu).getPropertyValue("--bs-position").trim() === "end";
      if (parentDropdown.classList.contains(CLASS_NAME_DROPUP)) {
        return isEnd ? PLACEMENT_TOPEND : PLACEMENT_TOP;
      }
      return isEnd ? PLACEMENT_BOTTOMEND : PLACEMENT_BOTTOM;
    }
    _detectNavbar() {
      return this._element.closest(`.${CLASS_NAME_NAVBAR}`) !== null;
    }
    _getOffset() {
      const {
        offset: offset2
      } = this._config;
      if (typeof offset2 === "string") {
        return offset2.split(",").map((val) => Number.parseInt(val, 10));
      }
      if (typeof offset2 === "function") {
        return (popperData) => offset2(popperData, this._element);
      }
      return offset2;
    }
    _getPopperConfig() {
      const defaultBsPopperConfig = {
        placement: this._getPlacement(),
        modifiers: [{
          name: "preventOverflow",
          options: {
            boundary: this._config.boundary
          }
        }, {
          name: "offset",
          options: {
            offset: this._getOffset()
          }
        }]
      };
      if (this._config.display === "static") {
        defaultBsPopperConfig.modifiers = [{
          name: "applyStyles",
          enabled: false
        }];
      }
      return {
        ...defaultBsPopperConfig,
        ...typeof this._config.popperConfig === "function" ? this._config.popperConfig(defaultBsPopperConfig) : this._config.popperConfig
      };
    }
    _selectMenuItem({
      key,
      target
    }) {
      const items = SelectorEngine.find(SELECTOR_VISIBLE_ITEMS, this._menu).filter(isVisible);
      if (!items.length) {
        return;
      }
      getNextActiveElement(items, target, key === ARROW_DOWN_KEY, !items.includes(target)).focus();
    }
    static jQueryInterface(config) {
      return this.each(function() {
        const data = Dropdown.getOrCreateInstance(this, config);
        if (typeof config !== "string") {
          return;
        }
        if (typeof data[config] === "undefined") {
          throw new TypeError(`No method named "${config}"`);
        }
        data[config]();
      });
    }
    static clearMenus(event) {
      if (event && (event.button === RIGHT_MOUSE_BUTTON || event.type === "keyup" && event.key !== TAB_KEY$1)) {
        return;
      }
      const toggles = SelectorEngine.find(SELECTOR_DATA_TOGGLE$3);
      for (let i2 = 0, len = toggles.length; i2 < len; i2++) {
        const context = Dropdown.getInstance(toggles[i2]);
        if (!context || context._config.autoClose === false) {
          continue;
        }
        if (!context._isShown()) {
          continue;
        }
        const relatedTarget = {
          relatedTarget: context._element
        };
        if (event) {
          const composedPath = event.composedPath();
          const isMenuTarget = composedPath.includes(context._menu);
          if (composedPath.includes(context._element) || context._config.autoClose === "inside" && !isMenuTarget || context._config.autoClose === "outside" && isMenuTarget) {
            continue;
          }
          if (context._menu.contains(event.target) && (event.type === "keyup" && event.key === TAB_KEY$1 || /input|select|option|textarea|form/i.test(event.target.tagName))) {
            continue;
          }
          if (event.type === "click") {
            relatedTarget.clickEvent = event;
          }
        }
        context._completeHide(relatedTarget);
      }
    }
    static getParentFromElement(element) {
      return getElementFromSelector(element) || element.parentNode;
    }
    static dataApiKeydownHandler(event) {
      if (/input|textarea/i.test(event.target.tagName) ? event.key === SPACE_KEY || event.key !== ESCAPE_KEY$2 && (event.key !== ARROW_DOWN_KEY && event.key !== ARROW_UP_KEY || event.target.closest(SELECTOR_MENU)) : !REGEXP_KEYDOWN.test(event.key)) {
        return;
      }
      const isActive = this.classList.contains(CLASS_NAME_SHOW$6);
      if (!isActive && event.key === ESCAPE_KEY$2) {
        return;
      }
      event.preventDefault();
      event.stopPropagation();
      if (isDisabled(this)) {
        return;
      }
      const getToggleButton = this.matches(SELECTOR_DATA_TOGGLE$3) ? this : SelectorEngine.prev(this, SELECTOR_DATA_TOGGLE$3)[0];
      const instance = Dropdown.getOrCreateInstance(getToggleButton);
      if (event.key === ESCAPE_KEY$2) {
        instance.hide();
        return;
      }
      if (event.key === ARROW_UP_KEY || event.key === ARROW_DOWN_KEY) {
        if (!isActive) {
          instance.show();
        }
        instance._selectMenuItem(event);
        return;
      }
      if (!isActive || event.key === SPACE_KEY) {
        Dropdown.clearMenus();
      }
    }
  };
  EventHandler.on(document, EVENT_KEYDOWN_DATA_API, SELECTOR_DATA_TOGGLE$3, Dropdown.dataApiKeydownHandler);
  EventHandler.on(document, EVENT_KEYDOWN_DATA_API, SELECTOR_MENU, Dropdown.dataApiKeydownHandler);
  EventHandler.on(document, EVENT_CLICK_DATA_API$3, Dropdown.clearMenus);
  EventHandler.on(document, EVENT_KEYUP_DATA_API, Dropdown.clearMenus);
  EventHandler.on(document, EVENT_CLICK_DATA_API$3, SELECTOR_DATA_TOGGLE$3, function(event) {
    event.preventDefault();
    Dropdown.getOrCreateInstance(this).toggle();
  });
  defineJQueryPlugin(Dropdown);
  var SELECTOR_FIXED_CONTENT = ".fixed-top, .fixed-bottom, .is-fixed, .sticky-top";
  var SELECTOR_STICKY_CONTENT = ".sticky-top";
  var ScrollBarHelper = class {
    constructor() {
      this._element = document.body;
    }
    getWidth() {
      const documentWidth = document.documentElement.clientWidth;
      return Math.abs(window.innerWidth - documentWidth);
    }
    hide() {
      const width = this.getWidth();
      this._disableOverFlow();
      this._setElementAttributes(this._element, "paddingRight", (calculatedValue) => calculatedValue + width);
      this._setElementAttributes(SELECTOR_FIXED_CONTENT, "paddingRight", (calculatedValue) => calculatedValue + width);
      this._setElementAttributes(SELECTOR_STICKY_CONTENT, "marginRight", (calculatedValue) => calculatedValue - width);
    }
    _disableOverFlow() {
      this._saveInitialAttribute(this._element, "overflow");
      this._element.style.overflow = "hidden";
    }
    _setElementAttributes(selector, styleProp, callback2) {
      const scrollbarWidth = this.getWidth();
      const manipulationCallBack = (element) => {
        if (element !== this._element && window.innerWidth > element.clientWidth + scrollbarWidth) {
          return;
        }
        this._saveInitialAttribute(element, styleProp);
        const calculatedValue = window.getComputedStyle(element)[styleProp];
        element.style[styleProp] = `${callback2(Number.parseFloat(calculatedValue))}px`;
      };
      this._applyManipulationCallback(selector, manipulationCallBack);
    }
    reset() {
      this._resetElementAttributes(this._element, "overflow");
      this._resetElementAttributes(this._element, "paddingRight");
      this._resetElementAttributes(SELECTOR_FIXED_CONTENT, "paddingRight");
      this._resetElementAttributes(SELECTOR_STICKY_CONTENT, "marginRight");
    }
    _saveInitialAttribute(element, styleProp) {
      const actualValue = element.style[styleProp];
      if (actualValue) {
        Manipulator.setDataAttribute(element, styleProp, actualValue);
      }
    }
    _resetElementAttributes(selector, styleProp) {
      const manipulationCallBack = (element) => {
        const value = Manipulator.getDataAttribute(element, styleProp);
        if (typeof value === "undefined") {
          element.style.removeProperty(styleProp);
        } else {
          Manipulator.removeDataAttribute(element, styleProp);
          element.style[styleProp] = value;
        }
      };
      this._applyManipulationCallback(selector, manipulationCallBack);
    }
    _applyManipulationCallback(selector, callBack) {
      if (isElement2(selector)) {
        callBack(selector);
      } else {
        SelectorEngine.find(selector, this._element).forEach(callBack);
      }
    }
    isOverflowing() {
      return this.getWidth() > 0;
    }
  };
  var Default$7 = {
    className: "modal-backdrop",
    isVisible: true,
    isAnimated: false,
    rootElement: "body",
    clickCallback: null
  };
  var DefaultType$7 = {
    className: "string",
    isVisible: "boolean",
    isAnimated: "boolean",
    rootElement: "(element|string)",
    clickCallback: "(function|null)"
  };
  var NAME$8 = "backdrop";
  var CLASS_NAME_FADE$4 = "fade";
  var CLASS_NAME_SHOW$5 = "show";
  var EVENT_MOUSEDOWN = `mousedown.bs.${NAME$8}`;
  var Backdrop = class {
    constructor(config) {
      this._config = this._getConfig(config);
      this._isAppended = false;
      this._element = null;
    }
    show(callback2) {
      if (!this._config.isVisible) {
        execute(callback2);
        return;
      }
      this._append();
      if (this._config.isAnimated) {
        reflow(this._getElement());
      }
      this._getElement().classList.add(CLASS_NAME_SHOW$5);
      this._emulateAnimation(() => {
        execute(callback2);
      });
    }
    hide(callback2) {
      if (!this._config.isVisible) {
        execute(callback2);
        return;
      }
      this._getElement().classList.remove(CLASS_NAME_SHOW$5);
      this._emulateAnimation(() => {
        this.dispose();
        execute(callback2);
      });
    }
    _getElement() {
      if (!this._element) {
        const backdrop = document.createElement("div");
        backdrop.className = this._config.className;
        if (this._config.isAnimated) {
          backdrop.classList.add(CLASS_NAME_FADE$4);
        }
        this._element = backdrop;
      }
      return this._element;
    }
    _getConfig(config) {
      config = {
        ...Default$7,
        ...typeof config === "object" ? config : {}
      };
      config.rootElement = getElement(config.rootElement);
      typeCheckConfig(NAME$8, config, DefaultType$7);
      return config;
    }
    _append() {
      if (this._isAppended) {
        return;
      }
      this._config.rootElement.append(this._getElement());
      EventHandler.on(this._getElement(), EVENT_MOUSEDOWN, () => {
        execute(this._config.clickCallback);
      });
      this._isAppended = true;
    }
    dispose() {
      if (!this._isAppended) {
        return;
      }
      EventHandler.off(this._element, EVENT_MOUSEDOWN);
      this._element.remove();
      this._isAppended = false;
    }
    _emulateAnimation(callback2) {
      executeAfterTransition(callback2, this._getElement(), this._config.isAnimated);
    }
  };
  var Default$6 = {
    trapElement: null,
    autofocus: true
  };
  var DefaultType$6 = {
    trapElement: "element",
    autofocus: "boolean"
  };
  var NAME$7 = "focustrap";
  var DATA_KEY$7 = "bs.focustrap";
  var EVENT_KEY$7 = `.${DATA_KEY$7}`;
  var EVENT_FOCUSIN$1 = `focusin${EVENT_KEY$7}`;
  var EVENT_KEYDOWN_TAB = `keydown.tab${EVENT_KEY$7}`;
  var TAB_KEY = "Tab";
  var TAB_NAV_FORWARD = "forward";
  var TAB_NAV_BACKWARD = "backward";
  var FocusTrap = class {
    constructor(config) {
      this._config = this._getConfig(config);
      this._isActive = false;
      this._lastTabNavDirection = null;
    }
    activate() {
      const {
        trapElement,
        autofocus
      } = this._config;
      if (this._isActive) {
        return;
      }
      if (autofocus) {
        trapElement.focus();
      }
      EventHandler.off(document, EVENT_KEY$7);
      EventHandler.on(document, EVENT_FOCUSIN$1, (event) => this._handleFocusin(event));
      EventHandler.on(document, EVENT_KEYDOWN_TAB, (event) => this._handleKeydown(event));
      this._isActive = true;
    }
    deactivate() {
      if (!this._isActive) {
        return;
      }
      this._isActive = false;
      EventHandler.off(document, EVENT_KEY$7);
    }
    _handleFocusin(event) {
      const {
        target
      } = event;
      const {
        trapElement
      } = this._config;
      if (target === document || target === trapElement || trapElement.contains(target)) {
        return;
      }
      const elements2 = SelectorEngine.focusableChildren(trapElement);
      if (elements2.length === 0) {
        trapElement.focus();
      } else if (this._lastTabNavDirection === TAB_NAV_BACKWARD) {
        elements2[elements2.length - 1].focus();
      } else {
        elements2[0].focus();
      }
    }
    _handleKeydown(event) {
      if (event.key !== TAB_KEY) {
        return;
      }
      this._lastTabNavDirection = event.shiftKey ? TAB_NAV_BACKWARD : TAB_NAV_FORWARD;
    }
    _getConfig(config) {
      config = {
        ...Default$6,
        ...typeof config === "object" ? config : {}
      };
      typeCheckConfig(NAME$7, config, DefaultType$6);
      return config;
    }
  };
  var NAME$6 = "modal";
  var DATA_KEY$6 = "bs.modal";
  var EVENT_KEY$6 = `.${DATA_KEY$6}`;
  var DATA_API_KEY$3 = ".data-api";
  var ESCAPE_KEY$1 = "Escape";
  var Default$5 = {
    backdrop: true,
    keyboard: true,
    focus: true
  };
  var DefaultType$5 = {
    backdrop: "(boolean|string)",
    keyboard: "boolean",
    focus: "boolean"
  };
  var EVENT_HIDE$3 = `hide${EVENT_KEY$6}`;
  var EVENT_HIDE_PREVENTED = `hidePrevented${EVENT_KEY$6}`;
  var EVENT_HIDDEN$3 = `hidden${EVENT_KEY$6}`;
  var EVENT_SHOW$3 = `show${EVENT_KEY$6}`;
  var EVENT_SHOWN$3 = `shown${EVENT_KEY$6}`;
  var EVENT_RESIZE = `resize${EVENT_KEY$6}`;
  var EVENT_CLICK_DISMISS = `click.dismiss${EVENT_KEY$6}`;
  var EVENT_KEYDOWN_DISMISS$1 = `keydown.dismiss${EVENT_KEY$6}`;
  var EVENT_MOUSEUP_DISMISS = `mouseup.dismiss${EVENT_KEY$6}`;
  var EVENT_MOUSEDOWN_DISMISS = `mousedown.dismiss${EVENT_KEY$6}`;
  var EVENT_CLICK_DATA_API$2 = `click${EVENT_KEY$6}${DATA_API_KEY$3}`;
  var CLASS_NAME_OPEN = "modal-open";
  var CLASS_NAME_FADE$3 = "fade";
  var CLASS_NAME_SHOW$4 = "show";
  var CLASS_NAME_STATIC = "modal-static";
  var OPEN_SELECTOR$1 = ".modal.show";
  var SELECTOR_DIALOG = ".modal-dialog";
  var SELECTOR_MODAL_BODY = ".modal-body";
  var SELECTOR_DATA_TOGGLE$2 = '[data-bs-toggle="modal"]';
  var Modal = class extends BaseComponent {
    constructor(element, config) {
      super(element);
      this._config = this._getConfig(config);
      this._dialog = SelectorEngine.findOne(SELECTOR_DIALOG, this._element);
      this._backdrop = this._initializeBackDrop();
      this._focustrap = this._initializeFocusTrap();
      this._isShown = false;
      this._ignoreBackdropClick = false;
      this._isTransitioning = false;
      this._scrollBar = new ScrollBarHelper();
    }
    static get Default() {
      return Default$5;
    }
    static get NAME() {
      return NAME$6;
    }
    toggle(relatedTarget) {
      return this._isShown ? this.hide() : this.show(relatedTarget);
    }
    show(relatedTarget) {
      if (this._isShown || this._isTransitioning) {
        return;
      }
      const showEvent = EventHandler.trigger(this._element, EVENT_SHOW$3, {
        relatedTarget
      });
      if (showEvent.defaultPrevented) {
        return;
      }
      this._isShown = true;
      if (this._isAnimated()) {
        this._isTransitioning = true;
      }
      this._scrollBar.hide();
      document.body.classList.add(CLASS_NAME_OPEN);
      this._adjustDialog();
      this._setEscapeEvent();
      this._setResizeEvent();
      EventHandler.on(this._dialog, EVENT_MOUSEDOWN_DISMISS, () => {
        EventHandler.one(this._element, EVENT_MOUSEUP_DISMISS, (event) => {
          if (event.target === this._element) {
            this._ignoreBackdropClick = true;
          }
        });
      });
      this._showBackdrop(() => this._showElement(relatedTarget));
    }
    hide() {
      if (!this._isShown || this._isTransitioning) {
        return;
      }
      const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE$3);
      if (hideEvent.defaultPrevented) {
        return;
      }
      this._isShown = false;
      const isAnimated = this._isAnimated();
      if (isAnimated) {
        this._isTransitioning = true;
      }
      this._setEscapeEvent();
      this._setResizeEvent();
      this._focustrap.deactivate();
      this._element.classList.remove(CLASS_NAME_SHOW$4);
      EventHandler.off(this._element, EVENT_CLICK_DISMISS);
      EventHandler.off(this._dialog, EVENT_MOUSEDOWN_DISMISS);
      this._queueCallback(() => this._hideModal(), this._element, isAnimated);
    }
    dispose() {
      [window, this._dialog].forEach((htmlElement) => EventHandler.off(htmlElement, EVENT_KEY$6));
      this._backdrop.dispose();
      this._focustrap.deactivate();
      super.dispose();
    }
    handleUpdate() {
      this._adjustDialog();
    }
    _initializeBackDrop() {
      return new Backdrop({
        isVisible: Boolean(this._config.backdrop),
        isAnimated: this._isAnimated()
      });
    }
    _initializeFocusTrap() {
      return new FocusTrap({
        trapElement: this._element
      });
    }
    _getConfig(config) {
      config = {
        ...Default$5,
        ...Manipulator.getDataAttributes(this._element),
        ...typeof config === "object" ? config : {}
      };
      typeCheckConfig(NAME$6, config, DefaultType$5);
      return config;
    }
    _showElement(relatedTarget) {
      const isAnimated = this._isAnimated();
      const modalBody = SelectorEngine.findOne(SELECTOR_MODAL_BODY, this._dialog);
      if (!this._element.parentNode || this._element.parentNode.nodeType !== Node.ELEMENT_NODE) {
        document.body.append(this._element);
      }
      this._element.style.display = "block";
      this._element.removeAttribute("aria-hidden");
      this._element.setAttribute("aria-modal", true);
      this._element.setAttribute("role", "dialog");
      this._element.scrollTop = 0;
      if (modalBody) {
        modalBody.scrollTop = 0;
      }
      if (isAnimated) {
        reflow(this._element);
      }
      this._element.classList.add(CLASS_NAME_SHOW$4);
      const transitionComplete = () => {
        if (this._config.focus) {
          this._focustrap.activate();
        }
        this._isTransitioning = false;
        EventHandler.trigger(this._element, EVENT_SHOWN$3, {
          relatedTarget
        });
      };
      this._queueCallback(transitionComplete, this._dialog, isAnimated);
    }
    _setEscapeEvent() {
      if (this._isShown) {
        EventHandler.on(this._element, EVENT_KEYDOWN_DISMISS$1, (event) => {
          if (this._config.keyboard && event.key === ESCAPE_KEY$1) {
            event.preventDefault();
            this.hide();
          } else if (!this._config.keyboard && event.key === ESCAPE_KEY$1) {
            this._triggerBackdropTransition();
          }
        });
      } else {
        EventHandler.off(this._element, EVENT_KEYDOWN_DISMISS$1);
      }
    }
    _setResizeEvent() {
      if (this._isShown) {
        EventHandler.on(window, EVENT_RESIZE, () => this._adjustDialog());
      } else {
        EventHandler.off(window, EVENT_RESIZE);
      }
    }
    _hideModal() {
      this._element.style.display = "none";
      this._element.setAttribute("aria-hidden", true);
      this._element.removeAttribute("aria-modal");
      this._element.removeAttribute("role");
      this._isTransitioning = false;
      this._backdrop.hide(() => {
        document.body.classList.remove(CLASS_NAME_OPEN);
        this._resetAdjustments();
        this._scrollBar.reset();
        EventHandler.trigger(this._element, EVENT_HIDDEN$3);
      });
    }
    _showBackdrop(callback2) {
      EventHandler.on(this._element, EVENT_CLICK_DISMISS, (event) => {
        if (this._ignoreBackdropClick) {
          this._ignoreBackdropClick = false;
          return;
        }
        if (event.target !== event.currentTarget) {
          return;
        }
        if (this._config.backdrop === true) {
          this.hide();
        } else if (this._config.backdrop === "static") {
          this._triggerBackdropTransition();
        }
      });
      this._backdrop.show(callback2);
    }
    _isAnimated() {
      return this._element.classList.contains(CLASS_NAME_FADE$3);
    }
    _triggerBackdropTransition() {
      const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE_PREVENTED);
      if (hideEvent.defaultPrevented) {
        return;
      }
      const {
        classList,
        scrollHeight,
        style
      } = this._element;
      const isModalOverflowing = scrollHeight > document.documentElement.clientHeight;
      if (!isModalOverflowing && style.overflowY === "hidden" || classList.contains(CLASS_NAME_STATIC)) {
        return;
      }
      if (!isModalOverflowing) {
        style.overflowY = "hidden";
      }
      classList.add(CLASS_NAME_STATIC);
      this._queueCallback(() => {
        classList.remove(CLASS_NAME_STATIC);
        if (!isModalOverflowing) {
          this._queueCallback(() => {
            style.overflowY = "";
          }, this._dialog);
        }
      }, this._dialog);
      this._element.focus();
    }
    _adjustDialog() {
      const isModalOverflowing = this._element.scrollHeight > document.documentElement.clientHeight;
      const scrollbarWidth = this._scrollBar.getWidth();
      const isBodyOverflowing = scrollbarWidth > 0;
      if (!isBodyOverflowing && isModalOverflowing && !isRTL() || isBodyOverflowing && !isModalOverflowing && isRTL()) {
        this._element.style.paddingLeft = `${scrollbarWidth}px`;
      }
      if (isBodyOverflowing && !isModalOverflowing && !isRTL() || !isBodyOverflowing && isModalOverflowing && isRTL()) {
        this._element.style.paddingRight = `${scrollbarWidth}px`;
      }
    }
    _resetAdjustments() {
      this._element.style.paddingLeft = "";
      this._element.style.paddingRight = "";
    }
    static jQueryInterface(config, relatedTarget) {
      return this.each(function() {
        const data = Modal.getOrCreateInstance(this, config);
        if (typeof config !== "string") {
          return;
        }
        if (typeof data[config] === "undefined") {
          throw new TypeError(`No method named "${config}"`);
        }
        data[config](relatedTarget);
      });
    }
  };
  EventHandler.on(document, EVENT_CLICK_DATA_API$2, SELECTOR_DATA_TOGGLE$2, function(event) {
    const target = getElementFromSelector(this);
    if (["A", "AREA"].includes(this.tagName)) {
      event.preventDefault();
    }
    EventHandler.one(target, EVENT_SHOW$3, (showEvent) => {
      if (showEvent.defaultPrevented) {
        return;
      }
      EventHandler.one(target, EVENT_HIDDEN$3, () => {
        if (isVisible(this)) {
          this.focus();
        }
      });
    });
    const allReadyOpen = SelectorEngine.findOne(OPEN_SELECTOR$1);
    if (allReadyOpen) {
      Modal.getInstance(allReadyOpen).hide();
    }
    const data = Modal.getOrCreateInstance(target);
    data.toggle(this);
  });
  enableDismissTrigger(Modal);
  defineJQueryPlugin(Modal);
  var NAME$5 = "offcanvas";
  var DATA_KEY$5 = "bs.offcanvas";
  var EVENT_KEY$5 = `.${DATA_KEY$5}`;
  var DATA_API_KEY$2 = ".data-api";
  var EVENT_LOAD_DATA_API$1 = `load${EVENT_KEY$5}${DATA_API_KEY$2}`;
  var ESCAPE_KEY = "Escape";
  var Default$4 = {
    backdrop: true,
    keyboard: true,
    scroll: false
  };
  var DefaultType$4 = {
    backdrop: "boolean",
    keyboard: "boolean",
    scroll: "boolean"
  };
  var CLASS_NAME_SHOW$3 = "show";
  var CLASS_NAME_BACKDROP = "offcanvas-backdrop";
  var OPEN_SELECTOR = ".offcanvas.show";
  var EVENT_SHOW$2 = `show${EVENT_KEY$5}`;
  var EVENT_SHOWN$2 = `shown${EVENT_KEY$5}`;
  var EVENT_HIDE$2 = `hide${EVENT_KEY$5}`;
  var EVENT_HIDDEN$2 = `hidden${EVENT_KEY$5}`;
  var EVENT_CLICK_DATA_API$1 = `click${EVENT_KEY$5}${DATA_API_KEY$2}`;
  var EVENT_KEYDOWN_DISMISS = `keydown.dismiss${EVENT_KEY$5}`;
  var SELECTOR_DATA_TOGGLE$1 = '[data-bs-toggle="offcanvas"]';
  var Offcanvas = class extends BaseComponent {
    constructor(element, config) {
      super(element);
      this._config = this._getConfig(config);
      this._isShown = false;
      this._backdrop = this._initializeBackDrop();
      this._focustrap = this._initializeFocusTrap();
      this._addEventListeners();
    }
    static get NAME() {
      return NAME$5;
    }
    static get Default() {
      return Default$4;
    }
    toggle(relatedTarget) {
      return this._isShown ? this.hide() : this.show(relatedTarget);
    }
    show(relatedTarget) {
      if (this._isShown) {
        return;
      }
      const showEvent = EventHandler.trigger(this._element, EVENT_SHOW$2, {
        relatedTarget
      });
      if (showEvent.defaultPrevented) {
        return;
      }
      this._isShown = true;
      this._element.style.visibility = "visible";
      this._backdrop.show();
      if (!this._config.scroll) {
        new ScrollBarHelper().hide();
      }
      this._element.removeAttribute("aria-hidden");
      this._element.setAttribute("aria-modal", true);
      this._element.setAttribute("role", "dialog");
      this._element.classList.add(CLASS_NAME_SHOW$3);
      const completeCallBack = () => {
        if (!this._config.scroll) {
          this._focustrap.activate();
        }
        EventHandler.trigger(this._element, EVENT_SHOWN$2, {
          relatedTarget
        });
      };
      this._queueCallback(completeCallBack, this._element, true);
    }
    hide() {
      if (!this._isShown) {
        return;
      }
      const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE$2);
      if (hideEvent.defaultPrevented) {
        return;
      }
      this._focustrap.deactivate();
      this._element.blur();
      this._isShown = false;
      this._element.classList.remove(CLASS_NAME_SHOW$3);
      this._backdrop.hide();
      const completeCallback = () => {
        this._element.setAttribute("aria-hidden", true);
        this._element.removeAttribute("aria-modal");
        this._element.removeAttribute("role");
        this._element.style.visibility = "hidden";
        if (!this._config.scroll) {
          new ScrollBarHelper().reset();
        }
        EventHandler.trigger(this._element, EVENT_HIDDEN$2);
      };
      this._queueCallback(completeCallback, this._element, true);
    }
    dispose() {
      this._backdrop.dispose();
      this._focustrap.deactivate();
      super.dispose();
    }
    _getConfig(config) {
      config = {
        ...Default$4,
        ...Manipulator.getDataAttributes(this._element),
        ...typeof config === "object" ? config : {}
      };
      typeCheckConfig(NAME$5, config, DefaultType$4);
      return config;
    }
    _initializeBackDrop() {
      return new Backdrop({
        className: CLASS_NAME_BACKDROP,
        isVisible: this._config.backdrop,
        isAnimated: true,
        rootElement: this._element.parentNode,
        clickCallback: () => this.hide()
      });
    }
    _initializeFocusTrap() {
      return new FocusTrap({
        trapElement: this._element
      });
    }
    _addEventListeners() {
      EventHandler.on(this._element, EVENT_KEYDOWN_DISMISS, (event) => {
        if (this._config.keyboard && event.key === ESCAPE_KEY) {
          this.hide();
        }
      });
    }
    static jQueryInterface(config) {
      return this.each(function() {
        const data = Offcanvas.getOrCreateInstance(this, config);
        if (typeof config !== "string") {
          return;
        }
        if (data[config] === void 0 || config.startsWith("_") || config === "constructor") {
          throw new TypeError(`No method named "${config}"`);
        }
        data[config](this);
      });
    }
  };
  EventHandler.on(document, EVENT_CLICK_DATA_API$1, SELECTOR_DATA_TOGGLE$1, function(event) {
    const target = getElementFromSelector(this);
    if (["A", "AREA"].includes(this.tagName)) {
      event.preventDefault();
    }
    if (isDisabled(this)) {
      return;
    }
    EventHandler.one(target, EVENT_HIDDEN$2, () => {
      if (isVisible(this)) {
        this.focus();
      }
    });
    const allReadyOpen = SelectorEngine.findOne(OPEN_SELECTOR);
    if (allReadyOpen && allReadyOpen !== target) {
      Offcanvas.getInstance(allReadyOpen).hide();
    }
    const data = Offcanvas.getOrCreateInstance(target);
    data.toggle(this);
  });
  EventHandler.on(window, EVENT_LOAD_DATA_API$1, () => SelectorEngine.find(OPEN_SELECTOR).forEach((el) => Offcanvas.getOrCreateInstance(el).show()));
  enableDismissTrigger(Offcanvas);
  defineJQueryPlugin(Offcanvas);
  var uriAttributes = /* @__PURE__ */ new Set(["background", "cite", "href", "itemtype", "longdesc", "poster", "src", "xlink:href"]);
  var ARIA_ATTRIBUTE_PATTERN = /^aria-[\w-]*$/i;
  var SAFE_URL_PATTERN = /^(?:(?:https?|mailto|ftp|tel|file|sms):|[^#&/:?]*(?:[#/?]|$))/i;
  var DATA_URL_PATTERN = /^data:(?:image\/(?:bmp|gif|jpeg|jpg|png|tiff|webp)|video\/(?:mpeg|mp4|ogg|webm)|audio\/(?:mp3|oga|ogg|opus));base64,[\d+/a-z]+=*$/i;
  var allowedAttribute = (attribute, allowedAttributeList) => {
    const attributeName = attribute.nodeName.toLowerCase();
    if (allowedAttributeList.includes(attributeName)) {
      if (uriAttributes.has(attributeName)) {
        return Boolean(SAFE_URL_PATTERN.test(attribute.nodeValue) || DATA_URL_PATTERN.test(attribute.nodeValue));
      }
      return true;
    }
    const regExp = allowedAttributeList.filter((attributeRegex) => attributeRegex instanceof RegExp);
    for (let i2 = 0, len = regExp.length; i2 < len; i2++) {
      if (regExp[i2].test(attributeName)) {
        return true;
      }
    }
    return false;
  };
  var DefaultAllowlist = {
    "*": ["class", "dir", "id", "lang", "role", ARIA_ATTRIBUTE_PATTERN],
    a: ["target", "href", "title", "rel"],
    area: [],
    b: [],
    br: [],
    col: [],
    code: [],
    div: [],
    em: [],
    hr: [],
    h1: [],
    h2: [],
    h3: [],
    h4: [],
    h5: [],
    h6: [],
    i: [],
    img: ["src", "srcset", "alt", "title", "width", "height"],
    li: [],
    ol: [],
    p: [],
    pre: [],
    s: [],
    small: [],
    span: [],
    sub: [],
    sup: [],
    strong: [],
    u: [],
    ul: []
  };
  function sanitizeHtml(unsafeHtml, allowList, sanitizeFn) {
    if (!unsafeHtml.length) {
      return unsafeHtml;
    }
    if (sanitizeFn && typeof sanitizeFn === "function") {
      return sanitizeFn(unsafeHtml);
    }
    const domParser = new window.DOMParser();
    const createdDocument = domParser.parseFromString(unsafeHtml, "text/html");
    const elements2 = [].concat(...createdDocument.body.querySelectorAll("*"));
    for (let i2 = 0, len = elements2.length; i2 < len; i2++) {
      const element = elements2[i2];
      const elementName = element.nodeName.toLowerCase();
      if (!Object.keys(allowList).includes(elementName)) {
        element.remove();
        continue;
      }
      const attributeList = [].concat(...element.attributes);
      const allowedAttributes = [].concat(allowList["*"] || [], allowList[elementName] || []);
      attributeList.forEach((attribute) => {
        if (!allowedAttribute(attribute, allowedAttributes)) {
          element.removeAttribute(attribute.nodeName);
        }
      });
    }
    return createdDocument.body.innerHTML;
  }
  var NAME$4 = "tooltip";
  var DATA_KEY$4 = "bs.tooltip";
  var EVENT_KEY$4 = `.${DATA_KEY$4}`;
  var CLASS_PREFIX$1 = "bs-tooltip";
  var DISALLOWED_ATTRIBUTES = /* @__PURE__ */ new Set(["sanitize", "allowList", "sanitizeFn"]);
  var DefaultType$3 = {
    animation: "boolean",
    template: "string",
    title: "(string|element|function)",
    trigger: "string",
    delay: "(number|object)",
    html: "boolean",
    selector: "(string|boolean)",
    placement: "(string|function)",
    offset: "(array|string|function)",
    container: "(string|element|boolean)",
    fallbackPlacements: "array",
    boundary: "(string|element)",
    customClass: "(string|function)",
    sanitize: "boolean",
    sanitizeFn: "(null|function)",
    allowList: "object",
    popperConfig: "(null|object|function)"
  };
  var AttachmentMap = {
    AUTO: "auto",
    TOP: "top",
    RIGHT: isRTL() ? "left" : "right",
    BOTTOM: "bottom",
    LEFT: isRTL() ? "right" : "left"
  };
  var Default$3 = {
    animation: true,
    template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',
    trigger: "hover focus",
    title: "",
    delay: 0,
    html: false,
    selector: false,
    placement: "top",
    offset: [0, 0],
    container: false,
    fallbackPlacements: ["top", "right", "bottom", "left"],
    boundary: "clippingParents",
    customClass: "",
    sanitize: true,
    sanitizeFn: null,
    allowList: DefaultAllowlist,
    popperConfig: null
  };
  var Event$2 = {
    HIDE: `hide${EVENT_KEY$4}`,
    HIDDEN: `hidden${EVENT_KEY$4}`,
    SHOW: `show${EVENT_KEY$4}`,
    SHOWN: `shown${EVENT_KEY$4}`,
    INSERTED: `inserted${EVENT_KEY$4}`,
    CLICK: `click${EVENT_KEY$4}`,
    FOCUSIN: `focusin${EVENT_KEY$4}`,
    FOCUSOUT: `focusout${EVENT_KEY$4}`,
    MOUSEENTER: `mouseenter${EVENT_KEY$4}`,
    MOUSELEAVE: `mouseleave${EVENT_KEY$4}`
  };
  var CLASS_NAME_FADE$2 = "fade";
  var CLASS_NAME_MODAL = "modal";
  var CLASS_NAME_SHOW$2 = "show";
  var HOVER_STATE_SHOW = "show";
  var HOVER_STATE_OUT = "out";
  var SELECTOR_TOOLTIP_INNER = ".tooltip-inner";
  var SELECTOR_MODAL = `.${CLASS_NAME_MODAL}`;
  var EVENT_MODAL_HIDE = "hide.bs.modal";
  var TRIGGER_HOVER = "hover";
  var TRIGGER_FOCUS = "focus";
  var TRIGGER_CLICK = "click";
  var TRIGGER_MANUAL = "manual";
  var Tooltip = class extends BaseComponent {
    constructor(element, config) {
      if (typeof lib_exports === "undefined") {
        throw new TypeError("Bootstrap's tooltips require Popper (https://popper.js.org)");
      }
      super(element);
      this._isEnabled = true;
      this._timeout = 0;
      this._hoverState = "";
      this._activeTrigger = {};
      this._popper = null;
      this._config = this._getConfig(config);
      this.tip = null;
      this._setListeners();
    }
    static get Default() {
      return Default$3;
    }
    static get NAME() {
      return NAME$4;
    }
    static get Event() {
      return Event$2;
    }
    static get DefaultType() {
      return DefaultType$3;
    }
    enable() {
      this._isEnabled = true;
    }
    disable() {
      this._isEnabled = false;
    }
    toggleEnabled() {
      this._isEnabled = !this._isEnabled;
    }
    toggle(event) {
      if (!this._isEnabled) {
        return;
      }
      if (event) {
        const context = this._initializeOnDelegatedTarget(event);
        context._activeTrigger.click = !context._activeTrigger.click;
        if (context._isWithActiveTrigger()) {
          context._enter(null, context);
        } else {
          context._leave(null, context);
        }
      } else {
        if (this.getTipElement().classList.contains(CLASS_NAME_SHOW$2)) {
          this._leave(null, this);
          return;
        }
        this._enter(null, this);
      }
    }
    dispose() {
      clearTimeout(this._timeout);
      EventHandler.off(this._element.closest(SELECTOR_MODAL), EVENT_MODAL_HIDE, this._hideModalHandler);
      if (this.tip) {
        this.tip.remove();
      }
      this._disposePopper();
      super.dispose();
    }
    show() {
      if (this._element.style.display === "none") {
        throw new Error("Please use show on visible elements");
      }
      if (!(this.isWithContent() && this._isEnabled)) {
        return;
      }
      const showEvent = EventHandler.trigger(this._element, this.constructor.Event.SHOW);
      const shadowRoot = findShadowRoot(this._element);
      const isInTheDom = shadowRoot === null ? this._element.ownerDocument.documentElement.contains(this._element) : shadowRoot.contains(this._element);
      if (showEvent.defaultPrevented || !isInTheDom) {
        return;
      }
      if (this.constructor.NAME === "tooltip" && this.tip && this.getTitle() !== this.tip.querySelector(SELECTOR_TOOLTIP_INNER).innerHTML) {
        this._disposePopper();
        this.tip.remove();
        this.tip = null;
      }
      const tip = this.getTipElement();
      const tipId = getUID(this.constructor.NAME);
      tip.setAttribute("id", tipId);
      this._element.setAttribute("aria-describedby", tipId);
      if (this._config.animation) {
        tip.classList.add(CLASS_NAME_FADE$2);
      }
      const placement = typeof this._config.placement === "function" ? this._config.placement.call(this, tip, this._element) : this._config.placement;
      const attachment = this._getAttachment(placement);
      this._addAttachmentClass(attachment);
      const {
        container
      } = this._config;
      Data.set(tip, this.constructor.DATA_KEY, this);
      if (!this._element.ownerDocument.documentElement.contains(this.tip)) {
        container.append(tip);
        EventHandler.trigger(this._element, this.constructor.Event.INSERTED);
      }
      if (this._popper) {
        this._popper.update();
      } else {
        this._popper = createPopper3(this._element, tip, this._getPopperConfig(attachment));
      }
      tip.classList.add(CLASS_NAME_SHOW$2);
      const customClass = this._resolvePossibleFunction(this._config.customClass);
      if (customClass) {
        tip.classList.add(...customClass.split(" "));
      }
      if ("ontouchstart" in document.documentElement) {
        [].concat(...document.body.children).forEach((element) => {
          EventHandler.on(element, "mouseover", noop);
        });
      }
      const complete = () => {
        const prevHoverState = this._hoverState;
        this._hoverState = null;
        EventHandler.trigger(this._element, this.constructor.Event.SHOWN);
        if (prevHoverState === HOVER_STATE_OUT) {
          this._leave(null, this);
        }
      };
      const isAnimated = this.tip.classList.contains(CLASS_NAME_FADE$2);
      this._queueCallback(complete, this.tip, isAnimated);
    }
    hide() {
      if (!this._popper) {
        return;
      }
      const tip = this.getTipElement();
      const complete = () => {
        if (this._isWithActiveTrigger()) {
          return;
        }
        if (this._hoverState !== HOVER_STATE_SHOW) {
          tip.remove();
        }
        this._cleanTipClass();
        this._element.removeAttribute("aria-describedby");
        EventHandler.trigger(this._element, this.constructor.Event.HIDDEN);
        this._disposePopper();
      };
      const hideEvent = EventHandler.trigger(this._element, this.constructor.Event.HIDE);
      if (hideEvent.defaultPrevented) {
        return;
      }
      tip.classList.remove(CLASS_NAME_SHOW$2);
      if ("ontouchstart" in document.documentElement) {
        [].concat(...document.body.children).forEach((element) => EventHandler.off(element, "mouseover", noop));
      }
      this._activeTrigger[TRIGGER_CLICK] = false;
      this._activeTrigger[TRIGGER_FOCUS] = false;
      this._activeTrigger[TRIGGER_HOVER] = false;
      const isAnimated = this.tip.classList.contains(CLASS_NAME_FADE$2);
      this._queueCallback(complete, this.tip, isAnimated);
      this._hoverState = "";
    }
    update() {
      if (this._popper !== null) {
        this._popper.update();
      }
    }
    isWithContent() {
      return Boolean(this.getTitle());
    }
    getTipElement() {
      if (this.tip) {
        return this.tip;
      }
      const element = document.createElement("div");
      element.innerHTML = this._config.template;
      const tip = element.children[0];
      this.setContent(tip);
      tip.classList.remove(CLASS_NAME_FADE$2, CLASS_NAME_SHOW$2);
      this.tip = tip;
      return this.tip;
    }
    setContent(tip) {
      this._sanitizeAndSetContent(tip, this.getTitle(), SELECTOR_TOOLTIP_INNER);
    }
    _sanitizeAndSetContent(template, content, selector) {
      const templateElement = SelectorEngine.findOne(selector, template);
      if (!content && templateElement) {
        templateElement.remove();
        return;
      }
      this.setElementContent(templateElement, content);
    }
    setElementContent(element, content) {
      if (element === null) {
        return;
      }
      if (isElement2(content)) {
        content = getElement(content);
        if (this._config.html) {
          if (content.parentNode !== element) {
            element.innerHTML = "";
            element.append(content);
          }
        } else {
          element.textContent = content.textContent;
        }
        return;
      }
      if (this._config.html) {
        if (this._config.sanitize) {
          content = sanitizeHtml(content, this._config.allowList, this._config.sanitizeFn);
        }
        element.innerHTML = content;
      } else {
        element.textContent = content;
      }
    }
    getTitle() {
      const title = this._element.getAttribute("data-bs-original-title") || this._config.title;
      return this._resolvePossibleFunction(title);
    }
    updateAttachment(attachment) {
      if (attachment === "right") {
        return "end";
      }
      if (attachment === "left") {
        return "start";
      }
      return attachment;
    }
    _initializeOnDelegatedTarget(event, context) {
      return context || this.constructor.getOrCreateInstance(event.delegateTarget, this._getDelegateConfig());
    }
    _getOffset() {
      const {
        offset: offset2
      } = this._config;
      if (typeof offset2 === "string") {
        return offset2.split(",").map((val) => Number.parseInt(val, 10));
      }
      if (typeof offset2 === "function") {
        return (popperData) => offset2(popperData, this._element);
      }
      return offset2;
    }
    _resolvePossibleFunction(content) {
      return typeof content === "function" ? content.call(this._element) : content;
    }
    _getPopperConfig(attachment) {
      const defaultBsPopperConfig = {
        placement: attachment,
        modifiers: [{
          name: "flip",
          options: {
            fallbackPlacements: this._config.fallbackPlacements
          }
        }, {
          name: "offset",
          options: {
            offset: this._getOffset()
          }
        }, {
          name: "preventOverflow",
          options: {
            boundary: this._config.boundary
          }
        }, {
          name: "arrow",
          options: {
            element: `.${this.constructor.NAME}-arrow`
          }
        }, {
          name: "onChange",
          enabled: true,
          phase: "afterWrite",
          fn: (data) => this._handlePopperPlacementChange(data)
        }],
        onFirstUpdate: (data) => {
          if (data.options.placement !== data.placement) {
            this._handlePopperPlacementChange(data);
          }
        }
      };
      return {
        ...defaultBsPopperConfig,
        ...typeof this._config.popperConfig === "function" ? this._config.popperConfig(defaultBsPopperConfig) : this._config.popperConfig
      };
    }
    _addAttachmentClass(attachment) {
      this.getTipElement().classList.add(`${this._getBasicClassPrefix()}-${this.updateAttachment(attachment)}`);
    }
    _getAttachment(placement) {
      return AttachmentMap[placement.toUpperCase()];
    }
    _setListeners() {
      const triggers = this._config.trigger.split(" ");
      triggers.forEach((trigger) => {
        if (trigger === "click") {
          EventHandler.on(this._element, this.constructor.Event.CLICK, this._config.selector, (event) => this.toggle(event));
        } else if (trigger !== TRIGGER_MANUAL) {
          const eventIn = trigger === TRIGGER_HOVER ? this.constructor.Event.MOUSEENTER : this.constructor.Event.FOCUSIN;
          const eventOut = trigger === TRIGGER_HOVER ? this.constructor.Event.MOUSELEAVE : this.constructor.Event.FOCUSOUT;
          EventHandler.on(this._element, eventIn, this._config.selector, (event) => this._enter(event));
          EventHandler.on(this._element, eventOut, this._config.selector, (event) => this._leave(event));
        }
      });
      this._hideModalHandler = () => {
        if (this._element) {
          this.hide();
        }
      };
      EventHandler.on(this._element.closest(SELECTOR_MODAL), EVENT_MODAL_HIDE, this._hideModalHandler);
      if (this._config.selector) {
        this._config = {
          ...this._config,
          trigger: "manual",
          selector: ""
        };
      } else {
        this._fixTitle();
      }
    }
    _fixTitle() {
      const title = this._element.getAttribute("title");
      const originalTitleType = typeof this._element.getAttribute("data-bs-original-title");
      if (title || originalTitleType !== "string") {
        this._element.setAttribute("data-bs-original-title", title || "");
        if (title && !this._element.getAttribute("aria-label") && !this._element.textContent) {
          this._element.setAttribute("aria-label", title);
        }
        this._element.setAttribute("title", "");
      }
    }
    _enter(event, context) {
      context = this._initializeOnDelegatedTarget(event, context);
      if (event) {
        context._activeTrigger[event.type === "focusin" ? TRIGGER_FOCUS : TRIGGER_HOVER] = true;
      }
      if (context.getTipElement().classList.contains(CLASS_NAME_SHOW$2) || context._hoverState === HOVER_STATE_SHOW) {
        context._hoverState = HOVER_STATE_SHOW;
        return;
      }
      clearTimeout(context._timeout);
      context._hoverState = HOVER_STATE_SHOW;
      if (!context._config.delay || !context._config.delay.show) {
        context.show();
        return;
      }
      context._timeout = setTimeout(() => {
        if (context._hoverState === HOVER_STATE_SHOW) {
          context.show();
        }
      }, context._config.delay.show);
    }
    _leave(event, context) {
      context = this._initializeOnDelegatedTarget(event, context);
      if (event) {
        context._activeTrigger[event.type === "focusout" ? TRIGGER_FOCUS : TRIGGER_HOVER] = context._element.contains(event.relatedTarget);
      }
      if (context._isWithActiveTrigger()) {
        return;
      }
      clearTimeout(context._timeout);
      context._hoverState = HOVER_STATE_OUT;
      if (!context._config.delay || !context._config.delay.hide) {
        context.hide();
        return;
      }
      context._timeout = setTimeout(() => {
        if (context._hoverState === HOVER_STATE_OUT) {
          context.hide();
        }
      }, context._config.delay.hide);
    }
    _isWithActiveTrigger() {
      for (const trigger in this._activeTrigger) {
        if (this._activeTrigger[trigger]) {
          return true;
        }
      }
      return false;
    }
    _getConfig(config) {
      const dataAttributes = Manipulator.getDataAttributes(this._element);
      Object.keys(dataAttributes).forEach((dataAttr) => {
        if (DISALLOWED_ATTRIBUTES.has(dataAttr)) {
          delete dataAttributes[dataAttr];
        }
      });
      config = {
        ...this.constructor.Default,
        ...dataAttributes,
        ...typeof config === "object" && config ? config : {}
      };
      config.container = config.container === false ? document.body : getElement(config.container);
      if (typeof config.delay === "number") {
        config.delay = {
          show: config.delay,
          hide: config.delay
        };
      }
      if (typeof config.title === "number") {
        config.title = config.title.toString();
      }
      if (typeof config.content === "number") {
        config.content = config.content.toString();
      }
      typeCheckConfig(NAME$4, config, this.constructor.DefaultType);
      if (config.sanitize) {
        config.template = sanitizeHtml(config.template, config.allowList, config.sanitizeFn);
      }
      return config;
    }
    _getDelegateConfig() {
      const config = {};
      for (const key in this._config) {
        if (this.constructor.Default[key] !== this._config[key]) {
          config[key] = this._config[key];
        }
      }
      return config;
    }
    _cleanTipClass() {
      const tip = this.getTipElement();
      const basicClassPrefixRegex = new RegExp(`(^|\\s)${this._getBasicClassPrefix()}\\S+`, "g");
      const tabClass = tip.getAttribute("class").match(basicClassPrefixRegex);
      if (tabClass !== null && tabClass.length > 0) {
        tabClass.map((token) => token.trim()).forEach((tClass) => tip.classList.remove(tClass));
      }
    }
    _getBasicClassPrefix() {
      return CLASS_PREFIX$1;
    }
    _handlePopperPlacementChange(popperData) {
      const {
        state
      } = popperData;
      if (!state) {
        return;
      }
      this.tip = state.elements.popper;
      this._cleanTipClass();
      this._addAttachmentClass(this._getAttachment(state.placement));
    }
    _disposePopper() {
      if (this._popper) {
        this._popper.destroy();
        this._popper = null;
      }
    }
    static jQueryInterface(config) {
      return this.each(function() {
        const data = Tooltip.getOrCreateInstance(this, config);
        if (typeof config === "string") {
          if (typeof data[config] === "undefined") {
            throw new TypeError(`No method named "${config}"`);
          }
          data[config]();
        }
      });
    }
  };
  defineJQueryPlugin(Tooltip);
  var NAME$3 = "popover";
  var DATA_KEY$3 = "bs.popover";
  var EVENT_KEY$3 = `.${DATA_KEY$3}`;
  var CLASS_PREFIX = "bs-popover";
  var Default$2 = {
    ...Tooltip.Default,
    placement: "right",
    offset: [0, 8],
    trigger: "click",
    content: "",
    template: '<div class="popover" role="tooltip"><div class="popover-arrow"></div><h3 class="popover-header"></h3><div class="popover-body"></div></div>'
  };
  var DefaultType$2 = {
    ...Tooltip.DefaultType,
    content: "(string|element|function)"
  };
  var Event$1 = {
    HIDE: `hide${EVENT_KEY$3}`,
    HIDDEN: `hidden${EVENT_KEY$3}`,
    SHOW: `show${EVENT_KEY$3}`,
    SHOWN: `shown${EVENT_KEY$3}`,
    INSERTED: `inserted${EVENT_KEY$3}`,
    CLICK: `click${EVENT_KEY$3}`,
    FOCUSIN: `focusin${EVENT_KEY$3}`,
    FOCUSOUT: `focusout${EVENT_KEY$3}`,
    MOUSEENTER: `mouseenter${EVENT_KEY$3}`,
    MOUSELEAVE: `mouseleave${EVENT_KEY$3}`
  };
  var SELECTOR_TITLE = ".popover-header";
  var SELECTOR_CONTENT = ".popover-body";
  var Popover = class extends Tooltip {
    static get Default() {
      return Default$2;
    }
    static get NAME() {
      return NAME$3;
    }
    static get Event() {
      return Event$1;
    }
    static get DefaultType() {
      return DefaultType$2;
    }
    isWithContent() {
      return this.getTitle() || this._getContent();
    }
    setContent(tip) {
      this._sanitizeAndSetContent(tip, this.getTitle(), SELECTOR_TITLE);
      this._sanitizeAndSetContent(tip, this._getContent(), SELECTOR_CONTENT);
    }
    _getContent() {
      return this._resolvePossibleFunction(this._config.content);
    }
    _getBasicClassPrefix() {
      return CLASS_PREFIX;
    }
    static jQueryInterface(config) {
      return this.each(function() {
        const data = Popover.getOrCreateInstance(this, config);
        if (typeof config === "string") {
          if (typeof data[config] === "undefined") {
            throw new TypeError(`No method named "${config}"`);
          }
          data[config]();
        }
      });
    }
  };
  defineJQueryPlugin(Popover);
  var NAME$2 = "scrollspy";
  var DATA_KEY$2 = "bs.scrollspy";
  var EVENT_KEY$2 = `.${DATA_KEY$2}`;
  var DATA_API_KEY$1 = ".data-api";
  var Default$1 = {
    offset: 10,
    method: "auto",
    target: ""
  };
  var DefaultType$1 = {
    offset: "number",
    method: "string",
    target: "(string|element)"
  };
  var EVENT_ACTIVATE = `activate${EVENT_KEY$2}`;
  var EVENT_SCROLL = `scroll${EVENT_KEY$2}`;
  var EVENT_LOAD_DATA_API = `load${EVENT_KEY$2}${DATA_API_KEY$1}`;
  var CLASS_NAME_DROPDOWN_ITEM = "dropdown-item";
  var CLASS_NAME_ACTIVE$1 = "active";
  var SELECTOR_DATA_SPY = '[data-bs-spy="scroll"]';
  var SELECTOR_NAV_LIST_GROUP$1 = ".nav, .list-group";
  var SELECTOR_NAV_LINKS = ".nav-link";
  var SELECTOR_NAV_ITEMS = ".nav-item";
  var SELECTOR_LIST_ITEMS = ".list-group-item";
  var SELECTOR_LINK_ITEMS = `${SELECTOR_NAV_LINKS}, ${SELECTOR_LIST_ITEMS}, .${CLASS_NAME_DROPDOWN_ITEM}`;
  var SELECTOR_DROPDOWN$1 = ".dropdown";
  var SELECTOR_DROPDOWN_TOGGLE$1 = ".dropdown-toggle";
  var METHOD_OFFSET = "offset";
  var METHOD_POSITION = "position";
  var ScrollSpy = class extends BaseComponent {
    constructor(element, config) {
      super(element);
      this._scrollElement = this._element.tagName === "BODY" ? window : this._element;
      this._config = this._getConfig(config);
      this._offsets = [];
      this._targets = [];
      this._activeTarget = null;
      this._scrollHeight = 0;
      EventHandler.on(this._scrollElement, EVENT_SCROLL, () => this._process());
      this.refresh();
      this._process();
    }
    static get Default() {
      return Default$1;
    }
    static get NAME() {
      return NAME$2;
    }
    refresh() {
      const autoMethod = this._scrollElement === this._scrollElement.window ? METHOD_OFFSET : METHOD_POSITION;
      const offsetMethod = this._config.method === "auto" ? autoMethod : this._config.method;
      const offsetBase = offsetMethod === METHOD_POSITION ? this._getScrollTop() : 0;
      this._offsets = [];
      this._targets = [];
      this._scrollHeight = this._getScrollHeight();
      const targets = SelectorEngine.find(SELECTOR_LINK_ITEMS, this._config.target);
      targets.map((element) => {
        const targetSelector = getSelectorFromElement(element);
        const target = targetSelector ? SelectorEngine.findOne(targetSelector) : null;
        if (target) {
          const targetBCR = target.getBoundingClientRect();
          if (targetBCR.width || targetBCR.height) {
            return [Manipulator[offsetMethod](target).top + offsetBase, targetSelector];
          }
        }
        return null;
      }).filter((item) => item).sort((a2, b2) => a2[0] - b2[0]).forEach((item) => {
        this._offsets.push(item[0]);
        this._targets.push(item[1]);
      });
    }
    dispose() {
      EventHandler.off(this._scrollElement, EVENT_KEY$2);
      super.dispose();
    }
    _getConfig(config) {
      config = {
        ...Default$1,
        ...Manipulator.getDataAttributes(this._element),
        ...typeof config === "object" && config ? config : {}
      };
      config.target = getElement(config.target) || document.documentElement;
      typeCheckConfig(NAME$2, config, DefaultType$1);
      return config;
    }
    _getScrollTop() {
      return this._scrollElement === window ? this._scrollElement.pageYOffset : this._scrollElement.scrollTop;
    }
    _getScrollHeight() {
      return this._scrollElement.scrollHeight || Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
    }
    _getOffsetHeight() {
      return this._scrollElement === window ? window.innerHeight : this._scrollElement.getBoundingClientRect().height;
    }
    _process() {
      const scrollTop = this._getScrollTop() + this._config.offset;
      const scrollHeight = this._getScrollHeight();
      const maxScroll = this._config.offset + scrollHeight - this._getOffsetHeight();
      if (this._scrollHeight !== scrollHeight) {
        this.refresh();
      }
      if (scrollTop >= maxScroll) {
        const target = this._targets[this._targets.length - 1];
        if (this._activeTarget !== target) {
          this._activate(target);
        }
        return;
      }
      if (this._activeTarget && scrollTop < this._offsets[0] && this._offsets[0] > 0) {
        this._activeTarget = null;
        this._clear();
        return;
      }
      for (let i2 = this._offsets.length; i2--; ) {
        const isActiveTarget = this._activeTarget !== this._targets[i2] && scrollTop >= this._offsets[i2] && (typeof this._offsets[i2 + 1] === "undefined" || scrollTop < this._offsets[i2 + 1]);
        if (isActiveTarget) {
          this._activate(this._targets[i2]);
        }
      }
    }
    _activate(target) {
      this._activeTarget = target;
      this._clear();
      const queries = SELECTOR_LINK_ITEMS.split(",").map((selector) => `${selector}[data-bs-target="${target}"],${selector}[href="${target}"]`);
      const link = SelectorEngine.findOne(queries.join(","), this._config.target);
      link.classList.add(CLASS_NAME_ACTIVE$1);
      if (link.classList.contains(CLASS_NAME_DROPDOWN_ITEM)) {
        SelectorEngine.findOne(SELECTOR_DROPDOWN_TOGGLE$1, link.closest(SELECTOR_DROPDOWN$1)).classList.add(CLASS_NAME_ACTIVE$1);
      } else {
        SelectorEngine.parents(link, SELECTOR_NAV_LIST_GROUP$1).forEach((listGroup) => {
          SelectorEngine.prev(listGroup, `${SELECTOR_NAV_LINKS}, ${SELECTOR_LIST_ITEMS}`).forEach((item) => item.classList.add(CLASS_NAME_ACTIVE$1));
          SelectorEngine.prev(listGroup, SELECTOR_NAV_ITEMS).forEach((navItem) => {
            SelectorEngine.children(navItem, SELECTOR_NAV_LINKS).forEach((item) => item.classList.add(CLASS_NAME_ACTIVE$1));
          });
        });
      }
      EventHandler.trigger(this._scrollElement, EVENT_ACTIVATE, {
        relatedTarget: target
      });
    }
    _clear() {
      SelectorEngine.find(SELECTOR_LINK_ITEMS, this._config.target).filter((node) => node.classList.contains(CLASS_NAME_ACTIVE$1)).forEach((node) => node.classList.remove(CLASS_NAME_ACTIVE$1));
    }
    static jQueryInterface(config) {
      return this.each(function() {
        const data = ScrollSpy.getOrCreateInstance(this, config);
        if (typeof config !== "string") {
          return;
        }
        if (typeof data[config] === "undefined") {
          throw new TypeError(`No method named "${config}"`);
        }
        data[config]();
      });
    }
  };
  EventHandler.on(window, EVENT_LOAD_DATA_API, () => {
    SelectorEngine.find(SELECTOR_DATA_SPY).forEach((spy) => new ScrollSpy(spy));
  });
  defineJQueryPlugin(ScrollSpy);
  var NAME$1 = "tab";
  var DATA_KEY$1 = "bs.tab";
  var EVENT_KEY$1 = `.${DATA_KEY$1}`;
  var DATA_API_KEY = ".data-api";
  var EVENT_HIDE$1 = `hide${EVENT_KEY$1}`;
  var EVENT_HIDDEN$1 = `hidden${EVENT_KEY$1}`;
  var EVENT_SHOW$1 = `show${EVENT_KEY$1}`;
  var EVENT_SHOWN$1 = `shown${EVENT_KEY$1}`;
  var EVENT_CLICK_DATA_API = `click${EVENT_KEY$1}${DATA_API_KEY}`;
  var CLASS_NAME_DROPDOWN_MENU = "dropdown-menu";
  var CLASS_NAME_ACTIVE = "active";
  var CLASS_NAME_FADE$1 = "fade";
  var CLASS_NAME_SHOW$1 = "show";
  var SELECTOR_DROPDOWN = ".dropdown";
  var SELECTOR_NAV_LIST_GROUP = ".nav, .list-group";
  var SELECTOR_ACTIVE = ".active";
  var SELECTOR_ACTIVE_UL = ":scope > li > .active";
  var SELECTOR_DATA_TOGGLE = '[data-bs-toggle="tab"], [data-bs-toggle="pill"], [data-bs-toggle="list"]';
  var SELECTOR_DROPDOWN_TOGGLE = ".dropdown-toggle";
  var SELECTOR_DROPDOWN_ACTIVE_CHILD = ":scope > .dropdown-menu .active";
  var Tab = class extends BaseComponent {
    static get NAME() {
      return NAME$1;
    }
    show() {
      if (this._element.parentNode && this._element.parentNode.nodeType === Node.ELEMENT_NODE && this._element.classList.contains(CLASS_NAME_ACTIVE)) {
        return;
      }
      let previous;
      const target = getElementFromSelector(this._element);
      const listElement = this._element.closest(SELECTOR_NAV_LIST_GROUP);
      if (listElement) {
        const itemSelector = listElement.nodeName === "UL" || listElement.nodeName === "OL" ? SELECTOR_ACTIVE_UL : SELECTOR_ACTIVE;
        previous = SelectorEngine.find(itemSelector, listElement);
        previous = previous[previous.length - 1];
      }
      const hideEvent = previous ? EventHandler.trigger(previous, EVENT_HIDE$1, {
        relatedTarget: this._element
      }) : null;
      const showEvent = EventHandler.trigger(this._element, EVENT_SHOW$1, {
        relatedTarget: previous
      });
      if (showEvent.defaultPrevented || hideEvent !== null && hideEvent.defaultPrevented) {
        return;
      }
      this._activate(this._element, listElement);
      const complete = () => {
        EventHandler.trigger(previous, EVENT_HIDDEN$1, {
          relatedTarget: this._element
        });
        EventHandler.trigger(this._element, EVENT_SHOWN$1, {
          relatedTarget: previous
        });
      };
      if (target) {
        this._activate(target, target.parentNode, complete);
      } else {
        complete();
      }
    }
    _activate(element, container, callback2) {
      const activeElements = container && (container.nodeName === "UL" || container.nodeName === "OL") ? SelectorEngine.find(SELECTOR_ACTIVE_UL, container) : SelectorEngine.children(container, SELECTOR_ACTIVE);
      const active = activeElements[0];
      const isTransitioning = callback2 && active && active.classList.contains(CLASS_NAME_FADE$1);
      const complete = () => this._transitionComplete(element, active, callback2);
      if (active && isTransitioning) {
        active.classList.remove(CLASS_NAME_SHOW$1);
        this._queueCallback(complete, element, true);
      } else {
        complete();
      }
    }
    _transitionComplete(element, active, callback2) {
      if (active) {
        active.classList.remove(CLASS_NAME_ACTIVE);
        const dropdownChild = SelectorEngine.findOne(SELECTOR_DROPDOWN_ACTIVE_CHILD, active.parentNode);
        if (dropdownChild) {
          dropdownChild.classList.remove(CLASS_NAME_ACTIVE);
        }
        if (active.getAttribute("role") === "tab") {
          active.setAttribute("aria-selected", false);
        }
      }
      element.classList.add(CLASS_NAME_ACTIVE);
      if (element.getAttribute("role") === "tab") {
        element.setAttribute("aria-selected", true);
      }
      reflow(element);
      if (element.classList.contains(CLASS_NAME_FADE$1)) {
        element.classList.add(CLASS_NAME_SHOW$1);
      }
      let parent = element.parentNode;
      if (parent && parent.nodeName === "LI") {
        parent = parent.parentNode;
      }
      if (parent && parent.classList.contains(CLASS_NAME_DROPDOWN_MENU)) {
        const dropdownElement = element.closest(SELECTOR_DROPDOWN);
        if (dropdownElement) {
          SelectorEngine.find(SELECTOR_DROPDOWN_TOGGLE, dropdownElement).forEach((dropdown) => dropdown.classList.add(CLASS_NAME_ACTIVE));
        }
        element.setAttribute("aria-expanded", true);
      }
      if (callback2) {
        callback2();
      }
    }
    static jQueryInterface(config) {
      return this.each(function() {
        const data = Tab.getOrCreateInstance(this);
        if (typeof config === "string") {
          if (typeof data[config] === "undefined") {
            throw new TypeError(`No method named "${config}"`);
          }
          data[config]();
        }
      });
    }
  };
  EventHandler.on(document, EVENT_CLICK_DATA_API, SELECTOR_DATA_TOGGLE, function(event) {
    if (["A", "AREA"].includes(this.tagName)) {
      event.preventDefault();
    }
    if (isDisabled(this)) {
      return;
    }
    const data = Tab.getOrCreateInstance(this);
    data.show();
  });
  defineJQueryPlugin(Tab);
  var NAME = "toast";
  var DATA_KEY = "bs.toast";
  var EVENT_KEY = `.${DATA_KEY}`;
  var EVENT_MOUSEOVER = `mouseover${EVENT_KEY}`;
  var EVENT_MOUSEOUT = `mouseout${EVENT_KEY}`;
  var EVENT_FOCUSIN = `focusin${EVENT_KEY}`;
  var EVENT_FOCUSOUT = `focusout${EVENT_KEY}`;
  var EVENT_HIDE = `hide${EVENT_KEY}`;
  var EVENT_HIDDEN = `hidden${EVENT_KEY}`;
  var EVENT_SHOW = `show${EVENT_KEY}`;
  var EVENT_SHOWN = `shown${EVENT_KEY}`;
  var CLASS_NAME_FADE = "fade";
  var CLASS_NAME_HIDE = "hide";
  var CLASS_NAME_SHOW = "show";
  var CLASS_NAME_SHOWING = "showing";
  var DefaultType = {
    animation: "boolean",
    autohide: "boolean",
    delay: "number"
  };
  var Default = {
    animation: true,
    autohide: true,
    delay: 5e3
  };
  var Toast = class extends BaseComponent {
    constructor(element, config) {
      super(element);
      this._config = this._getConfig(config);
      this._timeout = null;
      this._hasMouseInteraction = false;
      this._hasKeyboardInteraction = false;
      this._setListeners();
    }
    static get DefaultType() {
      return DefaultType;
    }
    static get Default() {
      return Default;
    }
    static get NAME() {
      return NAME;
    }
    show() {
      const showEvent = EventHandler.trigger(this._element, EVENT_SHOW);
      if (showEvent.defaultPrevented) {
        return;
      }
      this._clearTimeout();
      if (this._config.animation) {
        this._element.classList.add(CLASS_NAME_FADE);
      }
      const complete = () => {
        this._element.classList.remove(CLASS_NAME_SHOWING);
        EventHandler.trigger(this._element, EVENT_SHOWN);
        this._maybeScheduleHide();
      };
      this._element.classList.remove(CLASS_NAME_HIDE);
      reflow(this._element);
      this._element.classList.add(CLASS_NAME_SHOW);
      this._element.classList.add(CLASS_NAME_SHOWING);
      this._queueCallback(complete, this._element, this._config.animation);
    }
    hide() {
      if (!this._element.classList.contains(CLASS_NAME_SHOW)) {
        return;
      }
      const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE);
      if (hideEvent.defaultPrevented) {
        return;
      }
      const complete = () => {
        this._element.classList.add(CLASS_NAME_HIDE);
        this._element.classList.remove(CLASS_NAME_SHOWING);
        this._element.classList.remove(CLASS_NAME_SHOW);
        EventHandler.trigger(this._element, EVENT_HIDDEN);
      };
      this._element.classList.add(CLASS_NAME_SHOWING);
      this._queueCallback(complete, this._element, this._config.animation);
    }
    dispose() {
      this._clearTimeout();
      if (this._element.classList.contains(CLASS_NAME_SHOW)) {
        this._element.classList.remove(CLASS_NAME_SHOW);
      }
      super.dispose();
    }
    _getConfig(config) {
      config = {
        ...Default,
        ...Manipulator.getDataAttributes(this._element),
        ...typeof config === "object" && config ? config : {}
      };
      typeCheckConfig(NAME, config, this.constructor.DefaultType);
      return config;
    }
    _maybeScheduleHide() {
      if (!this._config.autohide) {
        return;
      }
      if (this._hasMouseInteraction || this._hasKeyboardInteraction) {
        return;
      }
      this._timeout = setTimeout(() => {
        this.hide();
      }, this._config.delay);
    }
    _onInteraction(event, isInteracting) {
      switch (event.type) {
        case "mouseover":
        case "mouseout":
          this._hasMouseInteraction = isInteracting;
          break;
        case "focusin":
        case "focusout":
          this._hasKeyboardInteraction = isInteracting;
          break;
      }
      if (isInteracting) {
        this._clearTimeout();
        return;
      }
      const nextElement = event.relatedTarget;
      if (this._element === nextElement || this._element.contains(nextElement)) {
        return;
      }
      this._maybeScheduleHide();
    }
    _setListeners() {
      EventHandler.on(this._element, EVENT_MOUSEOVER, (event) => this._onInteraction(event, true));
      EventHandler.on(this._element, EVENT_MOUSEOUT, (event) => this._onInteraction(event, false));
      EventHandler.on(this._element, EVENT_FOCUSIN, (event) => this._onInteraction(event, true));
      EventHandler.on(this._element, EVENT_FOCUSOUT, (event) => this._onInteraction(event, false));
    }
    _clearTimeout() {
      clearTimeout(this._timeout);
      this._timeout = null;
    }
    static jQueryInterface(config) {
      return this.each(function() {
        const data = Toast.getOrCreateInstance(this, config);
        if (typeof config === "string") {
          if (typeof data[config] === "undefined") {
            throw new TypeError(`No method named "${config}"`);
          }
          data[config](this);
        }
      });
    }
  };
  enableDismissTrigger(Toast);
  defineJQueryPlugin(Toast);

  // ../../node_modules/trix/dist/trix.esm.min.js
  var t = "2.0.10";
  var e = "[data-trix-attachment]";
  var i = { preview: { presentation: "gallery", caption: { name: true, size: true } }, file: { caption: { size: true } } };
  var n = { default: { tagName: "div", parse: false }, quote: { tagName: "blockquote", nestable: true }, heading1: { tagName: "h1", terminal: true, breakOnReturn: true, group: false }, code: { tagName: "pre", terminal: true, text: { plaintext: true } }, bulletList: { tagName: "ul", parse: false }, bullet: { tagName: "li", listAttribute: "bulletList", group: false, nestable: true, test(t2) {
    return r(t2.parentNode) === n[this.listAttribute].tagName;
  } }, numberList: { tagName: "ol", parse: false }, number: { tagName: "li", listAttribute: "numberList", group: false, nestable: true, test(t2) {
    return r(t2.parentNode) === n[this.listAttribute].tagName;
  } }, attachmentGallery: { tagName: "div", exclusive: true, terminal: true, parse: false, group: false } };
  var r = (t2) => {
    var e2;
    return t2 == null || (e2 = t2.tagName) === null || e2 === void 0 ? void 0 : e2.toLowerCase();
  };
  var o = navigator.userAgent.match(/android\s([0-9]+.*Chrome)/i);
  var s = o && parseInt(o[1]);
  var a = { composesExistingText: /Android.*Chrome/.test(navigator.userAgent), recentAndroid: s && s > 12, samsungAndroid: s && navigator.userAgent.match(/Android.*SM-/), forcesObjectResizing: /Trident.*rv:11/.test(navigator.userAgent), supportsInputEvents: typeof InputEvent != "undefined" && ["data", "getTargetRanges", "inputType"].every((t2) => t2 in InputEvent.prototype) };
  var l = { attachFiles: "Attach Files", bold: "Bold", bullets: "Bullets", byte: "Byte", bytes: "Bytes", captionPlaceholder: "Add a caption\u2026", code: "Code", heading1: "Heading", indent: "Increase Level", italic: "Italic", link: "Link", numbers: "Numbers", outdent: "Decrease Level", quote: "Quote", redo: "Redo", remove: "Remove", strike: "Strikethrough", undo: "Undo", unlink: "Unlink", url: "URL", urlPlaceholder: "Enter a URL\u2026", GB: "GB", KB: "KB", MB: "MB", PB: "PB", TB: "TB" };
  var c = [l.bytes, l.KB, l.MB, l.GB, l.TB, l.PB];
  var h = { prefix: "IEC", precision: 2, formatter(t2) {
    switch (t2) {
      case 0:
        return "0 ".concat(l.bytes);
      case 1:
        return "1 ".concat(l.byte);
      default:
        let e2;
        this.prefix === "SI" ? e2 = 1e3 : this.prefix === "IEC" && (e2 = 1024);
        const i2 = Math.floor(Math.log(t2) / Math.log(e2)), n2 = (t2 / Math.pow(e2, i2)).toFixed(this.precision).replace(/0*$/, "").replace(/\.$/, "");
        return "".concat(n2, " ").concat(c[i2]);
    }
  } };
  var u = "\uFEFF";
  var d = "\xA0";
  var g = function(t2) {
    for (const e2 in t2) {
      const i2 = t2[e2];
      this[e2] = i2;
    }
    return this;
  };
  var m = document.documentElement;
  var p = m.matches;
  var f = function(t2) {
    let { onElement: e2, matchingSelector: i2, withCallback: n2, inPhase: r2, preventDefault: o2, times: s2 } = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
    const a2 = e2 || m, l2 = i2, c2 = r2 === "capturing", h3 = function(t3) {
      s2 != null && --s2 == 0 && h3.destroy();
      const e3 = A(t3.target, { matchingSelector: l2 });
      e3 != null && (n2 == null || n2.call(e3, t3, e3), o2 && t3.preventDefault());
    };
    return h3.destroy = () => a2.removeEventListener(t2, h3, c2), a2.addEventListener(t2, h3, c2), h3;
  };
  var b = function(t2) {
    let { onElement: e2, bubbles: i2, cancelable: n2, attributes: r2 } = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
    const o2 = e2 != null ? e2 : m;
    i2 = i2 !== false, n2 = n2 !== false;
    const s2 = document.createEvent("Events");
    return s2.initEvent(t2, i2, n2), r2 != null && g.call(s2, r2), o2.dispatchEvent(s2);
  };
  var v = function(t2, e2) {
    if ((t2 == null ? void 0 : t2.nodeType) === 1)
      return p.call(t2, e2);
  };
  var A = function(t2) {
    let { matchingSelector: e2, untilNode: i2 } = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
    for (; t2 && t2.nodeType !== Node.ELEMENT_NODE; )
      t2 = t2.parentNode;
    if (t2 != null) {
      if (e2 == null)
        return t2;
      if (t2.closest && i2 == null)
        return t2.closest(e2);
      for (; t2 && t2 !== i2; ) {
        if (v(t2, e2))
          return t2;
        t2 = t2.parentNode;
      }
    }
  };
  var x = (t2) => document.activeElement !== t2 && y(t2, document.activeElement);
  var y = function(t2, e2) {
    if (t2 && e2)
      for (; e2; ) {
        if (e2 === t2)
          return true;
        e2 = e2.parentNode;
      }
  };
  var C = function(t2) {
    var e2;
    if ((e2 = t2) === null || e2 === void 0 || !e2.parentNode)
      return;
    let i2 = 0;
    for (t2 = t2.previousSibling; t2; )
      i2++, t2 = t2.previousSibling;
    return i2;
  };
  var R = (t2) => {
    var e2;
    return t2 == null || (e2 = t2.parentNode) === null || e2 === void 0 ? void 0 : e2.removeChild(t2);
  };
  var S = function(t2) {
    let { onlyNodesOfType: e2, usingFilter: i2, expandEntityReferences: n2 } = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
    const r2 = (() => {
      switch (e2) {
        case "element":
          return NodeFilter.SHOW_ELEMENT;
        case "text":
          return NodeFilter.SHOW_TEXT;
        case "comment":
          return NodeFilter.SHOW_COMMENT;
        default:
          return NodeFilter.SHOW_ALL;
      }
    })();
    return document.createTreeWalker(t2, r2, i2 != null ? i2 : null, n2 === true);
  };
  var E = (t2) => {
    var e2;
    return t2 == null || (e2 = t2.tagName) === null || e2 === void 0 ? void 0 : e2.toLowerCase();
  };
  var k = function(t2) {
    let e2, i2, n2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
    typeof t2 == "object" ? (n2 = t2, t2 = n2.tagName) : n2 = { attributes: n2 };
    const r2 = document.createElement(t2);
    if (n2.editable != null && (n2.attributes == null && (n2.attributes = {}), n2.attributes.contenteditable = n2.editable), n2.attributes)
      for (e2 in n2.attributes)
        i2 = n2.attributes[e2], r2.setAttribute(e2, i2);
    if (n2.style)
      for (e2 in n2.style)
        i2 = n2.style[e2], r2.style[e2] = i2;
    if (n2.data)
      for (e2 in n2.data)
        i2 = n2.data[e2], r2.dataset[e2] = i2;
    return n2.className && n2.className.split(" ").forEach((t3) => {
      r2.classList.add(t3);
    }), n2.textContent && (r2.textContent = n2.textContent), n2.childNodes && [].concat(n2.childNodes).forEach((t3) => {
      r2.appendChild(t3);
    }), r2;
  };
  var L;
  var D = function() {
    if (L != null)
      return L;
    L = [];
    for (const t2 in n) {
      const e2 = n[t2];
      e2.tagName && L.push(e2.tagName);
    }
    return L;
  };
  var w = (t2) => B(t2 == null ? void 0 : t2.firstChild);
  var T = function(t2) {
    let { strict: e2 } = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : { strict: true };
    return e2 ? B(t2) : B(t2) || !B(t2.firstChild) && function(t3) {
      return D().includes(E(t3)) && !D().includes(E(t3.firstChild));
    }(t2);
  };
  var B = (t2) => F(t2) && (t2 == null ? void 0 : t2.data) === "block";
  var F = (t2) => (t2 == null ? void 0 : t2.nodeType) === Node.COMMENT_NODE;
  var I = function(t2) {
    let { name: e2 } = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
    if (t2)
      return O(t2) ? t2.data === u ? !e2 || t2.parentNode.dataset.trixCursorTarget === e2 : void 0 : I(t2.firstChild);
  };
  var P = (t2) => v(t2, e);
  var N = (t2) => O(t2) && (t2 == null ? void 0 : t2.data) === "";
  var O = (t2) => (t2 == null ? void 0 : t2.nodeType) === Node.TEXT_NODE;
  var M = { level2Enabled: true, getLevel() {
    return this.level2Enabled && a.supportsInputEvents ? 2 : 0;
  }, pickFiles(t2) {
    const e2 = k("input", { type: "file", multiple: true, hidden: true, id: this.fileInputId });
    e2.addEventListener("change", () => {
      t2(e2.files), R(e2);
    }), R(document.getElementById(this.fileInputId)), document.body.appendChild(e2), e2.click();
  } };
  var j = { removeBlankTableCells: false, tableCellSeparator: " | ", tableRowSeparator: "\n" };
  var W = { bold: { tagName: "strong", inheritable: true, parser(t2) {
    const e2 = window.getComputedStyle(t2);
    return e2.fontWeight === "bold" || e2.fontWeight >= 600;
  } }, italic: { tagName: "em", inheritable: true, parser: (t2) => window.getComputedStyle(t2).fontStyle === "italic" }, href: { groupTagName: "a", parser(t2) {
    const i2 = "a:not(".concat(e, ")"), n2 = t2.closest(i2);
    if (n2)
      return n2.getAttribute("href");
  } }, strike: { tagName: "del", inheritable: true }, frozen: { style: { backgroundColor: "highlight" } } };
  var U = { getDefaultHTML: () => '<div class="trix-button-row">\n      <span class="trix-button-group trix-button-group--text-tools" data-trix-button-group="text-tools">\n        <button type="button" class="trix-button trix-button--icon trix-button--icon-bold" data-trix-attribute="bold" data-trix-key="b" title="'.concat(l.bold, '" tabindex="-1">').concat(l.bold, '</button>\n        <button type="button" class="trix-button trix-button--icon trix-button--icon-italic" data-trix-attribute="italic" data-trix-key="i" title="').concat(l.italic, '" tabindex="-1">').concat(l.italic, '</button>\n        <button type="button" class="trix-button trix-button--icon trix-button--icon-strike" data-trix-attribute="strike" title="').concat(l.strike, '" tabindex="-1">').concat(l.strike, '</button>\n        <button type="button" class="trix-button trix-button--icon trix-button--icon-link" data-trix-attribute="href" data-trix-action="link" data-trix-key="k" title="').concat(l.link, '" tabindex="-1">').concat(l.link, '</button>\n      </span>\n\n      <span class="trix-button-group trix-button-group--block-tools" data-trix-button-group="block-tools">\n        <button type="button" class="trix-button trix-button--icon trix-button--icon-heading-1" data-trix-attribute="heading1" title="').concat(l.heading1, '" tabindex="-1">').concat(l.heading1, '</button>\n        <button type="button" class="trix-button trix-button--icon trix-button--icon-quote" data-trix-attribute="quote" title="').concat(l.quote, '" tabindex="-1">').concat(l.quote, '</button>\n        <button type="button" class="trix-button trix-button--icon trix-button--icon-code" data-trix-attribute="code" title="').concat(l.code, '" tabindex="-1">').concat(l.code, '</button>\n        <button type="button" class="trix-button trix-button--icon trix-button--icon-bullet-list" data-trix-attribute="bullet" title="').concat(l.bullets, '" tabindex="-1">').concat(l.bullets, '</button>\n        <button type="button" class="trix-button trix-button--icon trix-button--icon-number-list" data-trix-attribute="number" title="').concat(l.numbers, '" tabindex="-1">').concat(l.numbers, '</button>\n        <button type="button" class="trix-button trix-button--icon trix-button--icon-decrease-nesting-level" data-trix-action="decreaseNestingLevel" title="').concat(l.outdent, '" tabindex="-1">').concat(l.outdent, '</button>\n        <button type="button" class="trix-button trix-button--icon trix-button--icon-increase-nesting-level" data-trix-action="increaseNestingLevel" title="').concat(l.indent, '" tabindex="-1">').concat(l.indent, '</button>\n      </span>\n\n      <span class="trix-button-group trix-button-group--file-tools" data-trix-button-group="file-tools">\n        <button type="button" class="trix-button trix-button--icon trix-button--icon-attach" data-trix-action="attachFiles" title="').concat(l.attachFiles, '" tabindex="-1">').concat(l.attachFiles, '</button>\n      </span>\n\n      <span class="trix-button-group-spacer"></span>\n\n      <span class="trix-button-group trix-button-group--history-tools" data-trix-button-group="history-tools">\n        <button type="button" class="trix-button trix-button--icon trix-button--icon-undo" data-trix-action="undo" data-trix-key="z" title="').concat(l.undo, '" tabindex="-1">').concat(l.undo, '</button>\n        <button type="button" class="trix-button trix-button--icon trix-button--icon-redo" data-trix-action="redo" data-trix-key="shift+z" title="').concat(l.redo, '" tabindex="-1">').concat(l.redo, '</button>\n      </span>\n    </div>\n\n    <div class="trix-dialogs" data-trix-dialogs>\n      <div class="trix-dialog trix-dialog--link" data-trix-dialog="href" data-trix-dialog-attribute="href">\n        <div class="trix-dialog__link-fields">\n          <input type="url" name="href" class="trix-input trix-input--dialog" placeholder="').concat(l.urlPlaceholder, '" aria-label="').concat(l.url, '" required data-trix-input>\n          <div class="trix-button-group">\n            <input type="button" class="trix-button trix-button--dialog" value="').concat(l.link, '" data-trix-method="setAttribute">\n            <input type="button" class="trix-button trix-button--dialog" value="').concat(l.unlink, '" data-trix-method="removeAttribute">\n          </div>\n        </div>\n      </div>\n    </div>') };
  var q = { interval: 5e3 };
  var V = Object.freeze({ __proto__: null, attachments: i, blockAttributes: n, browser: a, css: { attachment: "attachment", attachmentCaption: "attachment__caption", attachmentCaptionEditor: "attachment__caption-editor", attachmentMetadata: "attachment__metadata", attachmentMetadataContainer: "attachment__metadata-container", attachmentName: "attachment__name", attachmentProgress: "attachment__progress", attachmentSize: "attachment__size", attachmentToolbar: "attachment__toolbar", attachmentGallery: "attachment-gallery" }, fileSize: h, input: M, keyNames: { 8: "backspace", 9: "tab", 13: "return", 27: "escape", 37: "left", 39: "right", 46: "delete", 68: "d", 72: "h", 79: "o" }, lang: l, parser: j, textAttributes: W, toolbar: U, undo: q });
  var z = class {
    static proxyMethod(t2) {
      const { name: e2, toMethod: i2, toProperty: n2, optional: r2 } = _(t2);
      this.prototype[e2] = function() {
        let t3, o2;
        var s2, a2;
        i2 ? o2 = r2 ? (s2 = this[i2]) === null || s2 === void 0 ? void 0 : s2.call(this) : this[i2]() : n2 && (o2 = this[n2]);
        return r2 ? (t3 = (a2 = o2) === null || a2 === void 0 ? void 0 : a2[e2], t3 ? H.call(t3, o2, arguments) : void 0) : (t3 = o2[e2], H.call(t3, o2, arguments));
      };
    }
  };
  var _ = function(t2) {
    const e2 = t2.match(J);
    if (!e2)
      throw new Error("can't parse @proxyMethod expression: ".concat(t2));
    const i2 = { name: e2[4] };
    return e2[2] != null ? i2.toMethod = e2[1] : i2.toProperty = e2[1], e2[3] != null && (i2.optional = true), i2;
  };
  var { apply: H } = Function.prototype;
  var J = new RegExp("^(.+?)(\\(\\))?(\\?)?\\.(.+?)$");
  var K;
  var G;
  var $;
  var X = class extends z {
    static box() {
      let t2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : "";
      return t2 instanceof this ? t2 : this.fromUCS2String(t2 == null ? void 0 : t2.toString());
    }
    static fromUCS2String(t2) {
      return new this(t2, tt(t2));
    }
    static fromCodepoints(t2) {
      return new this(et(t2), t2);
    }
    constructor(t2, e2) {
      super(...arguments), this.ucs2String = t2, this.codepoints = e2, this.length = this.codepoints.length, this.ucs2Length = this.ucs2String.length;
    }
    offsetToUCS2Offset(t2) {
      return et(this.codepoints.slice(0, Math.max(0, t2))).length;
    }
    offsetFromUCS2Offset(t2) {
      return tt(this.ucs2String.slice(0, Math.max(0, t2))).length;
    }
    slice() {
      return this.constructor.fromCodepoints(this.codepoints.slice(...arguments));
    }
    charAt(t2) {
      return this.slice(t2, t2 + 1);
    }
    isEqualTo(t2) {
      return this.constructor.box(t2).ucs2String === this.ucs2String;
    }
    toJSON() {
      return this.ucs2String;
    }
    getCacheKey() {
      return this.ucs2String;
    }
    toString() {
      return this.ucs2String;
    }
  };
  var Y = ((K = Array.from) === null || K === void 0 ? void 0 : K.call(Array, "\u{1F47C}").length) === 1;
  var Q = ((G = " ".codePointAt) === null || G === void 0 ? void 0 : G.call(" ", 0)) != null;
  var Z = (($ = String.fromCodePoint) === null || $ === void 0 ? void 0 : $.call(String, 32, 128124)) === " \u{1F47C}";
  var tt;
  var et;
  tt = Y && Q ? (t2) => Array.from(t2).map((t3) => t3.codePointAt(0)) : function(t2) {
    const e2 = [];
    let i2 = 0;
    const { length: n2 } = t2;
    for (; i2 < n2; ) {
      let r2 = t2.charCodeAt(i2++);
      if (55296 <= r2 && r2 <= 56319 && i2 < n2) {
        const e3 = t2.charCodeAt(i2++);
        (64512 & e3) == 56320 ? r2 = ((1023 & r2) << 10) + (1023 & e3) + 65536 : i2--;
      }
      e2.push(r2);
    }
    return e2;
  }, et = Z ? (t2) => String.fromCodePoint(...Array.from(t2 || [])) : function(t2) {
    return (() => {
      const e2 = [];
      return Array.from(t2).forEach((t3) => {
        let i2 = "";
        t3 > 65535 && (t3 -= 65536, i2 += String.fromCharCode(t3 >>> 10 & 1023 | 55296), t3 = 56320 | 1023 & t3), e2.push(i2 + String.fromCharCode(t3));
      }), e2;
    })().join("");
  };
  var it = 0;
  var nt = class extends z {
    static fromJSONString(t2) {
      return this.fromJSON(JSON.parse(t2));
    }
    constructor() {
      super(...arguments), this.id = ++it;
    }
    hasSameConstructorAs(t2) {
      return this.constructor === (t2 == null ? void 0 : t2.constructor);
    }
    isEqualTo(t2) {
      return this === t2;
    }
    inspect() {
      const t2 = [], e2 = this.contentsForInspection() || {};
      for (const i2 in e2) {
        const n2 = e2[i2];
        t2.push("".concat(i2, "=").concat(n2));
      }
      return "#<".concat(this.constructor.name, ":").concat(this.id).concat(t2.length ? " ".concat(t2.join(", ")) : "", ">");
    }
    contentsForInspection() {
    }
    toJSONString() {
      return JSON.stringify(this);
    }
    toUTF16String() {
      return X.box(this);
    }
    getCacheKey() {
      return this.id.toString();
    }
  };
  var rt = function() {
    let t2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : [], e2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : [];
    if (t2.length !== e2.length)
      return false;
    for (let i2 = 0; i2 < t2.length; i2++) {
      if (t2[i2] !== e2[i2])
        return false;
    }
    return true;
  };
  var ot = function(t2) {
    const e2 = t2.slice(0);
    for (var i2 = arguments.length, n2 = new Array(i2 > 1 ? i2 - 1 : 0), r2 = 1; r2 < i2; r2++)
      n2[r2 - 1] = arguments[r2];
    return e2.splice(...n2), e2;
  };
  var st = /[\u05BE\u05C0\u05C3\u05D0-\u05EA\u05F0-\u05F4\u061B\u061F\u0621-\u063A\u0640-\u064A\u066D\u0671-\u06B7\u06BA-\u06BE\u06C0-\u06CE\u06D0-\u06D5\u06E5\u06E6\u200F\u202B\u202E\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE72\uFE74\uFE76-\uFEFC]/;
  var at = function() {
    const t2 = k("input", { dir: "auto", name: "x", dirName: "x.dir" }), e2 = k("textarea", { dir: "auto", name: "y", dirName: "y.dir" }), i2 = k("form");
    i2.appendChild(t2), i2.appendChild(e2);
    const n2 = function() {
      try {
        return new FormData(i2).has(e2.dirName);
      } catch (t3) {
        return false;
      }
    }(), r2 = function() {
      try {
        return t2.matches(":dir(ltr),:dir(rtl)");
      } catch (t3) {
        return false;
      }
    }();
    return n2 ? function(t3) {
      return e2.value = t3, new FormData(i2).get(e2.dirName);
    } : r2 ? function(e3) {
      return t2.value = e3, t2.matches(":dir(rtl)") ? "rtl" : "ltr";
    } : function(t3) {
      const e3 = t3.trim().charAt(0);
      return st.test(e3) ? "rtl" : "ltr";
    };
  }();
  var lt = null;
  var ct = null;
  var ht = null;
  var ut = null;
  var dt = () => (lt || (lt = ft().concat(mt())), lt);
  var gt = (t2) => n[t2];
  var mt = () => (ct || (ct = Object.keys(n)), ct);
  var pt = (t2) => W[t2];
  var ft = () => (ht || (ht = Object.keys(W)), ht);
  var bt = function(t2, e2) {
    vt(t2).textContent = e2.replace(/%t/g, t2);
  };
  var vt = function(t2) {
    const e2 = document.createElement("style");
    e2.setAttribute("type", "text/css"), e2.setAttribute("data-tag-name", t2.toLowerCase());
    const i2 = At();
    return i2 && e2.setAttribute("nonce", i2), document.head.insertBefore(e2, document.head.firstChild), e2;
  };
  var At = function() {
    const t2 = xt("trix-csp-nonce") || xt("csp-nonce");
    if (t2)
      return t2.getAttribute("content");
  };
  var xt = (t2) => document.head.querySelector("meta[name=".concat(t2, "]"));
  var yt = { "application/x-trix-feature-detection": "test" };
  var Ct = function(t2) {
    const e2 = t2.getData("text/plain"), i2 = t2.getData("text/html");
    if (!e2 || !i2)
      return e2 == null ? void 0 : e2.length;
    {
      const { body: t3 } = new DOMParser().parseFromString(i2, "text/html");
      if (t3.textContent === e2)
        return !t3.querySelector("*");
    }
  };
  var Rt = /Mac|^iP/.test(navigator.platform) ? (t2) => t2.metaKey : (t2) => t2.ctrlKey;
  var St = (t2) => setTimeout(t2, 1);
  var Et = function() {
    let t2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
    const e2 = {};
    for (const i2 in t2) {
      const n2 = t2[i2];
      e2[i2] = n2;
    }
    return e2;
  };
  var kt = function() {
    let t2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}, e2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
    if (Object.keys(t2).length !== Object.keys(e2).length)
      return false;
    for (const i2 in t2) {
      if (t2[i2] !== e2[i2])
        return false;
    }
    return true;
  };
  var Lt = function(t2) {
    if (t2 != null)
      return Array.isArray(t2) || (t2 = [t2, t2]), [Tt(t2[0]), Tt(t2[1] != null ? t2[1] : t2[0])];
  };
  var Dt = function(t2) {
    if (t2 == null)
      return;
    const [e2, i2] = Lt(t2);
    return Bt(e2, i2);
  };
  var wt = function(t2, e2) {
    if (t2 == null || e2 == null)
      return;
    const [i2, n2] = Lt(t2), [r2, o2] = Lt(e2);
    return Bt(i2, r2) && Bt(n2, o2);
  };
  var Tt = function(t2) {
    return typeof t2 == "number" ? t2 : Et(t2);
  };
  var Bt = function(t2, e2) {
    return typeof t2 == "number" ? t2 === e2 : kt(t2, e2);
  };
  var Ft = class extends z {
    constructor() {
      super(...arguments), this.update = this.update.bind(this), this.selectionManagers = [];
    }
    start() {
      this.started || (this.started = true, document.addEventListener("selectionchange", this.update, true));
    }
    stop() {
      if (this.started)
        return this.started = false, document.removeEventListener("selectionchange", this.update, true);
    }
    registerSelectionManager(t2) {
      if (!this.selectionManagers.includes(t2))
        return this.selectionManagers.push(t2), this.start();
    }
    unregisterSelectionManager(t2) {
      if (this.selectionManagers = this.selectionManagers.filter((e2) => e2 !== t2), this.selectionManagers.length === 0)
        return this.stop();
    }
    notifySelectionManagersOfSelectionChange() {
      return this.selectionManagers.map((t2) => t2.selectionDidChange());
    }
    update() {
      this.notifySelectionManagersOfSelectionChange();
    }
    reset() {
      this.update();
    }
  };
  var It = new Ft();
  var Pt = function() {
    const t2 = window.getSelection();
    if (t2.rangeCount > 0)
      return t2;
  };
  var Nt = function() {
    var t2;
    const e2 = (t2 = Pt()) === null || t2 === void 0 ? void 0 : t2.getRangeAt(0);
    if (e2 && !Mt(e2))
      return e2;
  };
  var Ot = function(t2) {
    const e2 = window.getSelection();
    return e2.removeAllRanges(), e2.addRange(t2), It.update();
  };
  var Mt = (t2) => jt(t2.startContainer) || jt(t2.endContainer);
  var jt = (t2) => !Object.getPrototypeOf(t2);
  var Wt = (t2) => t2.replace(new RegExp("".concat(u), "g"), "").replace(new RegExp("".concat(d), "g"), " ");
  var Ut = new RegExp("[^\\S".concat(d, "]"));
  var qt = (t2) => t2.replace(new RegExp("".concat(Ut.source), "g"), " ").replace(/\ {2,}/g, " ");
  var Vt = function(t2, e2) {
    if (t2.isEqualTo(e2))
      return ["", ""];
    const i2 = zt(t2, e2), { length: n2 } = i2.utf16String;
    let r2;
    if (n2) {
      const { offset: o2 } = i2, s2 = t2.codepoints.slice(0, o2).concat(t2.codepoints.slice(o2 + n2));
      r2 = zt(e2, X.fromCodepoints(s2));
    } else
      r2 = zt(e2, t2);
    return [i2.utf16String.toString(), r2.utf16String.toString()];
  };
  var zt = function(t2, e2) {
    let i2 = 0, n2 = t2.length, r2 = e2.length;
    for (; i2 < n2 && t2.charAt(i2).isEqualTo(e2.charAt(i2)); )
      i2++;
    for (; n2 > i2 + 1 && t2.charAt(n2 - 1).isEqualTo(e2.charAt(r2 - 1)); )
      n2--, r2--;
    return { utf16String: t2.slice(i2, n2), offset: i2 };
  };
  var _t = class extends nt {
    static fromCommonAttributesOfObjects() {
      let t2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : [];
      if (!t2.length)
        return new this();
      let e2 = Gt(t2[0]), i2 = e2.getKeys();
      return t2.slice(1).forEach((t3) => {
        i2 = e2.getKeysCommonToHash(Gt(t3)), e2 = e2.slice(i2);
      }), e2;
    }
    static box(t2) {
      return Gt(t2);
    }
    constructor() {
      let t2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
      super(...arguments), this.values = Kt(t2);
    }
    add(t2, e2) {
      return this.merge(Ht(t2, e2));
    }
    remove(t2) {
      return new _t(Kt(this.values, t2));
    }
    get(t2) {
      return this.values[t2];
    }
    has(t2) {
      return t2 in this.values;
    }
    merge(t2) {
      return new _t(Jt(this.values, $t(t2)));
    }
    slice(t2) {
      const e2 = {};
      return Array.from(t2).forEach((t3) => {
        this.has(t3) && (e2[t3] = this.values[t3]);
      }), new _t(e2);
    }
    getKeys() {
      return Object.keys(this.values);
    }
    getKeysCommonToHash(t2) {
      return t2 = Gt(t2), this.getKeys().filter((e2) => this.values[e2] === t2.values[e2]);
    }
    isEqualTo(t2) {
      return rt(this.toArray(), Gt(t2).toArray());
    }
    isEmpty() {
      return this.getKeys().length === 0;
    }
    toArray() {
      if (!this.array) {
        const t2 = [];
        for (const e2 in this.values) {
          const i2 = this.values[e2];
          t2.push(t2.push(e2, i2));
        }
        this.array = t2.slice(0);
      }
      return this.array;
    }
    toObject() {
      return Kt(this.values);
    }
    toJSON() {
      return this.toObject();
    }
    contentsForInspection() {
      return { values: JSON.stringify(this.values) };
    }
  };
  var Ht = function(t2, e2) {
    const i2 = {};
    return i2[t2] = e2, i2;
  };
  var Jt = function(t2, e2) {
    const i2 = Kt(t2);
    for (const t3 in e2) {
      const n2 = e2[t3];
      i2[t3] = n2;
    }
    return i2;
  };
  var Kt = function(t2, e2) {
    const i2 = {};
    return Object.keys(t2).sort().forEach((n2) => {
      n2 !== e2 && (i2[n2] = t2[n2]);
    }), i2;
  };
  var Gt = function(t2) {
    return t2 instanceof _t ? t2 : new _t(t2);
  };
  var $t = function(t2) {
    return t2 instanceof _t ? t2.values : t2;
  };
  var Xt = class {
    static groupObjects() {
      let t2, e2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : [], { depth: i2, asTree: n2 } = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
      n2 && i2 == null && (i2 = 0);
      const r2 = [];
      return Array.from(e2).forEach((e3) => {
        var o2;
        if (t2) {
          var s2, a2, l2;
          if ((s2 = e3.canBeGrouped) !== null && s2 !== void 0 && s2.call(e3, i2) && (a2 = (l2 = t2[t2.length - 1]).canBeGroupedWith) !== null && a2 !== void 0 && a2.call(l2, e3, i2))
            return void t2.push(e3);
          r2.push(new this(t2, { depth: i2, asTree: n2 })), t2 = null;
        }
        (o2 = e3.canBeGrouped) !== null && o2 !== void 0 && o2.call(e3, i2) ? t2 = [e3] : r2.push(e3);
      }), t2 && r2.push(new this(t2, { depth: i2, asTree: n2 })), r2;
    }
    constructor() {
      let t2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : [], { depth: e2, asTree: i2 } = arguments.length > 1 ? arguments[1] : void 0;
      this.objects = t2, i2 && (this.depth = e2, this.objects = this.constructor.groupObjects(this.objects, { asTree: i2, depth: this.depth + 1 }));
    }
    getObjects() {
      return this.objects;
    }
    getDepth() {
      return this.depth;
    }
    getCacheKey() {
      const t2 = ["objectGroup"];
      return Array.from(this.getObjects()).forEach((e2) => {
        t2.push(e2.getCacheKey());
      }), t2.join("/");
    }
  };
  var Yt = class extends z {
    constructor() {
      let t2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : [];
      super(...arguments), this.objects = {}, Array.from(t2).forEach((t3) => {
        const e2 = JSON.stringify(t3);
        this.objects[e2] == null && (this.objects[e2] = t3);
      });
    }
    find(t2) {
      const e2 = JSON.stringify(t2);
      return this.objects[e2];
    }
  };
  var Qt = class {
    constructor(t2) {
      this.reset(t2);
    }
    add(t2) {
      const e2 = Zt(t2);
      this.elements[e2] = t2;
    }
    remove(t2) {
      const e2 = Zt(t2), i2 = this.elements[e2];
      if (i2)
        return delete this.elements[e2], i2;
    }
    reset() {
      let t2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : [];
      return this.elements = {}, Array.from(t2).forEach((t3) => {
        this.add(t3);
      }), t2;
    }
  };
  var Zt = (t2) => t2.dataset.trixStoreKey;
  var te = class extends z {
    isPerforming() {
      return this.performing === true;
    }
    hasPerformed() {
      return this.performed === true;
    }
    hasSucceeded() {
      return this.performed && this.succeeded;
    }
    hasFailed() {
      return this.performed && !this.succeeded;
    }
    getPromise() {
      return this.promise || (this.promise = new Promise((t2, e2) => (this.performing = true, this.perform((i2, n2) => {
        this.succeeded = i2, this.performing = false, this.performed = true, this.succeeded ? t2(n2) : e2(n2);
      })))), this.promise;
    }
    perform(t2) {
      return t2(false);
    }
    release() {
      var t2, e2;
      (t2 = this.promise) === null || t2 === void 0 || (e2 = t2.cancel) === null || e2 === void 0 || e2.call(t2), this.promise = null, this.performing = null, this.performed = null, this.succeeded = null;
    }
  };
  te.proxyMethod("getPromise().then"), te.proxyMethod("getPromise().catch");
  var ee = class extends z {
    constructor(t2) {
      let e2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
      super(...arguments), this.object = t2, this.options = e2, this.childViews = [], this.rootView = this;
    }
    getNodes() {
      return this.nodes || (this.nodes = this.createNodes()), this.nodes.map((t2) => t2.cloneNode(true));
    }
    invalidate() {
      var t2;
      return this.nodes = null, this.childViews = [], (t2 = this.parentView) === null || t2 === void 0 ? void 0 : t2.invalidate();
    }
    invalidateViewForObject(t2) {
      var e2;
      return (e2 = this.findViewForObject(t2)) === null || e2 === void 0 ? void 0 : e2.invalidate();
    }
    findOrCreateCachedChildView(t2, e2, i2) {
      let n2 = this.getCachedViewForObject(e2);
      return n2 ? this.recordChildView(n2) : (n2 = this.createChildView(...arguments), this.cacheViewForObject(n2, e2)), n2;
    }
    createChildView(t2, e2) {
      let i2 = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
      e2 instanceof Xt && (i2.viewClass = t2, t2 = ie);
      const n2 = new t2(e2, i2);
      return this.recordChildView(n2);
    }
    recordChildView(t2) {
      return t2.parentView = this, t2.rootView = this.rootView, this.childViews.push(t2), t2;
    }
    getAllChildViews() {
      let t2 = [];
      return this.childViews.forEach((e2) => {
        t2.push(e2), t2 = t2.concat(e2.getAllChildViews());
      }), t2;
    }
    findElement() {
      return this.findElementForObject(this.object);
    }
    findElementForObject(t2) {
      const e2 = t2 == null ? void 0 : t2.id;
      if (e2)
        return this.rootView.element.querySelector("[data-trix-id='".concat(e2, "']"));
    }
    findViewForObject(t2) {
      for (const e2 of this.getAllChildViews())
        if (e2.object === t2)
          return e2;
    }
    getViewCache() {
      return this.rootView !== this ? this.rootView.getViewCache() : this.isViewCachingEnabled() ? (this.viewCache || (this.viewCache = {}), this.viewCache) : void 0;
    }
    isViewCachingEnabled() {
      return this.shouldCacheViews !== false;
    }
    enableViewCaching() {
      this.shouldCacheViews = true;
    }
    disableViewCaching() {
      this.shouldCacheViews = false;
    }
    getCachedViewForObject(t2) {
      var e2;
      return (e2 = this.getViewCache()) === null || e2 === void 0 ? void 0 : e2[t2.getCacheKey()];
    }
    cacheViewForObject(t2, e2) {
      const i2 = this.getViewCache();
      i2 && (i2[e2.getCacheKey()] = t2);
    }
    garbageCollectCachedViews() {
      const t2 = this.getViewCache();
      if (t2) {
        const e2 = this.getAllChildViews().concat(this).map((t3) => t3.object.getCacheKey());
        for (const i2 in t2)
          e2.includes(i2) || delete t2[i2];
      }
    }
  };
  var ie = class extends ee {
    constructor() {
      super(...arguments), this.objectGroup = this.object, this.viewClass = this.options.viewClass, delete this.options.viewClass;
    }
    getChildViews() {
      return this.childViews.length || Array.from(this.objectGroup.getObjects()).forEach((t2) => {
        this.findOrCreateCachedChildView(this.viewClass, t2, this.options);
      }), this.childViews;
    }
    createNodes() {
      const t2 = this.createContainerElement();
      return this.getChildViews().forEach((e2) => {
        Array.from(e2.getNodes()).forEach((e3) => {
          t2.appendChild(e3);
        });
      }), [t2];
    }
    createContainerElement() {
      let t2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : this.objectGroup.getDepth();
      return this.getChildViews()[0].createContainerElement(t2);
    }
  };
  var { css: ne } = V;
  var re = class extends ee {
    constructor() {
      super(...arguments), this.attachment = this.object, this.attachment.uploadProgressDelegate = this, this.attachmentPiece = this.options.piece;
    }
    createContentNodes() {
      return [];
    }
    createNodes() {
      let t2;
      const e2 = t2 = k({ tagName: "figure", className: this.getClassName(), data: this.getData(), editable: false }), i2 = this.getHref();
      return i2 && (t2 = k({ tagName: "a", editable: false, attributes: { href: i2, tabindex: -1 } }), e2.appendChild(t2)), this.attachment.hasContent() ? t2.innerHTML = this.attachment.getContent() : this.createContentNodes().forEach((e3) => {
        t2.appendChild(e3);
      }), t2.appendChild(this.createCaptionElement()), this.attachment.isPending() && (this.progressElement = k({ tagName: "progress", attributes: { class: ne.attachmentProgress, value: this.attachment.getUploadProgress(), max: 100 }, data: { trixMutable: true, trixStoreKey: ["progressElement", this.attachment.id].join("/") } }), e2.appendChild(this.progressElement)), [oe("left"), e2, oe("right")];
    }
    createCaptionElement() {
      const t2 = k({ tagName: "figcaption", className: ne.attachmentCaption }), e2 = this.attachmentPiece.getCaption();
      if (e2)
        t2.classList.add("".concat(ne.attachmentCaption, "--edited")), t2.textContent = e2;
      else {
        let e3, i2;
        const n2 = this.getCaptionConfig();
        if (n2.name && (e3 = this.attachment.getFilename()), n2.size && (i2 = this.attachment.getFormattedFilesize()), e3) {
          const i3 = k({ tagName: "span", className: ne.attachmentName, textContent: e3 });
          t2.appendChild(i3);
        }
        if (i2) {
          e3 && t2.appendChild(document.createTextNode(" "));
          const n3 = k({ tagName: "span", className: ne.attachmentSize, textContent: i2 });
          t2.appendChild(n3);
        }
      }
      return t2;
    }
    getClassName() {
      const t2 = [ne.attachment, "".concat(ne.attachment, "--").concat(this.attachment.getType())], e2 = this.attachment.getExtension();
      return e2 && t2.push("".concat(ne.attachment, "--").concat(e2)), t2.join(" ");
    }
    getData() {
      const t2 = { trixAttachment: JSON.stringify(this.attachment), trixContentType: this.attachment.getContentType(), trixId: this.attachment.id }, { attributes: e2 } = this.attachmentPiece;
      return e2.isEmpty() || (t2.trixAttributes = JSON.stringify(e2)), this.attachment.isPending() && (t2.trixSerialize = false), t2;
    }
    getHref() {
      if (!se(this.attachment.getContent(), "a"))
        return this.attachment.getHref();
    }
    getCaptionConfig() {
      var t2;
      const e2 = this.attachment.getType(), n2 = Et((t2 = i[e2]) === null || t2 === void 0 ? void 0 : t2.caption);
      return e2 === "file" && (n2.name = true), n2;
    }
    findProgressElement() {
      var t2;
      return (t2 = this.findElement()) === null || t2 === void 0 ? void 0 : t2.querySelector("progress");
    }
    attachmentDidChangeUploadProgress() {
      const t2 = this.attachment.getUploadProgress(), e2 = this.findProgressElement();
      e2 && (e2.value = t2);
    }
  };
  var oe = (t2) => k({ tagName: "span", textContent: u, data: { trixCursorTarget: t2, trixSerialize: false } });
  var se = function(t2, e2) {
    const i2 = k("div");
    return i2.innerHTML = t2 || "", i2.querySelector(e2);
  };
  var ae = class extends re {
    constructor() {
      super(...arguments), this.attachment.previewDelegate = this;
    }
    createContentNodes() {
      return this.image = k({ tagName: "img", attributes: { src: "" }, data: { trixMutable: true } }), this.refresh(this.image), [this.image];
    }
    createCaptionElement() {
      const t2 = super.createCaptionElement(...arguments);
      return t2.textContent || t2.setAttribute("data-trix-placeholder", l.captionPlaceholder), t2;
    }
    refresh(t2) {
      var e2;
      t2 || (t2 = (e2 = this.findElement()) === null || e2 === void 0 ? void 0 : e2.querySelector("img"));
      if (t2)
        return this.updateAttributesForImage(t2);
    }
    updateAttributesForImage(t2) {
      const e2 = this.attachment.getURL(), i2 = this.attachment.getPreviewURL();
      if (t2.src = i2 || e2, i2 === e2)
        t2.removeAttribute("data-trix-serialized-attributes");
      else {
        const i3 = JSON.stringify({ src: e2 });
        t2.setAttribute("data-trix-serialized-attributes", i3);
      }
      const n2 = this.attachment.getWidth(), r2 = this.attachment.getHeight();
      n2 != null && (t2.width = n2), r2 != null && (t2.height = r2);
      const o2 = ["imageElement", this.attachment.id, t2.src, t2.width, t2.height].join("/");
      t2.dataset.trixStoreKey = o2;
    }
    attachmentDidChangeAttributes() {
      return this.refresh(this.image), this.refresh();
    }
  };
  var le = class extends ee {
    constructor() {
      super(...arguments), this.piece = this.object, this.attributes = this.piece.getAttributes(), this.textConfig = this.options.textConfig, this.context = this.options.context, this.piece.attachment ? this.attachment = this.piece.attachment : this.string = this.piece.toString();
    }
    createNodes() {
      let t2 = this.attachment ? this.createAttachmentNodes() : this.createStringNodes();
      const e2 = this.createElement();
      if (e2) {
        const i2 = function(t3) {
          for (; (e3 = t3) !== null && e3 !== void 0 && e3.firstElementChild; ) {
            var e3;
            t3 = t3.firstElementChild;
          }
          return t3;
        }(e2);
        Array.from(t2).forEach((t3) => {
          i2.appendChild(t3);
        }), t2 = [e2];
      }
      return t2;
    }
    createAttachmentNodes() {
      const t2 = this.attachment.isPreviewable() ? ae : re;
      return this.createChildView(t2, this.piece.attachment, { piece: this.piece }).getNodes();
    }
    createStringNodes() {
      var t2;
      if ((t2 = this.textConfig) !== null && t2 !== void 0 && t2.plaintext)
        return [document.createTextNode(this.string)];
      {
        const t3 = [], e2 = this.string.split("\n");
        for (let i2 = 0; i2 < e2.length; i2++) {
          const n2 = e2[i2];
          if (i2 > 0) {
            const e3 = k("br");
            t3.push(e3);
          }
          if (n2.length) {
            const e3 = document.createTextNode(this.preserveSpaces(n2));
            t3.push(e3);
          }
        }
        return t3;
      }
    }
    createElement() {
      let t2, e2, i2;
      const n2 = {};
      for (e2 in this.attributes) {
        i2 = this.attributes[e2];
        const o2 = pt(e2);
        if (o2) {
          if (o2.tagName) {
            var r2;
            const e3 = k(o2.tagName);
            r2 ? (r2.appendChild(e3), r2 = e3) : t2 = r2 = e3;
          }
          if (o2.styleProperty && (n2[o2.styleProperty] = i2), o2.style)
            for (e2 in o2.style)
              i2 = o2.style[e2], n2[e2] = i2;
        }
      }
      if (Object.keys(n2).length)
        for (e2 in t2 || (t2 = k("span")), n2)
          i2 = n2[e2], t2.style[e2] = i2;
      return t2;
    }
    createContainerElement() {
      for (const t2 in this.attributes) {
        const e2 = this.attributes[t2], i2 = pt(t2);
        if (i2 && i2.groupTagName) {
          const n2 = {};
          return n2[t2] = e2, k(i2.groupTagName, n2);
        }
      }
    }
    preserveSpaces(t2) {
      return this.context.isLast && (t2 = t2.replace(/\ $/, d)), t2 = t2.replace(/(\S)\ {3}(\S)/g, "$1 ".concat(d, " $2")).replace(/\ {2}/g, "".concat(d, " ")).replace(/\ {2}/g, " ".concat(d)), (this.context.isFirst || this.context.followsWhitespace) && (t2 = t2.replace(/^\ /, d)), t2;
    }
  };
  var ce = class extends ee {
    constructor() {
      super(...arguments), this.text = this.object, this.textConfig = this.options.textConfig;
    }
    createNodes() {
      const t2 = [], e2 = Xt.groupObjects(this.getPieces()), i2 = e2.length - 1;
      for (let r2 = 0; r2 < e2.length; r2++) {
        const o2 = e2[r2], s2 = {};
        r2 === 0 && (s2.isFirst = true), r2 === i2 && (s2.isLast = true), he(n2) && (s2.followsWhitespace = true);
        const a2 = this.findOrCreateCachedChildView(le, o2, { textConfig: this.textConfig, context: s2 });
        t2.push(...Array.from(a2.getNodes() || []));
        var n2 = o2;
      }
      return t2;
    }
    getPieces() {
      return Array.from(this.text.getPieces()).filter((t2) => !t2.hasAttribute("blockBreak"));
    }
  };
  var he = (t2) => /\s$/.test(t2 == null ? void 0 : t2.toString());
  var { css: ue } = V;
  var de = class extends ee {
    constructor() {
      super(...arguments), this.block = this.object, this.attributes = this.block.getAttributes();
    }
    createNodes() {
      const t2 = [document.createComment("block")];
      if (this.block.isEmpty())
        t2.push(k("br"));
      else {
        var e2;
        const i2 = (e2 = gt(this.block.getLastAttribute())) === null || e2 === void 0 ? void 0 : e2.text, n2 = this.findOrCreateCachedChildView(ce, this.block.text, { textConfig: i2 });
        t2.push(...Array.from(n2.getNodes() || [])), this.shouldAddExtraNewlineElement() && t2.push(k("br"));
      }
      if (this.attributes.length)
        return t2;
      {
        let e3;
        const { tagName: i2 } = n.default;
        this.block.isRTL() && (e3 = { dir: "rtl" });
        const r2 = k({ tagName: i2, attributes: e3 });
        return t2.forEach((t3) => r2.appendChild(t3)), [r2];
      }
    }
    createContainerElement(t2) {
      let e2, i2;
      const n2 = this.attributes[t2], { tagName: r2 } = gt(n2);
      if (t2 === 0 && this.block.isRTL() && (e2 = { dir: "rtl" }), n2 === "attachmentGallery") {
        const t3 = this.block.getBlockBreakPosition();
        i2 = "".concat(ue.attachmentGallery, " ").concat(ue.attachmentGallery, "--").concat(t3);
      }
      return k({ tagName: r2, className: i2, attributes: e2 });
    }
    shouldAddExtraNewlineElement() {
      return /\n\n$/.test(this.block.toString());
    }
  };
  var ge = class extends ee {
    static render(t2) {
      const e2 = k("div"), i2 = new this(t2, { element: e2 });
      return i2.render(), i2.sync(), e2;
    }
    constructor() {
      super(...arguments), this.element = this.options.element, this.elementStore = new Qt(), this.setDocument(this.object);
    }
    setDocument(t2) {
      t2.isEqualTo(this.document) || (this.document = this.object = t2);
    }
    render() {
      if (this.childViews = [], this.shadowElement = k("div"), !this.document.isEmpty()) {
        const t2 = Xt.groupObjects(this.document.getBlocks(), { asTree: true });
        Array.from(t2).forEach((t3) => {
          const e2 = this.findOrCreateCachedChildView(de, t3);
          Array.from(e2.getNodes()).map((t4) => this.shadowElement.appendChild(t4));
        });
      }
    }
    isSynced() {
      return pe(this.shadowElement, this.element);
    }
    sync() {
      const t2 = this.createDocumentFragmentForSync();
      for (; this.element.lastChild; )
        this.element.removeChild(this.element.lastChild);
      return this.element.appendChild(t2), this.didSync();
    }
    didSync() {
      return this.elementStore.reset(me(this.element)), St(() => this.garbageCollectCachedViews());
    }
    createDocumentFragmentForSync() {
      const t2 = document.createDocumentFragment();
      return Array.from(this.shadowElement.childNodes).forEach((e2) => {
        t2.appendChild(e2.cloneNode(true));
      }), Array.from(me(t2)).forEach((t3) => {
        const e2 = this.elementStore.remove(t3);
        e2 && t3.parentNode.replaceChild(e2, t3);
      }), t2;
    }
  };
  var me = (t2) => t2.querySelectorAll("[data-trix-store-key]");
  var pe = (t2, e2) => fe(t2.innerHTML) === fe(e2.innerHTML);
  var fe = (t2) => t2.replace(/&nbsp;/g, " ");
  function be(t2) {
    var e2, i2;
    function n2(e3, i3) {
      try {
        var o2 = t2[e3](i3), s2 = o2.value, a2 = s2 instanceof ve;
        Promise.resolve(a2 ? s2.v : s2).then(function(i4) {
          if (a2) {
            var l2 = e3 === "return" ? "return" : "next";
            if (!s2.k || i4.done)
              return n2(l2, i4);
            i4 = t2[l2](i4).value;
          }
          r2(o2.done ? "return" : "normal", i4);
        }, function(t3) {
          n2("throw", t3);
        });
      } catch (t3) {
        r2("throw", t3);
      }
    }
    function r2(t3, r3) {
      switch (t3) {
        case "return":
          e2.resolve({ value: r3, done: true });
          break;
        case "throw":
          e2.reject(r3);
          break;
        default:
          e2.resolve({ value: r3, done: false });
      }
      (e2 = e2.next) ? n2(e2.key, e2.arg) : i2 = null;
    }
    this._invoke = function(t3, r3) {
      return new Promise(function(o2, s2) {
        var a2 = { key: t3, arg: r3, resolve: o2, reject: s2, next: null };
        i2 ? i2 = i2.next = a2 : (e2 = i2 = a2, n2(t3, r3));
      });
    }, typeof t2.return != "function" && (this.return = void 0);
  }
  function ve(t2, e2) {
    this.v = t2, this.k = e2;
  }
  function Ae(t2, e2, i2) {
    return (e2 = xe(e2)) in t2 ? Object.defineProperty(t2, e2, { value: i2, enumerable: true, configurable: true, writable: true }) : t2[e2] = i2, t2;
  }
  function xe(t2) {
    var e2 = function(t3, e3) {
      if (typeof t3 != "object" || t3 === null)
        return t3;
      var i2 = t3[Symbol.toPrimitive];
      if (i2 !== void 0) {
        var n2 = i2.call(t3, e3 || "default");
        if (typeof n2 != "object")
          return n2;
        throw new TypeError("@@toPrimitive must return a primitive value.");
      }
      return (e3 === "string" ? String : Number)(t3);
    }(t2, "string");
    return typeof e2 == "symbol" ? e2 : String(e2);
  }
  be.prototype[typeof Symbol == "function" && Symbol.asyncIterator || "@@asyncIterator"] = function() {
    return this;
  }, be.prototype.next = function(t2) {
    return this._invoke("next", t2);
  }, be.prototype.throw = function(t2) {
    return this._invoke("throw", t2);
  }, be.prototype.return = function(t2) {
    return this._invoke("return", t2);
  };
  var ye = class extends nt {
    static registerType(t2, e2) {
      e2.type = t2, this.types[t2] = e2;
    }
    static fromJSON(t2) {
      const e2 = this.types[t2.type];
      if (e2)
        return e2.fromJSON(t2);
    }
    constructor(t2) {
      let e2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
      super(...arguments), this.attributes = _t.box(e2);
    }
    copyWithAttributes(t2) {
      return new this.constructor(this.getValue(), t2);
    }
    copyWithAdditionalAttributes(t2) {
      return this.copyWithAttributes(this.attributes.merge(t2));
    }
    copyWithoutAttribute(t2) {
      return this.copyWithAttributes(this.attributes.remove(t2));
    }
    copy() {
      return this.copyWithAttributes(this.attributes);
    }
    getAttribute(t2) {
      return this.attributes.get(t2);
    }
    getAttributesHash() {
      return this.attributes;
    }
    getAttributes() {
      return this.attributes.toObject();
    }
    hasAttribute(t2) {
      return this.attributes.has(t2);
    }
    hasSameStringValueAsPiece(t2) {
      return t2 && this.toString() === t2.toString();
    }
    hasSameAttributesAsPiece(t2) {
      return t2 && (this.attributes === t2.attributes || this.attributes.isEqualTo(t2.attributes));
    }
    isBlockBreak() {
      return false;
    }
    isEqualTo(t2) {
      return super.isEqualTo(...arguments) || this.hasSameConstructorAs(t2) && this.hasSameStringValueAsPiece(t2) && this.hasSameAttributesAsPiece(t2);
    }
    isEmpty() {
      return this.length === 0;
    }
    isSerializable() {
      return true;
    }
    toJSON() {
      return { type: this.constructor.type, attributes: this.getAttributes() };
    }
    contentsForInspection() {
      return { type: this.constructor.type, attributes: this.attributes.inspect() };
    }
    canBeGrouped() {
      return this.hasAttribute("href");
    }
    canBeGroupedWith(t2) {
      return this.getAttribute("href") === t2.getAttribute("href");
    }
    getLength() {
      return this.length;
    }
    canBeConsolidatedWith(t2) {
      return false;
    }
  };
  Ae(ye, "types", {});
  var Ce = class extends te {
    constructor(t2) {
      super(...arguments), this.url = t2;
    }
    perform(t2) {
      const e2 = new Image();
      e2.onload = () => (e2.width = this.width = e2.naturalWidth, e2.height = this.height = e2.naturalHeight, t2(true, e2)), e2.onerror = () => t2(false), e2.src = this.url;
    }
  };
  var Re = class extends nt {
    static attachmentForFile(t2) {
      const e2 = new this(this.attributesForFile(t2));
      return e2.setFile(t2), e2;
    }
    static attributesForFile(t2) {
      return new _t({ filename: t2.name, filesize: t2.size, contentType: t2.type });
    }
    static fromJSON(t2) {
      return new this(t2);
    }
    constructor() {
      let t2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
      super(t2), this.releaseFile = this.releaseFile.bind(this), this.attributes = _t.box(t2), this.didChangeAttributes();
    }
    getAttribute(t2) {
      return this.attributes.get(t2);
    }
    hasAttribute(t2) {
      return this.attributes.has(t2);
    }
    getAttributes() {
      return this.attributes.toObject();
    }
    setAttributes() {
      let t2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
      const e2 = this.attributes.merge(t2);
      var i2, n2, r2, o2;
      if (!this.attributes.isEqualTo(e2))
        return this.attributes = e2, this.didChangeAttributes(), (i2 = this.previewDelegate) === null || i2 === void 0 || (n2 = i2.attachmentDidChangeAttributes) === null || n2 === void 0 || n2.call(i2, this), (r2 = this.delegate) === null || r2 === void 0 || (o2 = r2.attachmentDidChangeAttributes) === null || o2 === void 0 ? void 0 : o2.call(r2, this);
    }
    didChangeAttributes() {
      if (this.isPreviewable())
        return this.preloadURL();
    }
    isPending() {
      return this.file != null && !(this.getURL() || this.getHref());
    }
    isPreviewable() {
      return this.attributes.has("previewable") ? this.attributes.get("previewable") : Re.previewablePattern.test(this.getContentType());
    }
    getType() {
      return this.hasContent() ? "content" : this.isPreviewable() ? "preview" : "file";
    }
    getURL() {
      return this.attributes.get("url");
    }
    getHref() {
      return this.attributes.get("href");
    }
    getFilename() {
      return this.attributes.get("filename") || "";
    }
    getFilesize() {
      return this.attributes.get("filesize");
    }
    getFormattedFilesize() {
      const t2 = this.attributes.get("filesize");
      return typeof t2 == "number" ? h.formatter(t2) : "";
    }
    getExtension() {
      var t2;
      return (t2 = this.getFilename().match(/\.(\w+)$/)) === null || t2 === void 0 ? void 0 : t2[1].toLowerCase();
    }
    getContentType() {
      return this.attributes.get("contentType");
    }
    hasContent() {
      return this.attributes.has("content");
    }
    getContent() {
      return this.attributes.get("content");
    }
    getWidth() {
      return this.attributes.get("width");
    }
    getHeight() {
      return this.attributes.get("height");
    }
    getFile() {
      return this.file;
    }
    setFile(t2) {
      if (this.file = t2, this.isPreviewable())
        return this.preloadFile();
    }
    releaseFile() {
      this.releasePreloadedFile(), this.file = null;
    }
    getUploadProgress() {
      return this.uploadProgress != null ? this.uploadProgress : 0;
    }
    setUploadProgress(t2) {
      var e2, i2;
      if (this.uploadProgress !== t2)
        return this.uploadProgress = t2, (e2 = this.uploadProgressDelegate) === null || e2 === void 0 || (i2 = e2.attachmentDidChangeUploadProgress) === null || i2 === void 0 ? void 0 : i2.call(e2, this);
    }
    toJSON() {
      return this.getAttributes();
    }
    getCacheKey() {
      return [super.getCacheKey(...arguments), this.attributes.getCacheKey(), this.getPreviewURL()].join("/");
    }
    getPreviewURL() {
      return this.previewURL || this.preloadingURL;
    }
    setPreviewURL(t2) {
      var e2, i2, n2, r2;
      if (t2 !== this.getPreviewURL())
        return this.previewURL = t2, (e2 = this.previewDelegate) === null || e2 === void 0 || (i2 = e2.attachmentDidChangeAttributes) === null || i2 === void 0 || i2.call(e2, this), (n2 = this.delegate) === null || n2 === void 0 || (r2 = n2.attachmentDidChangePreviewURL) === null || r2 === void 0 ? void 0 : r2.call(n2, this);
    }
    preloadURL() {
      return this.preload(this.getURL(), this.releaseFile);
    }
    preloadFile() {
      if (this.file)
        return this.fileObjectURL = URL.createObjectURL(this.file), this.preload(this.fileObjectURL);
    }
    releasePreloadedFile() {
      this.fileObjectURL && (URL.revokeObjectURL(this.fileObjectURL), this.fileObjectURL = null);
    }
    preload(t2, e2) {
      if (t2 && t2 !== this.getPreviewURL()) {
        this.preloadingURL = t2;
        return new Ce(t2).then((i2) => {
          let { width: n2, height: r2 } = i2;
          return this.getWidth() && this.getHeight() || this.setAttributes({ width: n2, height: r2 }), this.preloadingURL = null, this.setPreviewURL(t2), e2 == null ? void 0 : e2();
        }).catch(() => (this.preloadingURL = null, e2 == null ? void 0 : e2()));
      }
    }
  };
  Ae(Re, "previewablePattern", /^image(\/(gif|png|webp|jpe?g)|$)/);
  var Se = class extends ye {
    static fromJSON(t2) {
      return new this(Re.fromJSON(t2.attachment), t2.attributes);
    }
    constructor(t2) {
      super(...arguments), this.attachment = t2, this.length = 1, this.ensureAttachmentExclusivelyHasAttribute("href"), this.attachment.hasContent() || this.removeProhibitedAttributes();
    }
    ensureAttachmentExclusivelyHasAttribute(t2) {
      this.hasAttribute(t2) && (this.attachment.hasAttribute(t2) || this.attachment.setAttributes(this.attributes.slice([t2])), this.attributes = this.attributes.remove(t2));
    }
    removeProhibitedAttributes() {
      const t2 = this.attributes.slice(Se.permittedAttributes);
      t2.isEqualTo(this.attributes) || (this.attributes = t2);
    }
    getValue() {
      return this.attachment;
    }
    isSerializable() {
      return !this.attachment.isPending();
    }
    getCaption() {
      return this.attributes.get("caption") || "";
    }
    isEqualTo(t2) {
      var e2;
      return super.isEqualTo(t2) && this.attachment.id === (t2 == null || (e2 = t2.attachment) === null || e2 === void 0 ? void 0 : e2.id);
    }
    toString() {
      return "\uFFFC";
    }
    toJSON() {
      const t2 = super.toJSON(...arguments);
      return t2.attachment = this.attachment, t2;
    }
    getCacheKey() {
      return [super.getCacheKey(...arguments), this.attachment.getCacheKey()].join("/");
    }
    toConsole() {
      return JSON.stringify(this.toString());
    }
  };
  Ae(Se, "permittedAttributes", ["caption", "presentation"]), ye.registerType("attachment", Se);
  var Ee = class extends ye {
    static fromJSON(t2) {
      return new this(t2.string, t2.attributes);
    }
    constructor(t2) {
      super(...arguments), this.string = ((t3) => t3.replace(/\r\n?/g, "\n"))(t2), this.length = this.string.length;
    }
    getValue() {
      return this.string;
    }
    toString() {
      return this.string.toString();
    }
    isBlockBreak() {
      return this.toString() === "\n" && this.getAttribute("blockBreak") === true;
    }
    toJSON() {
      const t2 = super.toJSON(...arguments);
      return t2.string = this.string, t2;
    }
    canBeConsolidatedWith(t2) {
      return t2 && this.hasSameConstructorAs(t2) && this.hasSameAttributesAsPiece(t2);
    }
    consolidateWith(t2) {
      return new this.constructor(this.toString() + t2.toString(), this.attributes);
    }
    splitAtOffset(t2) {
      let e2, i2;
      return t2 === 0 ? (e2 = null, i2 = this) : t2 === this.length ? (e2 = this, i2 = null) : (e2 = new this.constructor(this.string.slice(0, t2), this.attributes), i2 = new this.constructor(this.string.slice(t2), this.attributes)), [e2, i2];
    }
    toConsole() {
      let { string: t2 } = this;
      return t2.length > 15 && (t2 = t2.slice(0, 14) + "\u2026"), JSON.stringify(t2.toString());
    }
  };
  ye.registerType("string", Ee);
  var ke = class extends nt {
    static box(t2) {
      return t2 instanceof this ? t2 : new this(t2);
    }
    constructor() {
      let t2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : [];
      super(...arguments), this.objects = t2.slice(0), this.length = this.objects.length;
    }
    indexOf(t2) {
      return this.objects.indexOf(t2);
    }
    splice() {
      for (var t2 = arguments.length, e2 = new Array(t2), i2 = 0; i2 < t2; i2++)
        e2[i2] = arguments[i2];
      return new this.constructor(ot(this.objects, ...e2));
    }
    eachObject(t2) {
      return this.objects.map((e2, i2) => t2(e2, i2));
    }
    insertObjectAtIndex(t2, e2) {
      return this.splice(e2, 0, t2);
    }
    insertSplittableListAtIndex(t2, e2) {
      return this.splice(e2, 0, ...t2.objects);
    }
    insertSplittableListAtPosition(t2, e2) {
      const [i2, n2] = this.splitObjectAtPosition(e2);
      return new this.constructor(i2).insertSplittableListAtIndex(t2, n2);
    }
    editObjectAtIndex(t2, e2) {
      return this.replaceObjectAtIndex(e2(this.objects[t2]), t2);
    }
    replaceObjectAtIndex(t2, e2) {
      return this.splice(e2, 1, t2);
    }
    removeObjectAtIndex(t2) {
      return this.splice(t2, 1);
    }
    getObjectAtIndex(t2) {
      return this.objects[t2];
    }
    getSplittableListInRange(t2) {
      const [e2, i2, n2] = this.splitObjectsAtRange(t2);
      return new this.constructor(e2.slice(i2, n2 + 1));
    }
    selectSplittableList(t2) {
      const e2 = this.objects.filter((e3) => t2(e3));
      return new this.constructor(e2);
    }
    removeObjectsInRange(t2) {
      const [e2, i2, n2] = this.splitObjectsAtRange(t2);
      return new this.constructor(e2).splice(i2, n2 - i2 + 1);
    }
    transformObjectsInRange(t2, e2) {
      const [i2, n2, r2] = this.splitObjectsAtRange(t2), o2 = i2.map((t3, i3) => n2 <= i3 && i3 <= r2 ? e2(t3) : t3);
      return new this.constructor(o2);
    }
    splitObjectsAtRange(t2) {
      let e2, [i2, n2, r2] = this.splitObjectAtPosition(De(t2));
      return [i2, e2] = new this.constructor(i2).splitObjectAtPosition(we(t2) + r2), [i2, n2, e2 - 1];
    }
    getObjectAtPosition(t2) {
      const { index: e2 } = this.findIndexAndOffsetAtPosition(t2);
      return this.objects[e2];
    }
    splitObjectAtPosition(t2) {
      let e2, i2;
      const { index: n2, offset: r2 } = this.findIndexAndOffsetAtPosition(t2), o2 = this.objects.slice(0);
      if (n2 != null)
        if (r2 === 0)
          e2 = n2, i2 = 0;
        else {
          const t3 = this.getObjectAtIndex(n2), [s2, a2] = t3.splitAtOffset(r2);
          o2.splice(n2, 1, s2, a2), e2 = n2 + 1, i2 = s2.getLength() - r2;
        }
      else
        e2 = o2.length, i2 = 0;
      return [o2, e2, i2];
    }
    consolidate() {
      const t2 = [];
      let e2 = this.objects[0];
      return this.objects.slice(1).forEach((i2) => {
        var n2, r2;
        (n2 = (r2 = e2).canBeConsolidatedWith) !== null && n2 !== void 0 && n2.call(r2, i2) ? e2 = e2.consolidateWith(i2) : (t2.push(e2), e2 = i2);
      }), e2 && t2.push(e2), new this.constructor(t2);
    }
    consolidateFromIndexToIndex(t2, e2) {
      const i2 = this.objects.slice(0).slice(t2, e2 + 1), n2 = new this.constructor(i2).consolidate().toArray();
      return this.splice(t2, i2.length, ...n2);
    }
    findIndexAndOffsetAtPosition(t2) {
      let e2, i2 = 0;
      for (e2 = 0; e2 < this.objects.length; e2++) {
        const n2 = i2 + this.objects[e2].getLength();
        if (i2 <= t2 && t2 < n2)
          return { index: e2, offset: t2 - i2 };
        i2 = n2;
      }
      return { index: null, offset: null };
    }
    findPositionAtIndexAndOffset(t2, e2) {
      let i2 = 0;
      for (let n2 = 0; n2 < this.objects.length; n2++) {
        const r2 = this.objects[n2];
        if (n2 < t2)
          i2 += r2.getLength();
        else if (n2 === t2) {
          i2 += e2;
          break;
        }
      }
      return i2;
    }
    getEndPosition() {
      return this.endPosition == null && (this.endPosition = 0, this.objects.forEach((t2) => this.endPosition += t2.getLength())), this.endPosition;
    }
    toString() {
      return this.objects.join("");
    }
    toArray() {
      return this.objects.slice(0);
    }
    toJSON() {
      return this.toArray();
    }
    isEqualTo(t2) {
      return super.isEqualTo(...arguments) || Le(this.objects, t2 == null ? void 0 : t2.objects);
    }
    contentsForInspection() {
      return { objects: "[".concat(this.objects.map((t2) => t2.inspect()).join(", "), "]") };
    }
  };
  var Le = function(t2) {
    let e2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : [];
    if (t2.length !== e2.length)
      return false;
    let i2 = true;
    for (let n2 = 0; n2 < t2.length; n2++) {
      const r2 = t2[n2];
      i2 && !r2.isEqualTo(e2[n2]) && (i2 = false);
    }
    return i2;
  };
  var De = (t2) => t2[0];
  var we = (t2) => t2[1];
  var Te = class extends nt {
    static textForAttachmentWithAttributes(t2, e2) {
      return new this([new Se(t2, e2)]);
    }
    static textForStringWithAttributes(t2, e2) {
      return new this([new Ee(t2, e2)]);
    }
    static fromJSON(t2) {
      return new this(Array.from(t2).map((t3) => ye.fromJSON(t3)));
    }
    constructor() {
      let t2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : [];
      super(...arguments);
      const e2 = t2.filter((t3) => !t3.isEmpty());
      this.pieceList = new ke(e2);
    }
    copy() {
      return this.copyWithPieceList(this.pieceList);
    }
    copyWithPieceList(t2) {
      return new this.constructor(t2.consolidate().toArray());
    }
    copyUsingObjectMap(t2) {
      const e2 = this.getPieces().map((e3) => t2.find(e3) || e3);
      return new this.constructor(e2);
    }
    appendText(t2) {
      return this.insertTextAtPosition(t2, this.getLength());
    }
    insertTextAtPosition(t2, e2) {
      return this.copyWithPieceList(this.pieceList.insertSplittableListAtPosition(t2.pieceList, e2));
    }
    removeTextAtRange(t2) {
      return this.copyWithPieceList(this.pieceList.removeObjectsInRange(t2));
    }
    replaceTextAtRange(t2, e2) {
      return this.removeTextAtRange(e2).insertTextAtPosition(t2, e2[0]);
    }
    moveTextFromRangeToPosition(t2, e2) {
      if (t2[0] <= e2 && e2 <= t2[1])
        return;
      const i2 = this.getTextAtRange(t2), n2 = i2.getLength();
      return t2[0] < e2 && (e2 -= n2), this.removeTextAtRange(t2).insertTextAtPosition(i2, e2);
    }
    addAttributeAtRange(t2, e2, i2) {
      const n2 = {};
      return n2[t2] = e2, this.addAttributesAtRange(n2, i2);
    }
    addAttributesAtRange(t2, e2) {
      return this.copyWithPieceList(this.pieceList.transformObjectsInRange(e2, (e3) => e3.copyWithAdditionalAttributes(t2)));
    }
    removeAttributeAtRange(t2, e2) {
      return this.copyWithPieceList(this.pieceList.transformObjectsInRange(e2, (e3) => e3.copyWithoutAttribute(t2)));
    }
    setAttributesAtRange(t2, e2) {
      return this.copyWithPieceList(this.pieceList.transformObjectsInRange(e2, (e3) => e3.copyWithAttributes(t2)));
    }
    getAttributesAtPosition(t2) {
      var e2;
      return ((e2 = this.pieceList.getObjectAtPosition(t2)) === null || e2 === void 0 ? void 0 : e2.getAttributes()) || {};
    }
    getCommonAttributes() {
      const t2 = Array.from(this.pieceList.toArray()).map((t3) => t3.getAttributes());
      return _t.fromCommonAttributesOfObjects(t2).toObject();
    }
    getCommonAttributesAtRange(t2) {
      return this.getTextAtRange(t2).getCommonAttributes() || {};
    }
    getExpandedRangeForAttributeAtOffset(t2, e2) {
      let i2, n2 = i2 = e2;
      const r2 = this.getLength();
      for (; n2 > 0 && this.getCommonAttributesAtRange([n2 - 1, i2])[t2]; )
        n2--;
      for (; i2 < r2 && this.getCommonAttributesAtRange([e2, i2 + 1])[t2]; )
        i2++;
      return [n2, i2];
    }
    getTextAtRange(t2) {
      return this.copyWithPieceList(this.pieceList.getSplittableListInRange(t2));
    }
    getStringAtRange(t2) {
      return this.pieceList.getSplittableListInRange(t2).toString();
    }
    getStringAtPosition(t2) {
      return this.getStringAtRange([t2, t2 + 1]);
    }
    startsWithString(t2) {
      return this.getStringAtRange([0, t2.length]) === t2;
    }
    endsWithString(t2) {
      const e2 = this.getLength();
      return this.getStringAtRange([e2 - t2.length, e2]) === t2;
    }
    getAttachmentPieces() {
      return this.pieceList.toArray().filter((t2) => !!t2.attachment);
    }
    getAttachments() {
      return this.getAttachmentPieces().map((t2) => t2.attachment);
    }
    getAttachmentAndPositionById(t2) {
      let e2 = 0;
      for (const n2 of this.pieceList.toArray()) {
        var i2;
        if (((i2 = n2.attachment) === null || i2 === void 0 ? void 0 : i2.id) === t2)
          return { attachment: n2.attachment, position: e2 };
        e2 += n2.length;
      }
      return { attachment: null, position: null };
    }
    getAttachmentById(t2) {
      const { attachment: e2 } = this.getAttachmentAndPositionById(t2);
      return e2;
    }
    getRangeOfAttachment(t2) {
      const e2 = this.getAttachmentAndPositionById(t2.id), i2 = e2.position;
      if (t2 = e2.attachment)
        return [i2, i2 + 1];
    }
    updateAttributesForAttachment(t2, e2) {
      const i2 = this.getRangeOfAttachment(e2);
      return i2 ? this.addAttributesAtRange(t2, i2) : this;
    }
    getLength() {
      return this.pieceList.getEndPosition();
    }
    isEmpty() {
      return this.getLength() === 0;
    }
    isEqualTo(t2) {
      var e2;
      return super.isEqualTo(t2) || (t2 == null || (e2 = t2.pieceList) === null || e2 === void 0 ? void 0 : e2.isEqualTo(this.pieceList));
    }
    isBlockBreak() {
      return this.getLength() === 1 && this.pieceList.getObjectAtIndex(0).isBlockBreak();
    }
    eachPiece(t2) {
      return this.pieceList.eachObject(t2);
    }
    getPieces() {
      return this.pieceList.toArray();
    }
    getPieceAtPosition(t2) {
      return this.pieceList.getObjectAtPosition(t2);
    }
    contentsForInspection() {
      return { pieceList: this.pieceList.inspect() };
    }
    toSerializableText() {
      const t2 = this.pieceList.selectSplittableList((t3) => t3.isSerializable());
      return this.copyWithPieceList(t2);
    }
    toString() {
      return this.pieceList.toString();
    }
    toJSON() {
      return this.pieceList.toJSON();
    }
    toConsole() {
      return JSON.stringify(this.pieceList.toArray().map((t2) => JSON.parse(t2.toConsole())));
    }
    getDirection() {
      return at(this.toString());
    }
    isRTL() {
      return this.getDirection() === "rtl";
    }
  };
  var Be = class extends nt {
    static fromJSON(t2) {
      return new this(Te.fromJSON(t2.text), t2.attributes);
    }
    constructor(t2, e2) {
      super(...arguments), this.text = Fe(t2 || new Te()), this.attributes = e2 || [];
    }
    isEmpty() {
      return this.text.isBlockBreak();
    }
    isEqualTo(t2) {
      return !!super.isEqualTo(t2) || this.text.isEqualTo(t2 == null ? void 0 : t2.text) && rt(this.attributes, t2 == null ? void 0 : t2.attributes);
    }
    copyWithText(t2) {
      return new Be(t2, this.attributes);
    }
    copyWithoutText() {
      return this.copyWithText(null);
    }
    copyWithAttributes(t2) {
      return new Be(this.text, t2);
    }
    copyWithoutAttributes() {
      return this.copyWithAttributes(null);
    }
    copyUsingObjectMap(t2) {
      const e2 = t2.find(this.text);
      return e2 ? this.copyWithText(e2) : this.copyWithText(this.text.copyUsingObjectMap(t2));
    }
    addAttribute(t2) {
      const e2 = this.attributes.concat(je(t2));
      return this.copyWithAttributes(e2);
    }
    removeAttribute(t2) {
      const { listAttribute: e2 } = gt(t2), i2 = Ue(Ue(this.attributes, t2), e2);
      return this.copyWithAttributes(i2);
    }
    removeLastAttribute() {
      return this.removeAttribute(this.getLastAttribute());
    }
    getLastAttribute() {
      return We(this.attributes);
    }
    getAttributes() {
      return this.attributes.slice(0);
    }
    getAttributeLevel() {
      return this.attributes.length;
    }
    getAttributeAtLevel(t2) {
      return this.attributes[t2 - 1];
    }
    hasAttribute(t2) {
      return this.attributes.includes(t2);
    }
    hasAttributes() {
      return this.getAttributeLevel() > 0;
    }
    getLastNestableAttribute() {
      return We(this.getNestableAttributes());
    }
    getNestableAttributes() {
      return this.attributes.filter((t2) => gt(t2).nestable);
    }
    getNestingLevel() {
      return this.getNestableAttributes().length;
    }
    decreaseNestingLevel() {
      const t2 = this.getLastNestableAttribute();
      return t2 ? this.removeAttribute(t2) : this;
    }
    increaseNestingLevel() {
      const t2 = this.getLastNestableAttribute();
      if (t2) {
        const e2 = this.attributes.lastIndexOf(t2), i2 = ot(this.attributes, e2 + 1, 0, ...je(t2));
        return this.copyWithAttributes(i2);
      }
      return this;
    }
    getListItemAttributes() {
      return this.attributes.filter((t2) => gt(t2).listAttribute);
    }
    isListItem() {
      var t2;
      return (t2 = gt(this.getLastAttribute())) === null || t2 === void 0 ? void 0 : t2.listAttribute;
    }
    isTerminalBlock() {
      var t2;
      return (t2 = gt(this.getLastAttribute())) === null || t2 === void 0 ? void 0 : t2.terminal;
    }
    breaksOnReturn() {
      var t2;
      return (t2 = gt(this.getLastAttribute())) === null || t2 === void 0 ? void 0 : t2.breakOnReturn;
    }
    findLineBreakInDirectionFromPosition(t2, e2) {
      const i2 = this.toString();
      let n2;
      switch (t2) {
        case "forward":
          n2 = i2.indexOf("\n", e2);
          break;
        case "backward":
          n2 = i2.slice(0, e2).lastIndexOf("\n");
      }
      if (n2 !== -1)
        return n2;
    }
    contentsForInspection() {
      return { text: this.text.inspect(), attributes: this.attributes };
    }
    toString() {
      return this.text.toString();
    }
    toJSON() {
      return { text: this.text, attributes: this.attributes };
    }
    getDirection() {
      return this.text.getDirection();
    }
    isRTL() {
      return this.text.isRTL();
    }
    getLength() {
      return this.text.getLength();
    }
    canBeConsolidatedWith(t2) {
      return !this.hasAttributes() && !t2.hasAttributes() && this.getDirection() === t2.getDirection();
    }
    consolidateWith(t2) {
      const e2 = Te.textForStringWithAttributes("\n"), i2 = this.getTextWithoutBlockBreak().appendText(e2);
      return this.copyWithText(i2.appendText(t2.text));
    }
    splitAtOffset(t2) {
      let e2, i2;
      return t2 === 0 ? (e2 = null, i2 = this) : t2 === this.getLength() ? (e2 = this, i2 = null) : (e2 = this.copyWithText(this.text.getTextAtRange([0, t2])), i2 = this.copyWithText(this.text.getTextAtRange([t2, this.getLength()]))), [e2, i2];
    }
    getBlockBreakPosition() {
      return this.text.getLength() - 1;
    }
    getTextWithoutBlockBreak() {
      return Oe(this.text) ? this.text.getTextAtRange([0, this.getBlockBreakPosition()]) : this.text.copy();
    }
    canBeGrouped(t2) {
      return this.attributes[t2];
    }
    canBeGroupedWith(t2, e2) {
      const i2 = t2.getAttributes(), r2 = i2[e2], o2 = this.attributes[e2];
      return o2 === r2 && !(gt(o2).group === false && !(() => {
        if (!ut) {
          ut = [];
          for (const t3 in n) {
            const { listAttribute: e3 } = n[t3];
            e3 != null && ut.push(e3);
          }
        }
        return ut;
      })().includes(i2[e2 + 1])) && (this.getDirection() === t2.getDirection() || t2.isEmpty());
    }
  };
  var Fe = function(t2) {
    return t2 = Ie(t2), t2 = Ne(t2);
  };
  var Ie = function(t2) {
    let e2 = false;
    const i2 = t2.getPieces();
    let n2 = i2.slice(0, i2.length - 1);
    const r2 = i2[i2.length - 1];
    return r2 ? (n2 = n2.map((t3) => t3.isBlockBreak() ? (e2 = true, Me(t3)) : t3), e2 ? new Te([...n2, r2]) : t2) : t2;
  };
  var Pe = Te.textForStringWithAttributes("\n", { blockBreak: true });
  var Ne = function(t2) {
    return Oe(t2) ? t2 : t2.appendText(Pe);
  };
  var Oe = function(t2) {
    const e2 = t2.getLength();
    if (e2 === 0)
      return false;
    return t2.getTextAtRange([e2 - 1, e2]).isBlockBreak();
  };
  var Me = (t2) => t2.copyWithoutAttribute("blockBreak");
  var je = function(t2) {
    const { listAttribute: e2 } = gt(t2);
    return e2 ? [e2, t2] : [t2];
  };
  var We = (t2) => t2.slice(-1)[0];
  var Ue = function(t2, e2) {
    const i2 = t2.lastIndexOf(e2);
    return i2 === -1 ? t2 : ot(t2, i2, 1);
  };
  var qe = class extends nt {
    static fromJSON(t2) {
      return new this(Array.from(t2).map((t3) => Be.fromJSON(t3)));
    }
    static fromString(t2, e2) {
      const i2 = Te.textForStringWithAttributes(t2, e2);
      return new this([new Be(i2)]);
    }
    constructor() {
      let t2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : [];
      super(...arguments), t2.length === 0 && (t2 = [new Be()]), this.blockList = ke.box(t2);
    }
    isEmpty() {
      const t2 = this.getBlockAtIndex(0);
      return this.blockList.length === 1 && t2.isEmpty() && !t2.hasAttributes();
    }
    copy() {
      const t2 = (arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}).consolidateBlocks ? this.blockList.consolidate().toArray() : this.blockList.toArray();
      return new this.constructor(t2);
    }
    copyUsingObjectsFromDocument(t2) {
      const e2 = new Yt(t2.getObjects());
      return this.copyUsingObjectMap(e2);
    }
    copyUsingObjectMap(t2) {
      const e2 = this.getBlocks().map((e3) => t2.find(e3) || e3.copyUsingObjectMap(t2));
      return new this.constructor(e2);
    }
    copyWithBaseBlockAttributes() {
      let t2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : [];
      const e2 = this.getBlocks().map((e3) => {
        const i2 = t2.concat(e3.getAttributes());
        return e3.copyWithAttributes(i2);
      });
      return new this.constructor(e2);
    }
    replaceBlock(t2, e2) {
      const i2 = this.blockList.indexOf(t2);
      return i2 === -1 ? this : new this.constructor(this.blockList.replaceObjectAtIndex(e2, i2));
    }
    insertDocumentAtRange(t2, e2) {
      const { blockList: i2 } = t2;
      e2 = Lt(e2);
      let [n2] = e2;
      const { index: r2, offset: o2 } = this.locationFromPosition(n2);
      let s2 = this;
      const a2 = this.getBlockAtPosition(n2);
      return Dt(e2) && a2.isEmpty() && !a2.hasAttributes() ? s2 = new this.constructor(s2.blockList.removeObjectAtIndex(r2)) : a2.getBlockBreakPosition() === o2 && n2++, s2 = s2.removeTextAtRange(e2), new this.constructor(s2.blockList.insertSplittableListAtPosition(i2, n2));
    }
    mergeDocumentAtRange(t2, e2) {
      let i2, n2;
      e2 = Lt(e2);
      const [r2] = e2, o2 = this.locationFromPosition(r2), s2 = this.getBlockAtIndex(o2.index).getAttributes(), a2 = t2.getBaseBlockAttributes(), l2 = s2.slice(-a2.length);
      if (rt(a2, l2)) {
        const e3 = s2.slice(0, -a2.length);
        i2 = t2.copyWithBaseBlockAttributes(e3);
      } else
        i2 = t2.copy({ consolidateBlocks: true }).copyWithBaseBlockAttributes(s2);
      const c2 = i2.getBlockCount(), h3 = i2.getBlockAtIndex(0);
      if (rt(s2, h3.getAttributes())) {
        const t3 = h3.getTextWithoutBlockBreak();
        if (n2 = this.insertTextAtRange(t3, e2), c2 > 1) {
          i2 = new this.constructor(i2.getBlocks().slice(1));
          const e3 = r2 + t3.getLength();
          n2 = n2.insertDocumentAtRange(i2, e3);
        }
      } else
        n2 = this.insertDocumentAtRange(i2, e2);
      return n2;
    }
    insertTextAtRange(t2, e2) {
      e2 = Lt(e2);
      const [i2] = e2, { index: n2, offset: r2 } = this.locationFromPosition(i2), o2 = this.removeTextAtRange(e2);
      return new this.constructor(o2.blockList.editObjectAtIndex(n2, (e3) => e3.copyWithText(e3.text.insertTextAtPosition(t2, r2))));
    }
    removeTextAtRange(t2) {
      let e2;
      t2 = Lt(t2);
      const [i2, n2] = t2;
      if (Dt(t2))
        return this;
      const [r2, o2] = Array.from(this.locationRangeFromRange(t2)), s2 = r2.index, a2 = r2.offset, l2 = this.getBlockAtIndex(s2), c2 = o2.index, h3 = o2.offset, u2 = this.getBlockAtIndex(c2);
      if (n2 - i2 == 1 && l2.getBlockBreakPosition() === a2 && u2.getBlockBreakPosition() !== h3 && u2.text.getStringAtPosition(h3) === "\n")
        e2 = this.blockList.editObjectAtIndex(c2, (t3) => t3.copyWithText(t3.text.removeTextAtRange([h3, h3 + 1])));
      else {
        let t3;
        const i3 = l2.text.getTextAtRange([0, a2]), n3 = u2.text.getTextAtRange([h3, u2.getLength()]), r3 = i3.appendText(n3);
        t3 = s2 !== c2 && a2 === 0 && l2.getAttributeLevel() >= u2.getAttributeLevel() ? u2.copyWithText(r3) : l2.copyWithText(r3);
        const o3 = c2 + 1 - s2;
        e2 = this.blockList.splice(s2, o3, t3);
      }
      return new this.constructor(e2);
    }
    moveTextFromRangeToPosition(t2, e2) {
      let i2;
      t2 = Lt(t2);
      const [n2, r2] = t2;
      if (n2 <= e2 && e2 <= r2)
        return this;
      let o2 = this.getDocumentAtRange(t2), s2 = this.removeTextAtRange(t2);
      const a2 = n2 < e2;
      a2 && (e2 -= o2.getLength());
      const [l2, ...c2] = o2.getBlocks();
      return c2.length === 0 ? (i2 = l2.getTextWithoutBlockBreak(), a2 && (e2 += 1)) : i2 = l2.text, s2 = s2.insertTextAtRange(i2, e2), c2.length === 0 ? s2 : (o2 = new this.constructor(c2), e2 += i2.getLength(), s2.insertDocumentAtRange(o2, e2));
    }
    addAttributeAtRange(t2, e2, i2) {
      let { blockList: n2 } = this;
      return this.eachBlockAtRange(i2, (i3, r2, o2) => n2 = n2.editObjectAtIndex(o2, function() {
        return gt(t2) ? i3.addAttribute(t2, e2) : r2[0] === r2[1] ? i3 : i3.copyWithText(i3.text.addAttributeAtRange(t2, e2, r2));
      })), new this.constructor(n2);
    }
    addAttribute(t2, e2) {
      let { blockList: i2 } = this;
      return this.eachBlock((n2, r2) => i2 = i2.editObjectAtIndex(r2, () => n2.addAttribute(t2, e2))), new this.constructor(i2);
    }
    removeAttributeAtRange(t2, e2) {
      let { blockList: i2 } = this;
      return this.eachBlockAtRange(e2, function(e3, n2, r2) {
        gt(t2) ? i2 = i2.editObjectAtIndex(r2, () => e3.removeAttribute(t2)) : n2[0] !== n2[1] && (i2 = i2.editObjectAtIndex(r2, () => e3.copyWithText(e3.text.removeAttributeAtRange(t2, n2))));
      }), new this.constructor(i2);
    }
    updateAttributesForAttachment(t2, e2) {
      const i2 = this.getRangeOfAttachment(e2), [n2] = Array.from(i2), { index: r2 } = this.locationFromPosition(n2), o2 = this.getTextAtIndex(r2);
      return new this.constructor(this.blockList.editObjectAtIndex(r2, (i3) => i3.copyWithText(o2.updateAttributesForAttachment(t2, e2))));
    }
    removeAttributeForAttachment(t2, e2) {
      const i2 = this.getRangeOfAttachment(e2);
      return this.removeAttributeAtRange(t2, i2);
    }
    insertBlockBreakAtRange(t2) {
      let e2;
      t2 = Lt(t2);
      const [i2] = t2, { offset: n2 } = this.locationFromPosition(i2), r2 = this.removeTextAtRange(t2);
      return n2 === 0 && (e2 = [new Be()]), new this.constructor(r2.blockList.insertSplittableListAtPosition(new ke(e2), i2));
    }
    applyBlockAttributeAtRange(t2, e2, i2) {
      const n2 = this.expandRangeToLineBreaksAndSplitBlocks(i2);
      let r2 = n2.document;
      i2 = n2.range;
      const o2 = gt(t2);
      if (o2.listAttribute) {
        r2 = r2.removeLastListAttributeAtRange(i2, { exceptAttributeName: t2 });
        const e3 = r2.convertLineBreaksToBlockBreaksInRange(i2);
        r2 = e3.document, i2 = e3.range;
      } else
        r2 = o2.exclusive ? r2.removeBlockAttributesAtRange(i2) : o2.terminal ? r2.removeLastTerminalAttributeAtRange(i2) : r2.consolidateBlocksAtRange(i2);
      return r2.addAttributeAtRange(t2, e2, i2);
    }
    removeLastListAttributeAtRange(t2) {
      let e2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}, { blockList: i2 } = this;
      return this.eachBlockAtRange(t2, function(t3, n2, r2) {
        const o2 = t3.getLastAttribute();
        o2 && gt(o2).listAttribute && o2 !== e2.exceptAttributeName && (i2 = i2.editObjectAtIndex(r2, () => t3.removeAttribute(o2)));
      }), new this.constructor(i2);
    }
    removeLastTerminalAttributeAtRange(t2) {
      let { blockList: e2 } = this;
      return this.eachBlockAtRange(t2, function(t3, i2, n2) {
        const r2 = t3.getLastAttribute();
        r2 && gt(r2).terminal && (e2 = e2.editObjectAtIndex(n2, () => t3.removeAttribute(r2)));
      }), new this.constructor(e2);
    }
    removeBlockAttributesAtRange(t2) {
      let { blockList: e2 } = this;
      return this.eachBlockAtRange(t2, function(t3, i2, n2) {
        t3.hasAttributes() && (e2 = e2.editObjectAtIndex(n2, () => t3.copyWithoutAttributes()));
      }), new this.constructor(e2);
    }
    expandRangeToLineBreaksAndSplitBlocks(t2) {
      let e2;
      t2 = Lt(t2);
      let [i2, n2] = t2;
      const r2 = this.locationFromPosition(i2), o2 = this.locationFromPosition(n2);
      let s2 = this;
      const a2 = s2.getBlockAtIndex(r2.index);
      if (r2.offset = a2.findLineBreakInDirectionFromPosition("backward", r2.offset), r2.offset != null && (e2 = s2.positionFromLocation(r2), s2 = s2.insertBlockBreakAtRange([e2, e2 + 1]), o2.index += 1, o2.offset -= s2.getBlockAtIndex(r2.index).getLength(), r2.index += 1), r2.offset = 0, o2.offset === 0 && o2.index > r2.index)
        o2.index -= 1, o2.offset = s2.getBlockAtIndex(o2.index).getBlockBreakPosition();
      else {
        const t3 = s2.getBlockAtIndex(o2.index);
        t3.text.getStringAtRange([o2.offset - 1, o2.offset]) === "\n" ? o2.offset -= 1 : o2.offset = t3.findLineBreakInDirectionFromPosition("forward", o2.offset), o2.offset !== t3.getBlockBreakPosition() && (e2 = s2.positionFromLocation(o2), s2 = s2.insertBlockBreakAtRange([e2, e2 + 1]));
      }
      return i2 = s2.positionFromLocation(r2), n2 = s2.positionFromLocation(o2), { document: s2, range: t2 = Lt([i2, n2]) };
    }
    convertLineBreaksToBlockBreaksInRange(t2) {
      t2 = Lt(t2);
      let [e2] = t2;
      const i2 = this.getStringAtRange(t2).slice(0, -1);
      let n2 = this;
      return i2.replace(/.*?\n/g, function(t3) {
        e2 += t3.length, n2 = n2.insertBlockBreakAtRange([e2 - 1, e2]);
      }), { document: n2, range: t2 };
    }
    consolidateBlocksAtRange(t2) {
      t2 = Lt(t2);
      const [e2, i2] = t2, n2 = this.locationFromPosition(e2).index, r2 = this.locationFromPosition(i2).index;
      return new this.constructor(this.blockList.consolidateFromIndexToIndex(n2, r2));
    }
    getDocumentAtRange(t2) {
      t2 = Lt(t2);
      const e2 = this.blockList.getSplittableListInRange(t2).toArray();
      return new this.constructor(e2);
    }
    getStringAtRange(t2) {
      let e2;
      const i2 = t2 = Lt(t2);
      return i2[i2.length - 1] !== this.getLength() && (e2 = -1), this.getDocumentAtRange(t2).toString().slice(0, e2);
    }
    getBlockAtIndex(t2) {
      return this.blockList.getObjectAtIndex(t2);
    }
    getBlockAtPosition(t2) {
      const { index: e2 } = this.locationFromPosition(t2);
      return this.getBlockAtIndex(e2);
    }
    getTextAtIndex(t2) {
      var e2;
      return (e2 = this.getBlockAtIndex(t2)) === null || e2 === void 0 ? void 0 : e2.text;
    }
    getTextAtPosition(t2) {
      const { index: e2 } = this.locationFromPosition(t2);
      return this.getTextAtIndex(e2);
    }
    getPieceAtPosition(t2) {
      const { index: e2, offset: i2 } = this.locationFromPosition(t2);
      return this.getTextAtIndex(e2).getPieceAtPosition(i2);
    }
    getCharacterAtPosition(t2) {
      const { index: e2, offset: i2 } = this.locationFromPosition(t2);
      return this.getTextAtIndex(e2).getStringAtRange([i2, i2 + 1]);
    }
    getLength() {
      return this.blockList.getEndPosition();
    }
    getBlocks() {
      return this.blockList.toArray();
    }
    getBlockCount() {
      return this.blockList.length;
    }
    getEditCount() {
      return this.editCount;
    }
    eachBlock(t2) {
      return this.blockList.eachObject(t2);
    }
    eachBlockAtRange(t2, e2) {
      let i2, n2;
      t2 = Lt(t2);
      const [r2, o2] = t2, s2 = this.locationFromPosition(r2), a2 = this.locationFromPosition(o2);
      if (s2.index === a2.index)
        return i2 = this.getBlockAtIndex(s2.index), n2 = [s2.offset, a2.offset], e2(i2, n2, s2.index);
      for (let t3 = s2.index; t3 <= a2.index; t3++)
        if (i2 = this.getBlockAtIndex(t3), i2) {
          switch (t3) {
            case s2.index:
              n2 = [s2.offset, i2.text.getLength()];
              break;
            case a2.index:
              n2 = [0, a2.offset];
              break;
            default:
              n2 = [0, i2.text.getLength()];
          }
          e2(i2, n2, t3);
        }
    }
    getCommonAttributesAtRange(t2) {
      t2 = Lt(t2);
      const [e2] = t2;
      if (Dt(t2))
        return this.getCommonAttributesAtPosition(e2);
      {
        const e3 = [], i2 = [];
        return this.eachBlockAtRange(t2, function(t3, n2) {
          if (n2[0] !== n2[1])
            return e3.push(t3.text.getCommonAttributesAtRange(n2)), i2.push(Ve(t3));
        }), _t.fromCommonAttributesOfObjects(e3).merge(_t.fromCommonAttributesOfObjects(i2)).toObject();
      }
    }
    getCommonAttributesAtPosition(t2) {
      let e2, i2;
      const { index: n2, offset: r2 } = this.locationFromPosition(t2), o2 = this.getBlockAtIndex(n2);
      if (!o2)
        return {};
      const s2 = Ve(o2), a2 = o2.text.getAttributesAtPosition(r2), l2 = o2.text.getAttributesAtPosition(r2 - 1), c2 = Object.keys(W).filter((t3) => W[t3].inheritable);
      for (e2 in l2)
        i2 = l2[e2], (i2 === a2[e2] || c2.includes(e2)) && (s2[e2] = i2);
      return s2;
    }
    getRangeOfCommonAttributeAtPosition(t2, e2) {
      const { index: i2, offset: n2 } = this.locationFromPosition(e2), r2 = this.getTextAtIndex(i2), [o2, s2] = Array.from(r2.getExpandedRangeForAttributeAtOffset(t2, n2)), a2 = this.positionFromLocation({ index: i2, offset: o2 }), l2 = this.positionFromLocation({ index: i2, offset: s2 });
      return Lt([a2, l2]);
    }
    getBaseBlockAttributes() {
      let t2 = this.getBlockAtIndex(0).getAttributes();
      for (let e2 = 1; e2 < this.getBlockCount(); e2++) {
        const i2 = this.getBlockAtIndex(e2).getAttributes(), n2 = Math.min(t2.length, i2.length);
        t2 = (() => {
          const e3 = [];
          for (let r2 = 0; r2 < n2 && i2[r2] === t2[r2]; r2++)
            e3.push(i2[r2]);
          return e3;
        })();
      }
      return t2;
    }
    getAttachmentById(t2) {
      for (const e2 of this.getAttachments())
        if (e2.id === t2)
          return e2;
    }
    getAttachmentPieces() {
      let t2 = [];
      return this.blockList.eachObject((e2) => {
        let { text: i2 } = e2;
        return t2 = t2.concat(i2.getAttachmentPieces());
      }), t2;
    }
    getAttachments() {
      return this.getAttachmentPieces().map((t2) => t2.attachment);
    }
    getRangeOfAttachment(t2) {
      let e2 = 0;
      const i2 = this.blockList.toArray();
      for (let n2 = 0; n2 < i2.length; n2++) {
        const { text: r2 } = i2[n2], o2 = r2.getRangeOfAttachment(t2);
        if (o2)
          return Lt([e2 + o2[0], e2 + o2[1]]);
        e2 += r2.getLength();
      }
    }
    getLocationRangeOfAttachment(t2) {
      const e2 = this.getRangeOfAttachment(t2);
      return this.locationRangeFromRange(e2);
    }
    getAttachmentPieceForAttachment(t2) {
      for (const e2 of this.getAttachmentPieces())
        if (e2.attachment === t2)
          return e2;
    }
    findRangesForBlockAttribute(t2) {
      let e2 = 0;
      const i2 = [];
      return this.getBlocks().forEach((n2) => {
        const r2 = n2.getLength();
        n2.hasAttribute(t2) && i2.push([e2, e2 + r2]), e2 += r2;
      }), i2;
    }
    findRangesForTextAttribute(t2) {
      let { withValue: e2 } = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}, i2 = 0, n2 = [];
      const r2 = [];
      return this.getPieces().forEach((o2) => {
        const s2 = o2.getLength();
        (function(i3) {
          return e2 ? i3.getAttribute(t2) === e2 : i3.hasAttribute(t2);
        })(o2) && (n2[1] === i2 ? n2[1] = i2 + s2 : r2.push(n2 = [i2, i2 + s2])), i2 += s2;
      }), r2;
    }
    locationFromPosition(t2) {
      const e2 = this.blockList.findIndexAndOffsetAtPosition(Math.max(0, t2));
      if (e2.index != null)
        return e2;
      {
        const t3 = this.getBlocks();
        return { index: t3.length - 1, offset: t3[t3.length - 1].getLength() };
      }
    }
    positionFromLocation(t2) {
      return this.blockList.findPositionAtIndexAndOffset(t2.index, t2.offset);
    }
    locationRangeFromPosition(t2) {
      return Lt(this.locationFromPosition(t2));
    }
    locationRangeFromRange(t2) {
      if (!(t2 = Lt(t2)))
        return;
      const [e2, i2] = Array.from(t2), n2 = this.locationFromPosition(e2), r2 = this.locationFromPosition(i2);
      return Lt([n2, r2]);
    }
    rangeFromLocationRange(t2) {
      let e2;
      t2 = Lt(t2);
      const i2 = this.positionFromLocation(t2[0]);
      return Dt(t2) || (e2 = this.positionFromLocation(t2[1])), Lt([i2, e2]);
    }
    isEqualTo(t2) {
      return this.blockList.isEqualTo(t2 == null ? void 0 : t2.blockList);
    }
    getTexts() {
      return this.getBlocks().map((t2) => t2.text);
    }
    getPieces() {
      const t2 = [];
      return Array.from(this.getTexts()).forEach((e2) => {
        t2.push(...Array.from(e2.getPieces() || []));
      }), t2;
    }
    getObjects() {
      return this.getBlocks().concat(this.getTexts()).concat(this.getPieces());
    }
    toSerializableDocument() {
      const t2 = [];
      return this.blockList.eachObject((e2) => t2.push(e2.copyWithText(e2.text.toSerializableText()))), new this.constructor(t2);
    }
    toString() {
      return this.blockList.toString();
    }
    toJSON() {
      return this.blockList.toJSON();
    }
    toConsole() {
      return JSON.stringify(this.blockList.toArray().map((t2) => JSON.parse(t2.text.toConsole())));
    }
  };
  var Ve = function(t2) {
    const e2 = {}, i2 = t2.getLastAttribute();
    return i2 && (e2[i2] = true), e2;
  };
  var ze = "style href src width height class".split(" ");
  var _e = "javascript:".split(" ");
  var He = "script iframe form".split(" ");
  var Je = class extends z {
    static sanitize(t2, e2) {
      const i2 = new this(t2, e2);
      return i2.sanitize(), i2;
    }
    constructor(t2) {
      let { allowedAttributes: e2, forbiddenProtocols: i2, forbiddenElements: n2 } = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
      super(...arguments), this.allowedAttributes = e2 || ze, this.forbiddenProtocols = i2 || _e, this.forbiddenElements = n2 || He, this.body = Ke(t2);
    }
    sanitize() {
      return this.sanitizeElements(), this.normalizeListElementNesting();
    }
    getHTML() {
      return this.body.innerHTML;
    }
    getBody() {
      return this.body;
    }
    sanitizeElements() {
      const t2 = S(this.body), e2 = [];
      for (; t2.nextNode(); ) {
        const i2 = t2.currentNode;
        switch (i2.nodeType) {
          case Node.ELEMENT_NODE:
            this.elementIsRemovable(i2) ? e2.push(i2) : this.sanitizeElement(i2);
            break;
          case Node.COMMENT_NODE:
            e2.push(i2);
        }
      }
      return e2.forEach((t3) => R(t3)), this.body;
    }
    sanitizeElement(t2) {
      return t2.hasAttribute("href") && this.forbiddenProtocols.includes(t2.protocol) && t2.removeAttribute("href"), Array.from(t2.attributes).forEach((e2) => {
        let { name: i2 } = e2;
        this.allowedAttributes.includes(i2) || i2.indexOf("data-trix") === 0 || t2.removeAttribute(i2);
      }), t2;
    }
    normalizeListElementNesting() {
      return Array.from(this.body.querySelectorAll("ul,ol")).forEach((t2) => {
        const e2 = t2.previousElementSibling;
        e2 && E(e2) === "li" && e2.appendChild(t2);
      }), this.body;
    }
    elementIsRemovable(t2) {
      if ((t2 == null ? void 0 : t2.nodeType) === Node.ELEMENT_NODE)
        return this.elementIsForbidden(t2) || this.elementIsntSerializable(t2);
    }
    elementIsForbidden(t2) {
      return this.forbiddenElements.includes(E(t2));
    }
    elementIsntSerializable(t2) {
      return t2.getAttribute("data-trix-serialize") === "false" && !P(t2);
    }
  };
  var Ke = function() {
    let t2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : "";
    t2 = t2.replace(/<\/html[^>]*>[^]*$/i, "</html>");
    const e2 = document.implementation.createHTMLDocument("");
    return e2.documentElement.innerHTML = t2, Array.from(e2.head.querySelectorAll("style")).forEach((t3) => {
      e2.body.appendChild(t3);
    }), e2.body;
  };
  var Ge = function(t2) {
    let e2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
    return { string: t2 = Wt(t2), attributes: e2, type: "string" };
  };
  var $e = (t2, e2) => {
    try {
      return JSON.parse(t2.getAttribute("data-trix-".concat(e2)));
    } catch (t3) {
      return {};
    }
  };
  var Xe = class extends z {
    static parse(t2, e2) {
      const i2 = new this(t2, e2);
      return i2.parse(), i2;
    }
    constructor(t2) {
      let { referenceElement: e2 } = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
      super(...arguments), this.html = t2, this.referenceElement = e2, this.blocks = [], this.blockElements = [], this.processedElements = [];
    }
    getDocument() {
      return qe.fromJSON(this.blocks);
    }
    parse() {
      try {
        this.createHiddenContainer();
        const t2 = Je.sanitize(this.html).getHTML();
        this.containerElement.innerHTML = t2;
        const e2 = S(this.containerElement, { usingFilter: ti });
        for (; e2.nextNode(); )
          this.processNode(e2.currentNode);
        return this.translateBlockElementMarginsToNewlines();
      } finally {
        this.removeHiddenContainer();
      }
    }
    createHiddenContainer() {
      return this.referenceElement ? (this.containerElement = this.referenceElement.cloneNode(false), this.containerElement.removeAttribute("id"), this.containerElement.setAttribute("data-trix-internal", ""), this.containerElement.style.display = "none", this.referenceElement.parentNode.insertBefore(this.containerElement, this.referenceElement.nextSibling)) : (this.containerElement = k({ tagName: "div", style: { display: "none" } }), document.body.appendChild(this.containerElement));
    }
    removeHiddenContainer() {
      return R(this.containerElement);
    }
    processNode(t2) {
      switch (t2.nodeType) {
        case Node.TEXT_NODE:
          if (!this.isInsignificantTextNode(t2))
            return this.appendBlockForTextNode(t2), this.processTextNode(t2);
          break;
        case Node.ELEMENT_NODE:
          return this.appendBlockForElement(t2), this.processElement(t2);
      }
    }
    appendBlockForTextNode(t2) {
      const e2 = t2.parentNode;
      if (e2 === this.currentBlockElement && this.isBlockElement(t2.previousSibling))
        return this.appendStringWithAttributes("\n");
      if (e2 === this.containerElement || this.isBlockElement(e2)) {
        var i2;
        const t3 = this.getBlockAttributes(e2);
        rt(t3, (i2 = this.currentBlock) === null || i2 === void 0 ? void 0 : i2.attributes) || (this.currentBlock = this.appendBlockForAttributesWithElement(t3, e2), this.currentBlockElement = e2);
      }
    }
    appendBlockForElement(t2) {
      const e2 = this.isBlockElement(t2), i2 = y(this.currentBlockElement, t2);
      if (e2 && !this.isBlockElement(t2.firstChild)) {
        if (!this.isInsignificantTextNode(t2.firstChild) || !this.isBlockElement(t2.firstElementChild)) {
          const e3 = this.getBlockAttributes(t2);
          if (t2.firstChild) {
            if (i2 && rt(e3, this.currentBlock.attributes))
              return this.appendStringWithAttributes("\n");
            this.currentBlock = this.appendBlockForAttributesWithElement(e3, t2), this.currentBlockElement = t2;
          }
        }
      } else if (this.currentBlockElement && !i2 && !e2) {
        const e3 = this.findParentBlockElement(t2);
        if (e3)
          return this.appendBlockForElement(e3);
        this.currentBlock = this.appendEmptyBlock(), this.currentBlockElement = null;
      }
    }
    findParentBlockElement(t2) {
      let { parentElement: e2 } = t2;
      for (; e2 && e2 !== this.containerElement; ) {
        if (this.isBlockElement(e2) && this.blockElements.includes(e2))
          return e2;
        e2 = e2.parentElement;
      }
      return null;
    }
    processTextNode(t2) {
      let e2 = t2.data;
      var i2;
      Ye(t2.parentNode) || (e2 = qt(e2), ni((i2 = t2.previousSibling) === null || i2 === void 0 ? void 0 : i2.textContent) && (e2 = ei(e2)));
      return this.appendStringWithAttributes(e2, this.getTextAttributes(t2.parentNode));
    }
    processElement(t2) {
      let e2;
      if (P(t2)) {
        if (e2 = $e(t2, "attachment"), Object.keys(e2).length) {
          const i2 = this.getTextAttributes(t2);
          this.appendAttachmentWithAttributes(e2, i2), t2.innerHTML = "";
        }
        return this.processedElements.push(t2);
      }
      switch (E(t2)) {
        case "br":
          return this.isExtraBR(t2) || this.isBlockElement(t2.nextSibling) || this.appendStringWithAttributes("\n", this.getTextAttributes(t2)), this.processedElements.push(t2);
        case "img":
          e2 = { url: t2.getAttribute("src"), contentType: "image" };
          const i2 = ((t3) => {
            const e3 = t3.getAttribute("width"), i3 = t3.getAttribute("height"), n2 = {};
            return e3 && (n2.width = parseInt(e3, 10)), i3 && (n2.height = parseInt(i3, 10)), n2;
          })(t2);
          for (const t3 in i2) {
            const n2 = i2[t3];
            e2[t3] = n2;
          }
          return this.appendAttachmentWithAttributes(e2, this.getTextAttributes(t2)), this.processedElements.push(t2);
        case "tr":
          if (this.needsTableSeparator(t2))
            return this.appendStringWithAttributes(j.tableRowSeparator);
          break;
        case "td":
          if (this.needsTableSeparator(t2))
            return this.appendStringWithAttributes(j.tableCellSeparator);
      }
    }
    appendBlockForAttributesWithElement(t2, e2) {
      this.blockElements.push(e2);
      const i2 = function() {
        return { text: [], attributes: arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {} };
      }(t2);
      return this.blocks.push(i2), i2;
    }
    appendEmptyBlock() {
      return this.appendBlockForAttributesWithElement([], null);
    }
    appendStringWithAttributes(t2, e2) {
      return this.appendPiece(Ge(t2, e2));
    }
    appendAttachmentWithAttributes(t2, e2) {
      return this.appendPiece(function(t3) {
        return { attachment: t3, attributes: arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}, type: "attachment" };
      }(t2, e2));
    }
    appendPiece(t2) {
      return this.blocks.length === 0 && this.appendEmptyBlock(), this.blocks[this.blocks.length - 1].text.push(t2);
    }
    appendStringToTextAtIndex(t2, e2) {
      const { text: i2 } = this.blocks[e2], n2 = i2[i2.length - 1];
      if ((n2 == null ? void 0 : n2.type) !== "string")
        return i2.push(Ge(t2));
      n2.string += t2;
    }
    prependStringToTextAtIndex(t2, e2) {
      const { text: i2 } = this.blocks[e2], n2 = i2[0];
      if ((n2 == null ? void 0 : n2.type) !== "string")
        return i2.unshift(Ge(t2));
      n2.string = t2 + n2.string;
    }
    getTextAttributes(t2) {
      let e2;
      const i2 = {};
      for (const n2 in W) {
        const r2 = W[n2];
        if (r2.tagName && A(t2, { matchingSelector: r2.tagName, untilNode: this.containerElement }))
          i2[n2] = true;
        else if (r2.parser) {
          if (e2 = r2.parser(t2), e2) {
            let o2 = false;
            for (const i3 of this.findBlockElementAncestors(t2))
              if (r2.parser(i3) === e2) {
                o2 = true;
                break;
              }
            o2 || (i2[n2] = e2);
          }
        } else
          r2.styleProperty && (e2 = t2.style[r2.styleProperty], e2 && (i2[n2] = e2));
      }
      if (P(t2)) {
        const n2 = $e(t2, "attributes");
        for (const t3 in n2)
          e2 = n2[t3], i2[t3] = e2;
      }
      return i2;
    }
    getBlockAttributes(t2) {
      const e2 = [];
      for (; t2 && t2 !== this.containerElement; ) {
        for (const r2 in n) {
          const o2 = n[r2];
          var i2;
          if (o2.parse !== false) {
            if (E(t2) === o2.tagName)
              ((i2 = o2.test) !== null && i2 !== void 0 && i2.call(o2, t2) || !o2.test) && (e2.push(r2), o2.listAttribute && e2.push(o2.listAttribute));
          }
        }
        t2 = t2.parentNode;
      }
      return e2.reverse();
    }
    findBlockElementAncestors(t2) {
      const e2 = [];
      for (; t2 && t2 !== this.containerElement; ) {
        const i2 = E(t2);
        D().includes(i2) && e2.push(t2), t2 = t2.parentNode;
      }
      return e2;
    }
    isBlockElement(t2) {
      if ((t2 == null ? void 0 : t2.nodeType) === Node.ELEMENT_NODE && !P(t2) && !A(t2, { matchingSelector: "td", untilNode: this.containerElement }))
        return D().includes(E(t2)) || window.getComputedStyle(t2).display === "block";
    }
    isInsignificantTextNode(t2) {
      if ((t2 == null ? void 0 : t2.nodeType) !== Node.TEXT_NODE)
        return;
      if (!ii(t2.data))
        return;
      const { parentNode: e2, previousSibling: i2, nextSibling: n2 } = t2;
      return Qe(e2.previousSibling) && !this.isBlockElement(e2.previousSibling) || Ye(e2) ? void 0 : !i2 || this.isBlockElement(i2) || !n2 || this.isBlockElement(n2);
    }
    isExtraBR(t2) {
      return E(t2) === "br" && this.isBlockElement(t2.parentNode) && t2.parentNode.lastChild === t2;
    }
    needsTableSeparator(t2) {
      if (j.removeBlankTableCells) {
        var e2;
        const i2 = (e2 = t2.previousSibling) === null || e2 === void 0 ? void 0 : e2.textContent;
        return i2 && /\S/.test(i2);
      }
      return t2.previousSibling;
    }
    translateBlockElementMarginsToNewlines() {
      const t2 = this.getMarginOfDefaultBlockElement();
      for (let e2 = 0; e2 < this.blocks.length; e2++) {
        const i2 = this.getMarginOfBlockElementAtIndex(e2);
        i2 && (i2.top > 2 * t2.top && this.prependStringToTextAtIndex("\n", e2), i2.bottom > 2 * t2.bottom && this.appendStringToTextAtIndex("\n", e2));
      }
    }
    getMarginOfBlockElementAtIndex(t2) {
      const e2 = this.blockElements[t2];
      if (e2 && e2.textContent && !D().includes(E(e2)) && !this.processedElements.includes(e2))
        return Ze(e2);
    }
    getMarginOfDefaultBlockElement() {
      const t2 = k(n.default.tagName);
      return this.containerElement.appendChild(t2), Ze(t2);
    }
  };
  var Ye = function(t2) {
    const { whiteSpace: e2 } = window.getComputedStyle(t2);
    return ["pre", "pre-wrap", "pre-line"].includes(e2);
  };
  var Qe = (t2) => t2 && !ni(t2.textContent);
  var Ze = function(t2) {
    const e2 = window.getComputedStyle(t2);
    if (e2.display === "block")
      return { top: parseInt(e2.marginTop), bottom: parseInt(e2.marginBottom) };
  };
  var ti = function(t2) {
    return E(t2) === "style" ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT;
  };
  var ei = (t2) => t2.replace(new RegExp("^".concat(Ut.source, "+")), "");
  var ii = (t2) => new RegExp("^".concat(Ut.source, "*$")).test(t2);
  var ni = (t2) => /\s$/.test(t2);
  var ri = ["contenteditable", "data-trix-id", "data-trix-store-key", "data-trix-mutable", "data-trix-placeholder", "tabindex"];
  var oi = "data-trix-serialized-attributes";
  var si = "[".concat(oi, "]");
  var ai = new RegExp("<!--block-->", "g");
  var li = { "application/json": function(t2) {
    let e2;
    if (t2 instanceof qe)
      e2 = t2;
    else {
      if (!(t2 instanceof HTMLElement))
        throw new Error("unserializable object");
      e2 = Xe.parse(t2.innerHTML).getDocument();
    }
    return e2.toSerializableDocument().toJSONString();
  }, "text/html": function(t2) {
    let e2;
    if (t2 instanceof qe)
      e2 = ge.render(t2);
    else {
      if (!(t2 instanceof HTMLElement))
        throw new Error("unserializable object");
      e2 = t2.cloneNode(true);
    }
    return Array.from(e2.querySelectorAll("[data-trix-serialize=false]")).forEach((t3) => {
      R(t3);
    }), ri.forEach((t3) => {
      Array.from(e2.querySelectorAll("[".concat(t3, "]"))).forEach((e3) => {
        e3.removeAttribute(t3);
      });
    }), Array.from(e2.querySelectorAll(si)).forEach((t3) => {
      try {
        const e3 = JSON.parse(t3.getAttribute(oi));
        t3.removeAttribute(oi);
        for (const i2 in e3) {
          const n2 = e3[i2];
          t3.setAttribute(i2, n2);
        }
      } catch (t4) {
      }
    }), e2.innerHTML.replace(ai, "");
  } };
  var ci = Object.freeze({ __proto__: null });
  var hi = class extends z {
    constructor(t2, e2) {
      super(...arguments), this.attachmentManager = t2, this.attachment = e2, this.id = this.attachment.id, this.file = this.attachment.file;
    }
    remove() {
      return this.attachmentManager.requestRemovalOfAttachment(this.attachment);
    }
  };
  hi.proxyMethod("attachment.getAttribute"), hi.proxyMethod("attachment.hasAttribute"), hi.proxyMethod("attachment.setAttribute"), hi.proxyMethod("attachment.getAttributes"), hi.proxyMethod("attachment.setAttributes"), hi.proxyMethod("attachment.isPending"), hi.proxyMethod("attachment.isPreviewable"), hi.proxyMethod("attachment.getURL"), hi.proxyMethod("attachment.getHref"), hi.proxyMethod("attachment.getFilename"), hi.proxyMethod("attachment.getFilesize"), hi.proxyMethod("attachment.getFormattedFilesize"), hi.proxyMethod("attachment.getExtension"), hi.proxyMethod("attachment.getContentType"), hi.proxyMethod("attachment.getFile"), hi.proxyMethod("attachment.setFile"), hi.proxyMethod("attachment.releaseFile"), hi.proxyMethod("attachment.getUploadProgress"), hi.proxyMethod("attachment.setUploadProgress");
  var ui = class extends z {
    constructor() {
      let t2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : [];
      super(...arguments), this.managedAttachments = {}, Array.from(t2).forEach((t3) => {
        this.manageAttachment(t3);
      });
    }
    getAttachments() {
      const t2 = [];
      for (const e2 in this.managedAttachments) {
        const i2 = this.managedAttachments[e2];
        t2.push(i2);
      }
      return t2;
    }
    manageAttachment(t2) {
      return this.managedAttachments[t2.id] || (this.managedAttachments[t2.id] = new hi(this, t2)), this.managedAttachments[t2.id];
    }
    attachmentIsManaged(t2) {
      return t2.id in this.managedAttachments;
    }
    requestRemovalOfAttachment(t2) {
      var e2, i2;
      if (this.attachmentIsManaged(t2))
        return (e2 = this.delegate) === null || e2 === void 0 || (i2 = e2.attachmentManagerDidRequestRemovalOfAttachment) === null || i2 === void 0 ? void 0 : i2.call(e2, t2);
    }
    unmanageAttachment(t2) {
      const e2 = this.managedAttachments[t2.id];
      return delete this.managedAttachments[t2.id], e2;
    }
  };
  var di = class {
    constructor(t2) {
      this.composition = t2, this.document = this.composition.document;
      const e2 = this.composition.getSelectedRange();
      this.startPosition = e2[0], this.endPosition = e2[1], this.startLocation = this.document.locationFromPosition(this.startPosition), this.endLocation = this.document.locationFromPosition(this.endPosition), this.block = this.document.getBlockAtIndex(this.endLocation.index), this.breaksOnReturn = this.block.breaksOnReturn(), this.previousCharacter = this.block.text.getStringAtPosition(this.endLocation.offset - 1), this.nextCharacter = this.block.text.getStringAtPosition(this.endLocation.offset);
    }
    shouldInsertBlockBreak() {
      return this.block.hasAttributes() && this.block.isListItem() && !this.block.isEmpty() ? this.startLocation.offset !== 0 : this.breaksOnReturn && this.nextCharacter !== "\n";
    }
    shouldBreakFormattedBlock() {
      return this.block.hasAttributes() && !this.block.isListItem() && (this.breaksOnReturn && this.nextCharacter === "\n" || this.previousCharacter === "\n");
    }
    shouldDecreaseListLevel() {
      return this.block.hasAttributes() && this.block.isListItem() && this.block.isEmpty();
    }
    shouldPrependListItem() {
      return this.block.isListItem() && this.startLocation.offset === 0 && !this.block.isEmpty();
    }
    shouldRemoveLastBlockAttribute() {
      return this.block.hasAttributes() && !this.block.isListItem() && this.block.isEmpty();
    }
  };
  var gi = class extends z {
    constructor() {
      super(...arguments), this.document = new qe(), this.attachments = [], this.currentAttributes = {}, this.revision = 0;
    }
    setDocument(t2) {
      var e2, i2;
      if (!t2.isEqualTo(this.document))
        return this.document = t2, this.refreshAttachments(), this.revision++, (e2 = this.delegate) === null || e2 === void 0 || (i2 = e2.compositionDidChangeDocument) === null || i2 === void 0 ? void 0 : i2.call(e2, t2);
    }
    getSnapshot() {
      return { document: this.document, selectedRange: this.getSelectedRange() };
    }
    loadSnapshot(t2) {
      var e2, i2, n2, r2;
      let { document: o2, selectedRange: s2 } = t2;
      return (e2 = this.delegate) === null || e2 === void 0 || (i2 = e2.compositionWillLoadSnapshot) === null || i2 === void 0 || i2.call(e2), this.setDocument(o2 != null ? o2 : new qe()), this.setSelection(s2 != null ? s2 : [0, 0]), (n2 = this.delegate) === null || n2 === void 0 || (r2 = n2.compositionDidLoadSnapshot) === null || r2 === void 0 ? void 0 : r2.call(n2);
    }
    insertText(t2) {
      let { updatePosition: e2 } = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : { updatePosition: true };
      const i2 = this.getSelectedRange();
      this.setDocument(this.document.insertTextAtRange(t2, i2));
      const n2 = i2[0], r2 = n2 + t2.getLength();
      return e2 && this.setSelection(r2), this.notifyDelegateOfInsertionAtRange([n2, r2]);
    }
    insertBlock() {
      let t2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : new Be();
      const e2 = new qe([t2]);
      return this.insertDocument(e2);
    }
    insertDocument() {
      let t2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : new qe();
      const e2 = this.getSelectedRange();
      this.setDocument(this.document.insertDocumentAtRange(t2, e2));
      const i2 = e2[0], n2 = i2 + t2.getLength();
      return this.setSelection(n2), this.notifyDelegateOfInsertionAtRange([i2, n2]);
    }
    insertString(t2, e2) {
      const i2 = this.getCurrentTextAttributes(), n2 = Te.textForStringWithAttributes(t2, i2);
      return this.insertText(n2, e2);
    }
    insertBlockBreak() {
      const t2 = this.getSelectedRange();
      this.setDocument(this.document.insertBlockBreakAtRange(t2));
      const e2 = t2[0], i2 = e2 + 1;
      return this.setSelection(i2), this.notifyDelegateOfInsertionAtRange([e2, i2]);
    }
    insertLineBreak() {
      const t2 = new di(this);
      if (t2.shouldDecreaseListLevel())
        return this.decreaseListLevel(), this.setSelection(t2.startPosition);
      if (t2.shouldPrependListItem()) {
        const e2 = new qe([t2.block.copyWithoutText()]);
        return this.insertDocument(e2);
      }
      return t2.shouldInsertBlockBreak() ? this.insertBlockBreak() : t2.shouldRemoveLastBlockAttribute() ? this.removeLastBlockAttribute() : t2.shouldBreakFormattedBlock() ? this.breakFormattedBlock(t2) : this.insertString("\n");
    }
    insertHTML(t2) {
      const e2 = Xe.parse(t2).getDocument(), i2 = this.getSelectedRange();
      this.setDocument(this.document.mergeDocumentAtRange(e2, i2));
      const n2 = i2[0], r2 = n2 + e2.getLength() - 1;
      return this.setSelection(r2), this.notifyDelegateOfInsertionAtRange([n2, r2]);
    }
    replaceHTML(t2) {
      const e2 = Xe.parse(t2).getDocument().copyUsingObjectsFromDocument(this.document), i2 = this.getLocationRange({ strict: false }), n2 = this.document.rangeFromLocationRange(i2);
      return this.setDocument(e2), this.setSelection(n2);
    }
    insertFile(t2) {
      return this.insertFiles([t2]);
    }
    insertFiles(t2) {
      const e2 = [];
      return Array.from(t2).forEach((t3) => {
        var i2;
        if ((i2 = this.delegate) !== null && i2 !== void 0 && i2.compositionShouldAcceptFile(t3)) {
          const i3 = Re.attachmentForFile(t3);
          e2.push(i3);
        }
      }), this.insertAttachments(e2);
    }
    insertAttachment(t2) {
      return this.insertAttachments([t2]);
    }
    insertAttachments(t2) {
      let e2 = new Te();
      return Array.from(t2).forEach((t3) => {
        var n2;
        const r2 = t3.getType(), o2 = (n2 = i[r2]) === null || n2 === void 0 ? void 0 : n2.presentation, s2 = this.getCurrentTextAttributes();
        o2 && (s2.presentation = o2);
        const a2 = Te.textForAttachmentWithAttributes(t3, s2);
        e2 = e2.appendText(a2);
      }), this.insertText(e2);
    }
    shouldManageDeletingInDirection(t2) {
      const e2 = this.getLocationRange();
      if (Dt(e2)) {
        if (t2 === "backward" && e2[0].offset === 0)
          return true;
        if (this.shouldManageMovingCursorInDirection(t2))
          return true;
      } else if (e2[0].index !== e2[1].index)
        return true;
      return false;
    }
    deleteInDirection(t2) {
      let e2, i2, n2, { length: r2 } = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
      const o2 = this.getLocationRange();
      let s2 = this.getSelectedRange();
      const a2 = Dt(s2);
      if (a2 ? i2 = t2 === "backward" && o2[0].offset === 0 : n2 = o2[0].index !== o2[1].index, i2 && this.canDecreaseBlockAttributeLevel()) {
        const t3 = this.getBlock();
        if (t3.isListItem() ? this.decreaseListLevel() : this.decreaseBlockAttributeLevel(), this.setSelection(s2[0]), t3.isEmpty())
          return false;
      }
      return a2 && (s2 = this.getExpandedRangeInDirection(t2, { length: r2 }), t2 === "backward" && (e2 = this.getAttachmentAtRange(s2))), e2 ? (this.editAttachment(e2), false) : (this.setDocument(this.document.removeTextAtRange(s2)), this.setSelection(s2[0]), !i2 && !n2 && void 0);
    }
    moveTextFromRange(t2) {
      const [e2] = Array.from(this.getSelectedRange());
      return this.setDocument(this.document.moveTextFromRangeToPosition(t2, e2)), this.setSelection(e2);
    }
    removeAttachment(t2) {
      const e2 = this.document.getRangeOfAttachment(t2);
      if (e2)
        return this.stopEditingAttachment(), this.setDocument(this.document.removeTextAtRange(e2)), this.setSelection(e2[0]);
    }
    removeLastBlockAttribute() {
      const [t2, e2] = Array.from(this.getSelectedRange()), i2 = this.document.getBlockAtPosition(e2);
      return this.removeCurrentAttribute(i2.getLastAttribute()), this.setSelection(t2);
    }
    insertPlaceholder() {
      return this.placeholderPosition = this.getPosition(), this.insertString(" ");
    }
    selectPlaceholder() {
      if (this.placeholderPosition != null)
        return this.setSelectedRange([this.placeholderPosition, this.placeholderPosition + 1]), this.getSelectedRange();
    }
    forgetPlaceholder() {
      this.placeholderPosition = null;
    }
    hasCurrentAttribute(t2) {
      const e2 = this.currentAttributes[t2];
      return e2 != null && e2 !== false;
    }
    toggleCurrentAttribute(t2) {
      const e2 = !this.currentAttributes[t2];
      return e2 ? this.setCurrentAttribute(t2, e2) : this.removeCurrentAttribute(t2);
    }
    canSetCurrentAttribute(t2) {
      return gt(t2) ? this.canSetCurrentBlockAttribute(t2) : this.canSetCurrentTextAttribute(t2);
    }
    canSetCurrentTextAttribute(t2) {
      const e2 = this.getSelectedDocument();
      if (e2) {
        for (const t3 of Array.from(e2.getAttachments()))
          if (!t3.hasContent())
            return false;
        return true;
      }
    }
    canSetCurrentBlockAttribute(t2) {
      const e2 = this.getBlock();
      if (e2)
        return !e2.isTerminalBlock();
    }
    setCurrentAttribute(t2, e2) {
      return gt(t2) ? this.setBlockAttribute(t2, e2) : (this.setTextAttribute(t2, e2), this.currentAttributes[t2] = e2, this.notifyDelegateOfCurrentAttributesChange());
    }
    setTextAttribute(t2, e2) {
      const i2 = this.getSelectedRange();
      if (!i2)
        return;
      const [n2, r2] = Array.from(i2);
      if (n2 !== r2)
        return this.setDocument(this.document.addAttributeAtRange(t2, e2, i2));
      if (t2 === "href") {
        const t3 = Te.textForStringWithAttributes(e2, { href: e2 });
        return this.insertText(t3);
      }
    }
    setBlockAttribute(t2, e2) {
      const i2 = this.getSelectedRange();
      if (this.canSetCurrentAttribute(t2))
        return this.setDocument(this.document.applyBlockAttributeAtRange(t2, e2, i2)), this.setSelection(i2);
    }
    removeCurrentAttribute(t2) {
      return gt(t2) ? (this.removeBlockAttribute(t2), this.updateCurrentAttributes()) : (this.removeTextAttribute(t2), delete this.currentAttributes[t2], this.notifyDelegateOfCurrentAttributesChange());
    }
    removeTextAttribute(t2) {
      const e2 = this.getSelectedRange();
      if (e2)
        return this.setDocument(this.document.removeAttributeAtRange(t2, e2));
    }
    removeBlockAttribute(t2) {
      const e2 = this.getSelectedRange();
      if (e2)
        return this.setDocument(this.document.removeAttributeAtRange(t2, e2));
    }
    canDecreaseNestingLevel() {
      var t2;
      return ((t2 = this.getBlock()) === null || t2 === void 0 ? void 0 : t2.getNestingLevel()) > 0;
    }
    canIncreaseNestingLevel() {
      var t2;
      const e2 = this.getBlock();
      if (e2) {
        if ((t2 = gt(e2.getLastNestableAttribute())) === null || t2 === void 0 || !t2.listAttribute)
          return e2.getNestingLevel() > 0;
        {
          const t3 = this.getPreviousBlock();
          if (t3)
            return function() {
              let t4 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : [];
              return rt((arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : []).slice(0, t4.length), t4);
            }(t3.getListItemAttributes(), e2.getListItemAttributes());
        }
      }
    }
    decreaseNestingLevel() {
      const t2 = this.getBlock();
      if (t2)
        return this.setDocument(this.document.replaceBlock(t2, t2.decreaseNestingLevel()));
    }
    increaseNestingLevel() {
      const t2 = this.getBlock();
      if (t2)
        return this.setDocument(this.document.replaceBlock(t2, t2.increaseNestingLevel()));
    }
    canDecreaseBlockAttributeLevel() {
      var t2;
      return ((t2 = this.getBlock()) === null || t2 === void 0 ? void 0 : t2.getAttributeLevel()) > 0;
    }
    decreaseBlockAttributeLevel() {
      var t2;
      const e2 = (t2 = this.getBlock()) === null || t2 === void 0 ? void 0 : t2.getLastAttribute();
      if (e2)
        return this.removeCurrentAttribute(e2);
    }
    decreaseListLevel() {
      let [t2] = Array.from(this.getSelectedRange());
      const { index: e2 } = this.document.locationFromPosition(t2);
      let i2 = e2;
      const n2 = this.getBlock().getAttributeLevel();
      let r2 = this.document.getBlockAtIndex(i2 + 1);
      for (; r2 && r2.isListItem() && !(r2.getAttributeLevel() <= n2); )
        i2++, r2 = this.document.getBlockAtIndex(i2 + 1);
      t2 = this.document.positionFromLocation({ index: e2, offset: 0 });
      const o2 = this.document.positionFromLocation({ index: i2, offset: 0 });
      return this.setDocument(this.document.removeLastListAttributeAtRange([t2, o2]));
    }
    updateCurrentAttributes() {
      const t2 = this.getSelectedRange({ ignoreLock: true });
      if (t2) {
        const e2 = this.document.getCommonAttributesAtRange(t2);
        if (Array.from(dt()).forEach((t3) => {
          e2[t3] || this.canSetCurrentAttribute(t3) || (e2[t3] = false);
        }), !kt(e2, this.currentAttributes))
          return this.currentAttributes = e2, this.notifyDelegateOfCurrentAttributesChange();
      }
    }
    getCurrentAttributes() {
      return g.call({}, this.currentAttributes);
    }
    getCurrentTextAttributes() {
      const t2 = {};
      for (const e2 in this.currentAttributes) {
        const i2 = this.currentAttributes[e2];
        i2 !== false && pt(e2) && (t2[e2] = i2);
      }
      return t2;
    }
    freezeSelection() {
      return this.setCurrentAttribute("frozen", true);
    }
    thawSelection() {
      return this.removeCurrentAttribute("frozen");
    }
    hasFrozenSelection() {
      return this.hasCurrentAttribute("frozen");
    }
    setSelection(t2) {
      var e2;
      const i2 = this.document.locationRangeFromRange(t2);
      return (e2 = this.delegate) === null || e2 === void 0 ? void 0 : e2.compositionDidRequestChangingSelectionToLocationRange(i2);
    }
    getSelectedRange() {
      const t2 = this.getLocationRange();
      if (t2)
        return this.document.rangeFromLocationRange(t2);
    }
    setSelectedRange(t2) {
      const e2 = this.document.locationRangeFromRange(t2);
      return this.getSelectionManager().setLocationRange(e2);
    }
    getPosition() {
      const t2 = this.getLocationRange();
      if (t2)
        return this.document.positionFromLocation(t2[0]);
    }
    getLocationRange(t2) {
      return this.targetLocationRange ? this.targetLocationRange : this.getSelectionManager().getLocationRange(t2) || Lt({ index: 0, offset: 0 });
    }
    withTargetLocationRange(t2, e2) {
      let i2;
      this.targetLocationRange = t2;
      try {
        i2 = e2();
      } finally {
        this.targetLocationRange = null;
      }
      return i2;
    }
    withTargetRange(t2, e2) {
      const i2 = this.document.locationRangeFromRange(t2);
      return this.withTargetLocationRange(i2, e2);
    }
    withTargetDOMRange(t2, e2) {
      const i2 = this.createLocationRangeFromDOMRange(t2, { strict: false });
      return this.withTargetLocationRange(i2, e2);
    }
    getExpandedRangeInDirection(t2) {
      let { length: e2 } = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}, [i2, n2] = Array.from(this.getSelectedRange());
      return t2 === "backward" ? e2 ? i2 -= e2 : i2 = this.translateUTF16PositionFromOffset(i2, -1) : e2 ? n2 += e2 : n2 = this.translateUTF16PositionFromOffset(n2, 1), Lt([i2, n2]);
    }
    shouldManageMovingCursorInDirection(t2) {
      if (this.editingAttachment)
        return true;
      const e2 = this.getExpandedRangeInDirection(t2);
      return this.getAttachmentAtRange(e2) != null;
    }
    moveCursorInDirection(t2) {
      let e2, i2;
      if (this.editingAttachment)
        i2 = this.document.getRangeOfAttachment(this.editingAttachment);
      else {
        const n2 = this.getSelectedRange();
        i2 = this.getExpandedRangeInDirection(t2), e2 = !wt(n2, i2);
      }
      if (t2 === "backward" ? this.setSelectedRange(i2[0]) : this.setSelectedRange(i2[1]), e2) {
        const t3 = this.getAttachmentAtRange(i2);
        if (t3)
          return this.editAttachment(t3);
      }
    }
    expandSelectionInDirection(t2) {
      let { length: e2 } = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
      const i2 = this.getExpandedRangeInDirection(t2, { length: e2 });
      return this.setSelectedRange(i2);
    }
    expandSelectionForEditing() {
      if (this.hasCurrentAttribute("href"))
        return this.expandSelectionAroundCommonAttribute("href");
    }
    expandSelectionAroundCommonAttribute(t2) {
      const e2 = this.getPosition(), i2 = this.document.getRangeOfCommonAttributeAtPosition(t2, e2);
      return this.setSelectedRange(i2);
    }
    selectionContainsAttachments() {
      var t2;
      return ((t2 = this.getSelectedAttachments()) === null || t2 === void 0 ? void 0 : t2.length) > 0;
    }
    selectionIsInCursorTarget() {
      return this.editingAttachment || this.positionIsCursorTarget(this.getPosition());
    }
    positionIsCursorTarget(t2) {
      const e2 = this.document.locationFromPosition(t2);
      if (e2)
        return this.locationIsCursorTarget(e2);
    }
    positionIsBlockBreak(t2) {
      var e2;
      return (e2 = this.document.getPieceAtPosition(t2)) === null || e2 === void 0 ? void 0 : e2.isBlockBreak();
    }
    getSelectedDocument() {
      const t2 = this.getSelectedRange();
      if (t2)
        return this.document.getDocumentAtRange(t2);
    }
    getSelectedAttachments() {
      var t2;
      return (t2 = this.getSelectedDocument()) === null || t2 === void 0 ? void 0 : t2.getAttachments();
    }
    getAttachments() {
      return this.attachments.slice(0);
    }
    refreshAttachments() {
      const t2 = this.document.getAttachments(), { added: e2, removed: i2 } = function() {
        let t3 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : [], e3 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : [];
        const i3 = [], n2 = [], r2 = /* @__PURE__ */ new Set();
        t3.forEach((t4) => {
          r2.add(t4);
        });
        const o2 = /* @__PURE__ */ new Set();
        return e3.forEach((t4) => {
          o2.add(t4), r2.has(t4) || i3.push(t4);
        }), t3.forEach((t4) => {
          o2.has(t4) || n2.push(t4);
        }), { added: i3, removed: n2 };
      }(this.attachments, t2);
      return this.attachments = t2, Array.from(i2).forEach((t3) => {
        var e3, i3;
        t3.delegate = null, (e3 = this.delegate) === null || e3 === void 0 || (i3 = e3.compositionDidRemoveAttachment) === null || i3 === void 0 || i3.call(e3, t3);
      }), (() => {
        const t3 = [];
        return Array.from(e2).forEach((e3) => {
          var i3, n2;
          e3.delegate = this, t3.push((i3 = this.delegate) === null || i3 === void 0 || (n2 = i3.compositionDidAddAttachment) === null || n2 === void 0 ? void 0 : n2.call(i3, e3));
        }), t3;
      })();
    }
    attachmentDidChangeAttributes(t2) {
      var e2, i2;
      return this.revision++, (e2 = this.delegate) === null || e2 === void 0 || (i2 = e2.compositionDidEditAttachment) === null || i2 === void 0 ? void 0 : i2.call(e2, t2);
    }
    attachmentDidChangePreviewURL(t2) {
      var e2, i2;
      return this.revision++, (e2 = this.delegate) === null || e2 === void 0 || (i2 = e2.compositionDidChangeAttachmentPreviewURL) === null || i2 === void 0 ? void 0 : i2.call(e2, t2);
    }
    editAttachment(t2, e2) {
      var i2, n2;
      if (t2 !== this.editingAttachment)
        return this.stopEditingAttachment(), this.editingAttachment = t2, (i2 = this.delegate) === null || i2 === void 0 || (n2 = i2.compositionDidStartEditingAttachment) === null || n2 === void 0 ? void 0 : n2.call(i2, this.editingAttachment, e2);
    }
    stopEditingAttachment() {
      var t2, e2;
      this.editingAttachment && ((t2 = this.delegate) === null || t2 === void 0 || (e2 = t2.compositionDidStopEditingAttachment) === null || e2 === void 0 || e2.call(t2, this.editingAttachment), this.editingAttachment = null);
    }
    updateAttributesForAttachment(t2, e2) {
      return this.setDocument(this.document.updateAttributesForAttachment(t2, e2));
    }
    removeAttributeForAttachment(t2, e2) {
      return this.setDocument(this.document.removeAttributeForAttachment(t2, e2));
    }
    breakFormattedBlock(t2) {
      let { document: e2 } = t2;
      const { block: i2 } = t2;
      let n2 = t2.startPosition, r2 = [n2 - 1, n2];
      i2.getBlockBreakPosition() === t2.startLocation.offset ? (i2.breaksOnReturn() && t2.nextCharacter === "\n" ? n2 += 1 : e2 = e2.removeTextAtRange(r2), r2 = [n2, n2]) : t2.nextCharacter === "\n" ? t2.previousCharacter === "\n" ? r2 = [n2 - 1, n2 + 1] : (r2 = [n2, n2 + 1], n2 += 1) : t2.startLocation.offset - 1 != 0 && (n2 += 1);
      const o2 = new qe([i2.removeLastAttribute().copyWithoutText()]);
      return this.setDocument(e2.insertDocumentAtRange(o2, r2)), this.setSelection(n2);
    }
    getPreviousBlock() {
      const t2 = this.getLocationRange();
      if (t2) {
        const { index: e2 } = t2[0];
        if (e2 > 0)
          return this.document.getBlockAtIndex(e2 - 1);
      }
    }
    getBlock() {
      const t2 = this.getLocationRange();
      if (t2)
        return this.document.getBlockAtIndex(t2[0].index);
    }
    getAttachmentAtRange(t2) {
      const e2 = this.document.getDocumentAtRange(t2);
      if (e2.toString() === "".concat("\uFFFC", "\n"))
        return e2.getAttachments()[0];
    }
    notifyDelegateOfCurrentAttributesChange() {
      var t2, e2;
      return (t2 = this.delegate) === null || t2 === void 0 || (e2 = t2.compositionDidChangeCurrentAttributes) === null || e2 === void 0 ? void 0 : e2.call(t2, this.currentAttributes);
    }
    notifyDelegateOfInsertionAtRange(t2) {
      var e2, i2;
      return (e2 = this.delegate) === null || e2 === void 0 || (i2 = e2.compositionDidPerformInsertionAtRange) === null || i2 === void 0 ? void 0 : i2.call(e2, t2);
    }
    translateUTF16PositionFromOffset(t2, e2) {
      const i2 = this.document.toUTF16String(), n2 = i2.offsetFromUCS2Offset(t2);
      return i2.offsetToUCS2Offset(n2 + e2);
    }
  };
  gi.proxyMethod("getSelectionManager().getPointRange"), gi.proxyMethod("getSelectionManager().setLocationRangeFromPointRange"), gi.proxyMethod("getSelectionManager().createLocationRangeFromDOMRange"), gi.proxyMethod("getSelectionManager().locationIsCursorTarget"), gi.proxyMethod("getSelectionManager().selectionIsExpanded"), gi.proxyMethod("delegate?.getSelectionManager");
  var mi = class extends z {
    constructor(t2) {
      super(...arguments), this.composition = t2, this.undoEntries = [], this.redoEntries = [];
    }
    recordUndoEntry(t2) {
      let { context: e2, consolidatable: i2 } = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
      const n2 = this.undoEntries.slice(-1)[0];
      if (!i2 || !pi(n2, t2, e2)) {
        const i3 = this.createEntry({ description: t2, context: e2 });
        this.undoEntries.push(i3), this.redoEntries = [];
      }
    }
    undo() {
      const t2 = this.undoEntries.pop();
      if (t2) {
        const e2 = this.createEntry(t2);
        return this.redoEntries.push(e2), this.composition.loadSnapshot(t2.snapshot);
      }
    }
    redo() {
      const t2 = this.redoEntries.pop();
      if (t2) {
        const e2 = this.createEntry(t2);
        return this.undoEntries.push(e2), this.composition.loadSnapshot(t2.snapshot);
      }
    }
    canUndo() {
      return this.undoEntries.length > 0;
    }
    canRedo() {
      return this.redoEntries.length > 0;
    }
    createEntry() {
      let { description: t2, context: e2 } = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
      return { description: t2 == null ? void 0 : t2.toString(), context: JSON.stringify(e2), snapshot: this.composition.getSnapshot() };
    }
  };
  var pi = (t2, e2, i2) => (t2 == null ? void 0 : t2.description) === (e2 == null ? void 0 : e2.toString()) && (t2 == null ? void 0 : t2.context) === JSON.stringify(i2);
  var fi = "attachmentGallery";
  var bi = class {
    constructor(t2) {
      this.document = t2.document, this.selectedRange = t2.selectedRange;
    }
    perform() {
      return this.removeBlockAttribute(), this.applyBlockAttribute();
    }
    getSnapshot() {
      return { document: this.document, selectedRange: this.selectedRange };
    }
    removeBlockAttribute() {
      return this.findRangesOfBlocks().map((t2) => this.document = this.document.removeAttributeAtRange(fi, t2));
    }
    applyBlockAttribute() {
      let t2 = 0;
      this.findRangesOfPieces().forEach((e2) => {
        e2[1] - e2[0] > 1 && (e2[0] += t2, e2[1] += t2, this.document.getCharacterAtPosition(e2[1]) !== "\n" && (this.document = this.document.insertBlockBreakAtRange(e2[1]), e2[1] < this.selectedRange[1] && this.moveSelectedRangeForward(), e2[1]++, t2++), e2[0] !== 0 && this.document.getCharacterAtPosition(e2[0] - 1) !== "\n" && (this.document = this.document.insertBlockBreakAtRange(e2[0]), e2[0] < this.selectedRange[0] && this.moveSelectedRangeForward(), e2[0]++, t2++), this.document = this.document.applyBlockAttributeAtRange(fi, true, e2));
      });
    }
    findRangesOfBlocks() {
      return this.document.findRangesForBlockAttribute(fi);
    }
    findRangesOfPieces() {
      return this.document.findRangesForTextAttribute("presentation", { withValue: "gallery" });
    }
    moveSelectedRangeForward() {
      this.selectedRange[0] += 1, this.selectedRange[1] += 1;
    }
  };
  var vi = function(t2) {
    const e2 = new bi(t2);
    return e2.perform(), e2.getSnapshot();
  };
  var Ai = [vi];
  var xi = class {
    constructor(t2, e2, i2) {
      this.insertFiles = this.insertFiles.bind(this), this.composition = t2, this.selectionManager = e2, this.element = i2, this.undoManager = new mi(this.composition), this.filters = Ai.slice(0);
    }
    loadDocument(t2) {
      return this.loadSnapshot({ document: t2, selectedRange: [0, 0] });
    }
    loadHTML() {
      let t2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : "";
      const e2 = Xe.parse(t2, { referenceElement: this.element }).getDocument();
      return this.loadDocument(e2);
    }
    loadJSON(t2) {
      let { document: e2, selectedRange: i2 } = t2;
      return e2 = qe.fromJSON(e2), this.loadSnapshot({ document: e2, selectedRange: i2 });
    }
    loadSnapshot(t2) {
      return this.undoManager = new mi(this.composition), this.composition.loadSnapshot(t2);
    }
    getDocument() {
      return this.composition.document;
    }
    getSelectedDocument() {
      return this.composition.getSelectedDocument();
    }
    getSnapshot() {
      return this.composition.getSnapshot();
    }
    toJSON() {
      return this.getSnapshot();
    }
    deleteInDirection(t2) {
      return this.composition.deleteInDirection(t2);
    }
    insertAttachment(t2) {
      return this.composition.insertAttachment(t2);
    }
    insertAttachments(t2) {
      return this.composition.insertAttachments(t2);
    }
    insertDocument(t2) {
      return this.composition.insertDocument(t2);
    }
    insertFile(t2) {
      return this.composition.insertFile(t2);
    }
    insertFiles(t2) {
      return this.composition.insertFiles(t2);
    }
    insertHTML(t2) {
      return this.composition.insertHTML(t2);
    }
    insertString(t2) {
      return this.composition.insertString(t2);
    }
    insertText(t2) {
      return this.composition.insertText(t2);
    }
    insertLineBreak() {
      return this.composition.insertLineBreak();
    }
    getSelectedRange() {
      return this.composition.getSelectedRange();
    }
    getPosition() {
      return this.composition.getPosition();
    }
    getClientRectAtPosition(t2) {
      const e2 = this.getDocument().locationRangeFromRange([t2, t2 + 1]);
      return this.selectionManager.getClientRectAtLocationRange(e2);
    }
    expandSelectionInDirection(t2) {
      return this.composition.expandSelectionInDirection(t2);
    }
    moveCursorInDirection(t2) {
      return this.composition.moveCursorInDirection(t2);
    }
    setSelectedRange(t2) {
      return this.composition.setSelectedRange(t2);
    }
    activateAttribute(t2) {
      let e2 = !(arguments.length > 1 && arguments[1] !== void 0) || arguments[1];
      return this.composition.setCurrentAttribute(t2, e2);
    }
    attributeIsActive(t2) {
      return this.composition.hasCurrentAttribute(t2);
    }
    canActivateAttribute(t2) {
      return this.composition.canSetCurrentAttribute(t2);
    }
    deactivateAttribute(t2) {
      return this.composition.removeCurrentAttribute(t2);
    }
    canDecreaseNestingLevel() {
      return this.composition.canDecreaseNestingLevel();
    }
    canIncreaseNestingLevel() {
      return this.composition.canIncreaseNestingLevel();
    }
    decreaseNestingLevel() {
      if (this.canDecreaseNestingLevel())
        return this.composition.decreaseNestingLevel();
    }
    increaseNestingLevel() {
      if (this.canIncreaseNestingLevel())
        return this.composition.increaseNestingLevel();
    }
    canRedo() {
      return this.undoManager.canRedo();
    }
    canUndo() {
      return this.undoManager.canUndo();
    }
    recordUndoEntry(t2) {
      let { context: e2, consolidatable: i2 } = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
      return this.undoManager.recordUndoEntry(t2, { context: e2, consolidatable: i2 });
    }
    redo() {
      if (this.canRedo())
        return this.undoManager.redo();
    }
    undo() {
      if (this.canUndo())
        return this.undoManager.undo();
    }
  };
  var yi = class {
    constructor(t2) {
      this.element = t2;
    }
    findLocationFromContainerAndOffset(t2, e2) {
      let { strict: i2 } = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : { strict: true }, n2 = 0, r2 = false;
      const o2 = { index: 0, offset: 0 }, s2 = this.findAttachmentElementParentForNode(t2);
      s2 && (t2 = s2.parentNode, e2 = C(s2));
      const a2 = S(this.element, { usingFilter: Ei });
      for (; a2.nextNode(); ) {
        const s3 = a2.currentNode;
        if (s3 === t2 && O(t2)) {
          I(s3) || (o2.offset += e2);
          break;
        }
        if (s3.parentNode === t2) {
          if (n2++ === e2)
            break;
        } else if (!y(t2, s3) && n2 > 0)
          break;
        T(s3, { strict: i2 }) ? (r2 && o2.index++, o2.offset = 0, r2 = true) : o2.offset += Ci(s3);
      }
      return o2;
    }
    findContainerAndOffsetFromLocation(t2) {
      let e2, i2;
      if (t2.index === 0 && t2.offset === 0) {
        for (e2 = this.element, i2 = 0; e2.firstChild; )
          if (e2 = e2.firstChild, w(e2)) {
            i2 = 1;
            break;
          }
        return [e2, i2];
      }
      let [n2, r2] = this.findNodeAndOffsetFromLocation(t2);
      if (n2) {
        if (O(n2))
          Ci(n2) === 0 ? (e2 = n2.parentNode.parentNode, i2 = C(n2.parentNode), I(n2, { name: "right" }) && i2++) : (e2 = n2, i2 = t2.offset - r2);
        else {
          if (e2 = n2.parentNode, !T(n2.previousSibling) && !w(e2))
            for (; n2 === e2.lastChild && (n2 = e2, e2 = e2.parentNode, !w(e2)); )
              ;
          i2 = C(n2), t2.offset !== 0 && i2++;
        }
        return [e2, i2];
      }
    }
    findNodeAndOffsetFromLocation(t2) {
      let e2, i2, n2 = 0;
      for (const r2 of this.getSignificantNodesForIndex(t2.index)) {
        const o2 = Ci(r2);
        if (t2.offset <= n2 + o2)
          if (O(r2)) {
            if (e2 = r2, i2 = n2, t2.offset === i2 && I(e2))
              break;
          } else
            e2 || (e2 = r2, i2 = n2);
        if (n2 += o2, n2 > t2.offset)
          break;
      }
      return [e2, i2];
    }
    findAttachmentElementParentForNode(t2) {
      for (; t2 && t2 !== this.element; ) {
        if (P(t2))
          return t2;
        t2 = t2.parentNode;
      }
    }
    getSignificantNodesForIndex(t2) {
      const e2 = [], i2 = S(this.element, { usingFilter: Ri });
      let n2 = false;
      for (; i2.nextNode(); ) {
        const o2 = i2.currentNode;
        var r2;
        if (B(o2)) {
          if (r2 != null ? r2++ : r2 = 0, r2 === t2)
            n2 = true;
          else if (n2)
            break;
        } else
          n2 && e2.push(o2);
      }
      return e2;
    }
  };
  var Ci = function(t2) {
    if (t2.nodeType === Node.TEXT_NODE) {
      if (I(t2))
        return 0;
      return t2.textContent.length;
    }
    return E(t2) === "br" || P(t2) ? 1 : 0;
  };
  var Ri = function(t2) {
    return Si(t2) === NodeFilter.FILTER_ACCEPT ? Ei(t2) : NodeFilter.FILTER_REJECT;
  };
  var Si = function(t2) {
    return N(t2) ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT;
  };
  var Ei = function(t2) {
    return P(t2.parentNode) ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT;
  };
  var ki = class {
    createDOMRangeFromPoint(t2) {
      let e2, { x: i2, y: n2 } = t2;
      if (document.caretPositionFromPoint) {
        const { offsetNode: t3, offset: r2 } = document.caretPositionFromPoint(i2, n2);
        return e2 = document.createRange(), e2.setStart(t3, r2), e2;
      }
      if (document.caretRangeFromPoint)
        return document.caretRangeFromPoint(i2, n2);
      if (document.body.createTextRange) {
        const t3 = Nt();
        try {
          const t4 = document.body.createTextRange();
          t4.moveToPoint(i2, n2), t4.select();
        } catch (t4) {
        }
        return e2 = Nt(), Ot(t3), e2;
      }
    }
    getClientRectsForDOMRange(t2) {
      const e2 = Array.from(t2.getClientRects());
      return [e2[0], e2[e2.length - 1]];
    }
  };
  var Li = class extends z {
    constructor(t2) {
      super(...arguments), this.didMouseDown = this.didMouseDown.bind(this), this.selectionDidChange = this.selectionDidChange.bind(this), this.element = t2, this.locationMapper = new yi(this.element), this.pointMapper = new ki(), this.lockCount = 0, f("mousedown", { onElement: this.element, withCallback: this.didMouseDown });
    }
    getLocationRange() {
      let t2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
      return t2.strict === false ? this.createLocationRangeFromDOMRange(Nt()) : t2.ignoreLock ? this.currentLocationRange : this.lockedLocationRange ? this.lockedLocationRange : this.currentLocationRange;
    }
    setLocationRange(t2) {
      if (this.lockedLocationRange)
        return;
      t2 = Lt(t2);
      const e2 = this.createDOMRangeFromLocationRange(t2);
      e2 && (Ot(e2), this.updateCurrentLocationRange(t2));
    }
    setLocationRangeFromPointRange(t2) {
      t2 = Lt(t2);
      const e2 = this.getLocationAtPoint(t2[0]), i2 = this.getLocationAtPoint(t2[1]);
      this.setLocationRange([e2, i2]);
    }
    getClientRectAtLocationRange(t2) {
      const e2 = this.createDOMRangeFromLocationRange(t2);
      if (e2)
        return this.getClientRectsForDOMRange(e2)[1];
    }
    locationIsCursorTarget(t2) {
      const e2 = Array.from(this.findNodeAndOffsetFromLocation(t2))[0];
      return I(e2);
    }
    lock() {
      this.lockCount++ == 0 && (this.updateCurrentLocationRange(), this.lockedLocationRange = this.getLocationRange());
    }
    unlock() {
      if (--this.lockCount == 0) {
        const { lockedLocationRange: t2 } = this;
        if (this.lockedLocationRange = null, t2 != null)
          return this.setLocationRange(t2);
      }
    }
    clearSelection() {
      var t2;
      return (t2 = Pt()) === null || t2 === void 0 ? void 0 : t2.removeAllRanges();
    }
    selectionIsCollapsed() {
      var t2;
      return ((t2 = Nt()) === null || t2 === void 0 ? void 0 : t2.collapsed) === true;
    }
    selectionIsExpanded() {
      return !this.selectionIsCollapsed();
    }
    createLocationRangeFromDOMRange(t2, e2) {
      if (t2 == null || !this.domRangeWithinElement(t2))
        return;
      const i2 = this.findLocationFromContainerAndOffset(t2.startContainer, t2.startOffset, e2);
      if (!i2)
        return;
      const n2 = t2.collapsed ? void 0 : this.findLocationFromContainerAndOffset(t2.endContainer, t2.endOffset, e2);
      return Lt([i2, n2]);
    }
    didMouseDown() {
      return this.pauseTemporarily();
    }
    pauseTemporarily() {
      let t2;
      this.paused = true;
      const e2 = () => {
        if (this.paused = false, clearTimeout(i2), Array.from(t2).forEach((t3) => {
          t3.destroy();
        }), y(document, this.element))
          return this.selectionDidChange();
      }, i2 = setTimeout(e2, 200);
      t2 = ["mousemove", "keydown"].map((t3) => f(t3, { onElement: document, withCallback: e2 }));
    }
    selectionDidChange() {
      if (!this.paused && !x(this.element))
        return this.updateCurrentLocationRange();
    }
    updateCurrentLocationRange(t2) {
      var e2, i2;
      if ((t2 != null ? t2 : t2 = this.createLocationRangeFromDOMRange(Nt())) && !wt(t2, this.currentLocationRange))
        return this.currentLocationRange = t2, (e2 = this.delegate) === null || e2 === void 0 || (i2 = e2.locationRangeDidChange) === null || i2 === void 0 ? void 0 : i2.call(e2, this.currentLocationRange.slice(0));
    }
    createDOMRangeFromLocationRange(t2) {
      const e2 = this.findContainerAndOffsetFromLocation(t2[0]), i2 = Dt(t2) ? e2 : this.findContainerAndOffsetFromLocation(t2[1]) || e2;
      if (e2 != null && i2 != null) {
        const t3 = document.createRange();
        return t3.setStart(...Array.from(e2 || [])), t3.setEnd(...Array.from(i2 || [])), t3;
      }
    }
    getLocationAtPoint(t2) {
      const e2 = this.createDOMRangeFromPoint(t2);
      var i2;
      if (e2)
        return (i2 = this.createLocationRangeFromDOMRange(e2)) === null || i2 === void 0 ? void 0 : i2[0];
    }
    domRangeWithinElement(t2) {
      return t2.collapsed ? y(this.element, t2.startContainer) : y(this.element, t2.startContainer) && y(this.element, t2.endContainer);
    }
  };
  Li.proxyMethod("locationMapper.findLocationFromContainerAndOffset"), Li.proxyMethod("locationMapper.findContainerAndOffsetFromLocation"), Li.proxyMethod("locationMapper.findNodeAndOffsetFromLocation"), Li.proxyMethod("pointMapper.createDOMRangeFromPoint"), Li.proxyMethod("pointMapper.getClientRectsForDOMRange");
  var Di = Object.freeze({ __proto__: null, Attachment: Re, AttachmentManager: ui, AttachmentPiece: Se, Block: Be, Composition: gi, Document: qe, Editor: xi, HTMLParser: Xe, HTMLSanitizer: Je, LineBreakInsertion: di, LocationMapper: yi, ManagedAttachment: hi, Piece: ye, PointMapper: ki, SelectionManager: Li, SplittableList: ke, StringPiece: Ee, Text: Te, UndoManager: mi });
  var wi = Object.freeze({ __proto__: null, ObjectView: ee, AttachmentView: re, BlockView: de, DocumentView: ge, PieceView: le, PreviewableAttachmentView: ae, TextView: ce });
  var { lang: Ti, css: Bi, keyNames: Fi } = V;
  var Ii = function(t2) {
    return function() {
      const e2 = t2.apply(this, arguments);
      e2.do(), this.undos || (this.undos = []), this.undos.push(e2.undo);
    };
  };
  var Pi = class extends z {
    constructor(t2, e2, i2) {
      let n2 = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {};
      super(...arguments), Ae(this, "makeElementMutable", Ii(() => ({ do: () => {
        this.element.dataset.trixMutable = true;
      }, undo: () => delete this.element.dataset.trixMutable }))), Ae(this, "addToolbar", Ii(() => {
        const t3 = k({ tagName: "div", className: Bi.attachmentToolbar, data: { trixMutable: true }, childNodes: k({ tagName: "div", className: "trix-button-row", childNodes: k({ tagName: "span", className: "trix-button-group trix-button-group--actions", childNodes: k({ tagName: "button", className: "trix-button trix-button--remove", textContent: Ti.remove, attributes: { title: Ti.remove }, data: { trixAction: "remove" } }) }) }) });
        return this.attachment.isPreviewable() && t3.appendChild(k({ tagName: "div", className: Bi.attachmentMetadataContainer, childNodes: k({ tagName: "span", className: Bi.attachmentMetadata, childNodes: [k({ tagName: "span", className: Bi.attachmentName, textContent: this.attachment.getFilename(), attributes: { title: this.attachment.getFilename() } }), k({ tagName: "span", className: Bi.attachmentSize, textContent: this.attachment.getFormattedFilesize() })] }) })), f("click", { onElement: t3, withCallback: this.didClickToolbar }), f("click", { onElement: t3, matchingSelector: "[data-trix-action]", withCallback: this.didClickActionButton }), b("trix-attachment-before-toolbar", { onElement: this.element, attributes: { toolbar: t3, attachment: this.attachment } }), { do: () => this.element.appendChild(t3), undo: () => R(t3) };
      })), Ae(this, "installCaptionEditor", Ii(() => {
        const t3 = k({ tagName: "textarea", className: Bi.attachmentCaptionEditor, attributes: { placeholder: Ti.captionPlaceholder }, data: { trixMutable: true } });
        t3.value = this.attachmentPiece.getCaption();
        const e3 = t3.cloneNode();
        e3.classList.add("trix-autoresize-clone"), e3.tabIndex = -1;
        const i3 = function() {
          e3.value = t3.value, t3.style.height = e3.scrollHeight + "px";
        };
        f("input", { onElement: t3, withCallback: i3 }), f("input", { onElement: t3, withCallback: this.didInputCaption }), f("keydown", { onElement: t3, withCallback: this.didKeyDownCaption }), f("change", { onElement: t3, withCallback: this.didChangeCaption }), f("blur", { onElement: t3, withCallback: this.didBlurCaption });
        const n3 = this.element.querySelector("figcaption"), r2 = n3.cloneNode();
        return { do: () => {
          if (n3.style.display = "none", r2.appendChild(t3), r2.appendChild(e3), r2.classList.add("".concat(Bi.attachmentCaption, "--editing")), n3.parentElement.insertBefore(r2, n3), i3(), this.options.editCaption)
            return St(() => t3.focus());
        }, undo() {
          R(r2), n3.style.display = null;
        } };
      })), this.didClickToolbar = this.didClickToolbar.bind(this), this.didClickActionButton = this.didClickActionButton.bind(this), this.didKeyDownCaption = this.didKeyDownCaption.bind(this), this.didInputCaption = this.didInputCaption.bind(this), this.didChangeCaption = this.didChangeCaption.bind(this), this.didBlurCaption = this.didBlurCaption.bind(this), this.attachmentPiece = t2, this.element = e2, this.container = i2, this.options = n2, this.attachment = this.attachmentPiece.attachment, E(this.element) === "a" && (this.element = this.element.firstChild), this.install();
    }
    install() {
      this.makeElementMutable(), this.addToolbar(), this.attachment.isPreviewable() && this.installCaptionEditor();
    }
    uninstall() {
      var t2;
      let e2 = this.undos.pop();
      for (this.savePendingCaption(); e2; )
        e2(), e2 = this.undos.pop();
      (t2 = this.delegate) === null || t2 === void 0 || t2.didUninstallAttachmentEditor(this);
    }
    savePendingCaption() {
      if (this.pendingCaption != null) {
        const r2 = this.pendingCaption;
        var t2, e2, i2, n2;
        if (this.pendingCaption = null, r2)
          (t2 = this.delegate) === null || t2 === void 0 || (e2 = t2.attachmentEditorDidRequestUpdatingAttributesForAttachment) === null || e2 === void 0 || e2.call(t2, { caption: r2 }, this.attachment);
        else
          (i2 = this.delegate) === null || i2 === void 0 || (n2 = i2.attachmentEditorDidRequestRemovingAttributeForAttachment) === null || n2 === void 0 || n2.call(i2, "caption", this.attachment);
      }
    }
    didClickToolbar(t2) {
      return t2.preventDefault(), t2.stopPropagation();
    }
    didClickActionButton(t2) {
      var e2;
      if (t2.target.getAttribute("data-trix-action") === "remove")
        return (e2 = this.delegate) === null || e2 === void 0 ? void 0 : e2.attachmentEditorDidRequestRemovalOfAttachment(this.attachment);
    }
    didKeyDownCaption(t2) {
      var e2, i2;
      if (Fi[t2.keyCode] === "return")
        return t2.preventDefault(), this.savePendingCaption(), (e2 = this.delegate) === null || e2 === void 0 || (i2 = e2.attachmentEditorDidRequestDeselectingAttachment) === null || i2 === void 0 ? void 0 : i2.call(e2, this.attachment);
    }
    didInputCaption(t2) {
      this.pendingCaption = t2.target.value.replace(/\s/g, " ").trim();
    }
    didChangeCaption(t2) {
      return this.savePendingCaption();
    }
    didBlurCaption(t2) {
      return this.savePendingCaption();
    }
  };
  var Ni = class extends z {
    constructor(t2, i2) {
      super(...arguments), this.didFocus = this.didFocus.bind(this), this.didBlur = this.didBlur.bind(this), this.didClickAttachment = this.didClickAttachment.bind(this), this.element = t2, this.composition = i2, this.documentView = new ge(this.composition.document, { element: this.element }), f("focus", { onElement: this.element, withCallback: this.didFocus }), f("blur", { onElement: this.element, withCallback: this.didBlur }), f("click", { onElement: this.element, matchingSelector: "a[contenteditable=false]", preventDefault: true }), f("mousedown", { onElement: this.element, matchingSelector: e, withCallback: this.didClickAttachment }), f("click", { onElement: this.element, matchingSelector: "a".concat(e), preventDefault: true });
    }
    didFocus(t2) {
      var e2;
      const i2 = () => {
        var t3, e3;
        if (!this.focused)
          return this.focused = true, (t3 = this.delegate) === null || t3 === void 0 || (e3 = t3.compositionControllerDidFocus) === null || e3 === void 0 ? void 0 : e3.call(t3);
      };
      return ((e2 = this.blurPromise) === null || e2 === void 0 ? void 0 : e2.then(i2)) || i2();
    }
    didBlur(t2) {
      this.blurPromise = new Promise((t3) => St(() => {
        var e2, i2;
        x(this.element) || (this.focused = null, (e2 = this.delegate) === null || e2 === void 0 || (i2 = e2.compositionControllerDidBlur) === null || i2 === void 0 || i2.call(e2));
        return this.blurPromise = null, t3();
      }));
    }
    didClickAttachment(t2, e2) {
      var i2, n2;
      const r2 = this.findAttachmentForElement(e2), o2 = !!A(t2.target, { matchingSelector: "figcaption" });
      return (i2 = this.delegate) === null || i2 === void 0 || (n2 = i2.compositionControllerDidSelectAttachment) === null || n2 === void 0 ? void 0 : n2.call(i2, r2, { editCaption: o2 });
    }
    getSerializableElement() {
      return this.isEditingAttachment() ? this.documentView.shadowElement : this.element;
    }
    render() {
      var t2, e2, i2, n2, r2, o2;
      (this.revision !== this.composition.revision && (this.documentView.setDocument(this.composition.document), this.documentView.render(), this.revision = this.composition.revision), this.canSyncDocumentView() && !this.documentView.isSynced()) && ((i2 = this.delegate) === null || i2 === void 0 || (n2 = i2.compositionControllerWillSyncDocumentView) === null || n2 === void 0 || n2.call(i2), this.documentView.sync(), (r2 = this.delegate) === null || r2 === void 0 || (o2 = r2.compositionControllerDidSyncDocumentView) === null || o2 === void 0 || o2.call(r2));
      return (t2 = this.delegate) === null || t2 === void 0 || (e2 = t2.compositionControllerDidRender) === null || e2 === void 0 ? void 0 : e2.call(t2);
    }
    rerenderViewForObject(t2) {
      return this.invalidateViewForObject(t2), this.render();
    }
    invalidateViewForObject(t2) {
      return this.documentView.invalidateViewForObject(t2);
    }
    isViewCachingEnabled() {
      return this.documentView.isViewCachingEnabled();
    }
    enableViewCaching() {
      return this.documentView.enableViewCaching();
    }
    disableViewCaching() {
      return this.documentView.disableViewCaching();
    }
    refreshViewCache() {
      return this.documentView.garbageCollectCachedViews();
    }
    isEditingAttachment() {
      return !!this.attachmentEditor;
    }
    installAttachmentEditorForAttachment(t2, e2) {
      var i2;
      if (((i2 = this.attachmentEditor) === null || i2 === void 0 ? void 0 : i2.attachment) === t2)
        return;
      const n2 = this.documentView.findElementForObject(t2);
      if (!n2)
        return;
      this.uninstallAttachmentEditor();
      const r2 = this.composition.document.getAttachmentPieceForAttachment(t2);
      this.attachmentEditor = new Pi(r2, n2, this.element, e2), this.attachmentEditor.delegate = this;
    }
    uninstallAttachmentEditor() {
      var t2;
      return (t2 = this.attachmentEditor) === null || t2 === void 0 ? void 0 : t2.uninstall();
    }
    didUninstallAttachmentEditor() {
      return this.attachmentEditor = null, this.render();
    }
    attachmentEditorDidRequestUpdatingAttributesForAttachment(t2, e2) {
      var i2, n2;
      return (i2 = this.delegate) === null || i2 === void 0 || (n2 = i2.compositionControllerWillUpdateAttachment) === null || n2 === void 0 || n2.call(i2, e2), this.composition.updateAttributesForAttachment(t2, e2);
    }
    attachmentEditorDidRequestRemovingAttributeForAttachment(t2, e2) {
      var i2, n2;
      return (i2 = this.delegate) === null || i2 === void 0 || (n2 = i2.compositionControllerWillUpdateAttachment) === null || n2 === void 0 || n2.call(i2, e2), this.composition.removeAttributeForAttachment(t2, e2);
    }
    attachmentEditorDidRequestRemovalOfAttachment(t2) {
      var e2, i2;
      return (e2 = this.delegate) === null || e2 === void 0 || (i2 = e2.compositionControllerDidRequestRemovalOfAttachment) === null || i2 === void 0 ? void 0 : i2.call(e2, t2);
    }
    attachmentEditorDidRequestDeselectingAttachment(t2) {
      var e2, i2;
      return (e2 = this.delegate) === null || e2 === void 0 || (i2 = e2.compositionControllerDidRequestDeselectingAttachment) === null || i2 === void 0 ? void 0 : i2.call(e2, t2);
    }
    canSyncDocumentView() {
      return !this.isEditingAttachment();
    }
    findAttachmentForElement(t2) {
      return this.composition.document.getAttachmentById(parseInt(t2.dataset.trixId, 10));
    }
  };
  var Oi = class extends z {
  };
  var Mi = "data-trix-mutable";
  var ji = "[".concat(Mi, "]");
  var Wi = { attributes: true, childList: true, characterData: true, characterDataOldValue: true, subtree: true };
  var Ui = class extends z {
    constructor(t2) {
      super(t2), this.didMutate = this.didMutate.bind(this), this.element = t2, this.observer = new window.MutationObserver(this.didMutate), this.start();
    }
    start() {
      return this.reset(), this.observer.observe(this.element, Wi);
    }
    stop() {
      return this.observer.disconnect();
    }
    didMutate(t2) {
      var e2, i2;
      if (this.mutations.push(...Array.from(this.findSignificantMutations(t2) || [])), this.mutations.length)
        return (e2 = this.delegate) === null || e2 === void 0 || (i2 = e2.elementDidMutate) === null || i2 === void 0 || i2.call(e2, this.getMutationSummary()), this.reset();
    }
    reset() {
      this.mutations = [];
    }
    findSignificantMutations(t2) {
      return t2.filter((t3) => this.mutationIsSignificant(t3));
    }
    mutationIsSignificant(t2) {
      if (this.nodeIsMutable(t2.target))
        return false;
      for (const e2 of Array.from(this.nodesModifiedByMutation(t2)))
        if (this.nodeIsSignificant(e2))
          return true;
      return false;
    }
    nodeIsSignificant(t2) {
      return t2 !== this.element && !this.nodeIsMutable(t2) && !N(t2);
    }
    nodeIsMutable(t2) {
      return A(t2, { matchingSelector: ji });
    }
    nodesModifiedByMutation(t2) {
      const e2 = [];
      switch (t2.type) {
        case "attributes":
          t2.attributeName !== Mi && e2.push(t2.target);
          break;
        case "characterData":
          e2.push(t2.target.parentNode), e2.push(t2.target);
          break;
        case "childList":
          e2.push(...Array.from(t2.addedNodes || [])), e2.push(...Array.from(t2.removedNodes || []));
      }
      return e2;
    }
    getMutationSummary() {
      return this.getTextMutationSummary();
    }
    getTextMutationSummary() {
      const { additions: t2, deletions: e2 } = this.getTextChangesFromCharacterData(), i2 = this.getTextChangesFromChildList();
      Array.from(i2.additions).forEach((e3) => {
        Array.from(t2).includes(e3) || t2.push(e3);
      }), e2.push(...Array.from(i2.deletions || []));
      const n2 = {}, r2 = t2.join("");
      r2 && (n2.textAdded = r2);
      const o2 = e2.join("");
      return o2 && (n2.textDeleted = o2), n2;
    }
    getMutationsByType(t2) {
      return Array.from(this.mutations).filter((e2) => e2.type === t2);
    }
    getTextChangesFromChildList() {
      let t2, e2;
      const i2 = [], n2 = [];
      Array.from(this.getMutationsByType("childList")).forEach((t3) => {
        i2.push(...Array.from(t3.addedNodes || [])), n2.push(...Array.from(t3.removedNodes || []));
      });
      i2.length === 0 && n2.length === 1 && B(n2[0]) ? (t2 = [], e2 = ["\n"]) : (t2 = qi(i2), e2 = qi(n2));
      return { additions: t2.filter((t3, i3) => t3 !== e2[i3]).map(Wt), deletions: e2.filter((e3, i3) => e3 !== t2[i3]).map(Wt) };
    }
    getTextChangesFromCharacterData() {
      let t2, e2;
      const i2 = this.getMutationsByType("characterData");
      if (i2.length) {
        const n2 = i2[0], r2 = i2[i2.length - 1], o2 = function(t3, e3) {
          let i3, n3;
          return t3 = X.box(t3), (e3 = X.box(e3)).length < t3.length ? [n3, i3] = Vt(t3, e3) : [i3, n3] = Vt(e3, t3), { added: i3, removed: n3 };
        }(Wt(n2.oldValue), Wt(r2.target.data));
        t2 = o2.added, e2 = o2.removed;
      }
      return { additions: t2 ? [t2] : [], deletions: e2 ? [e2] : [] };
    }
  };
  var qi = function() {
    let t2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : [];
    const e2 = [];
    for (const i2 of Array.from(t2))
      switch (i2.nodeType) {
        case Node.TEXT_NODE:
          e2.push(i2.data);
          break;
        case Node.ELEMENT_NODE:
          E(i2) === "br" ? e2.push("\n") : e2.push(...Array.from(qi(i2.childNodes) || []));
      }
    return e2;
  };
  var Vi = class extends te {
    constructor(t2) {
      super(...arguments), this.file = t2;
    }
    perform(t2) {
      const e2 = new FileReader();
      return e2.onerror = () => t2(false), e2.onload = () => {
        e2.onerror = null;
        try {
          e2.abort();
        } catch (t3) {
        }
        return t2(true, this.file);
      }, e2.readAsArrayBuffer(this.file);
    }
  };
  var zi = class {
    constructor(t2) {
      this.element = t2;
    }
    shouldIgnore(t2) {
      return !!a.samsungAndroid && (this.previousEvent = this.event, this.event = t2, this.checkSamsungKeyboardBuggyModeStart(), this.checkSamsungKeyboardBuggyModeEnd(), this.buggyMode);
    }
    checkSamsungKeyboardBuggyModeStart() {
      this.insertingLongTextAfterUnidentifiedChar() && _i(this.element.innerText, this.event.data) && (this.buggyMode = true, this.event.preventDefault());
    }
    checkSamsungKeyboardBuggyModeEnd() {
      this.buggyMode && this.event.inputType !== "insertText" && (this.buggyMode = false);
    }
    insertingLongTextAfterUnidentifiedChar() {
      var t2;
      return this.isBeforeInputInsertText() && this.previousEventWasUnidentifiedKeydown() && ((t2 = this.event.data) === null || t2 === void 0 ? void 0 : t2.length) > 50;
    }
    isBeforeInputInsertText() {
      return this.event.type === "beforeinput" && this.event.inputType === "insertText";
    }
    previousEventWasUnidentifiedKeydown() {
      var t2, e2;
      return ((t2 = this.previousEvent) === null || t2 === void 0 ? void 0 : t2.type) === "keydown" && ((e2 = this.previousEvent) === null || e2 === void 0 ? void 0 : e2.key) === "Unidentified";
    }
  };
  var _i = (t2, e2) => Ji(t2) === Ji(e2);
  var Hi = new RegExp("(".concat("\uFFFC", "|").concat(u, "|").concat(d, "|\\s)+"), "g");
  var Ji = (t2) => t2.replace(Hi, " ").trim();
  var Ki = class extends z {
    constructor(t2) {
      super(...arguments), this.element = t2, this.mutationObserver = new Ui(this.element), this.mutationObserver.delegate = this, this.flakyKeyboardDetector = new zi(this.element);
      for (const t3 in this.constructor.events)
        f(t3, { onElement: this.element, withCallback: this.handlerFor(t3) });
    }
    elementDidMutate(t2) {
    }
    editorWillSyncDocumentView() {
      return this.mutationObserver.stop();
    }
    editorDidSyncDocumentView() {
      return this.mutationObserver.start();
    }
    requestRender() {
      var t2, e2;
      return (t2 = this.delegate) === null || t2 === void 0 || (e2 = t2.inputControllerDidRequestRender) === null || e2 === void 0 ? void 0 : e2.call(t2);
    }
    requestReparse() {
      var t2, e2;
      return (t2 = this.delegate) === null || t2 === void 0 || (e2 = t2.inputControllerDidRequestReparse) === null || e2 === void 0 || e2.call(t2), this.requestRender();
    }
    attachFiles(t2) {
      const e2 = Array.from(t2).map((t3) => new Vi(t3));
      return Promise.all(e2).then((t3) => {
        this.handleInput(function() {
          var e3, i2;
          return (e3 = this.delegate) === null || e3 === void 0 || e3.inputControllerWillAttachFiles(), (i2 = this.responder) === null || i2 === void 0 || i2.insertFiles(t3), this.requestRender();
        });
      });
    }
    handlerFor(t2) {
      return (e2) => {
        e2.defaultPrevented || this.handleInput(() => {
          if (!x(this.element)) {
            if (this.flakyKeyboardDetector.shouldIgnore(e2))
              return;
            this.eventName = t2, this.constructor.events[t2].call(this, e2);
          }
        });
      };
    }
    handleInput(t2) {
      try {
        var e2;
        (e2 = this.delegate) === null || e2 === void 0 || e2.inputControllerWillHandleInput(), t2.call(this);
      } finally {
        var i2;
        (i2 = this.delegate) === null || i2 === void 0 || i2.inputControllerDidHandleInput();
      }
    }
    createLinkHTML(t2, e2) {
      const i2 = document.createElement("a");
      return i2.href = t2, i2.textContent = e2 || t2, i2.outerHTML;
    }
  };
  var Gi;
  Ae(Ki, "events", {});
  var { browser: $i, keyNames: Xi } = V;
  var Yi = 0;
  var Qi = class extends Ki {
    constructor() {
      super(...arguments), this.resetInputSummary();
    }
    setInputSummary() {
      let t2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
      this.inputSummary.eventName = this.eventName;
      for (const e2 in t2) {
        const i2 = t2[e2];
        this.inputSummary[e2] = i2;
      }
      return this.inputSummary;
    }
    resetInputSummary() {
      this.inputSummary = {};
    }
    reset() {
      return this.resetInputSummary(), It.reset();
    }
    elementDidMutate(t2) {
      var e2, i2;
      return this.isComposing() ? (e2 = this.delegate) === null || e2 === void 0 || (i2 = e2.inputControllerDidAllowUnhandledInput) === null || i2 === void 0 ? void 0 : i2.call(e2) : this.handleInput(function() {
        return this.mutationIsSignificant(t2) && (this.mutationIsExpected(t2) ? this.requestRender() : this.requestReparse()), this.reset();
      });
    }
    mutationIsExpected(t2) {
      let { textAdded: e2, textDeleted: i2 } = t2;
      if (this.inputSummary.preferDocument)
        return true;
      const n2 = e2 != null ? e2 === this.inputSummary.textAdded : !this.inputSummary.textAdded, r2 = i2 != null ? this.inputSummary.didDelete : !this.inputSummary.didDelete, o2 = ["\n", " \n"].includes(e2) && !n2, s2 = i2 === "\n" && !r2;
      if (o2 && !s2 || s2 && !o2) {
        const t3 = this.getSelectedRange();
        if (t3) {
          var a2;
          const i3 = o2 ? e2.replace(/\n$/, "").length || -1 : (e2 == null ? void 0 : e2.length) || 1;
          if ((a2 = this.responder) !== null && a2 !== void 0 && a2.positionIsBlockBreak(t3[1] + i3))
            return true;
        }
      }
      return n2 && r2;
    }
    mutationIsSignificant(t2) {
      var e2;
      const i2 = Object.keys(t2).length > 0, n2 = ((e2 = this.compositionInput) === null || e2 === void 0 ? void 0 : e2.getEndData()) === "";
      return i2 || !n2;
    }
    getCompositionInput() {
      if (this.isComposing())
        return this.compositionInput;
      this.compositionInput = new rn(this);
    }
    isComposing() {
      return this.compositionInput && !this.compositionInput.isEnded();
    }
    deleteInDirection(t2, e2) {
      var i2;
      return ((i2 = this.responder) === null || i2 === void 0 ? void 0 : i2.deleteInDirection(t2)) !== false ? this.setInputSummary({ didDelete: true }) : e2 ? (e2.preventDefault(), this.requestRender()) : void 0;
    }
    serializeSelectionToDataTransfer(t2) {
      var e2;
      if (!function(t3) {
        if (t3 == null || !t3.setData)
          return false;
        for (const e3 in yt) {
          const i3 = yt[e3];
          try {
            if (t3.setData(e3, i3), !t3.getData(e3) === i3)
              return false;
          } catch (t4) {
            return false;
          }
        }
        return true;
      }(t2))
        return;
      const i2 = (e2 = this.responder) === null || e2 === void 0 ? void 0 : e2.getSelectedDocument().toSerializableDocument();
      return t2.setData("application/x-trix-document", JSON.stringify(i2)), t2.setData("text/html", ge.render(i2).innerHTML), t2.setData("text/plain", i2.toString().replace(/\n$/, "")), true;
    }
    canAcceptDataTransfer(t2) {
      const e2 = {};
      return Array.from((t2 == null ? void 0 : t2.types) || []).forEach((t3) => {
        e2[t3] = true;
      }), e2.Files || e2["application/x-trix-document"] || e2["text/html"] || e2["text/plain"];
    }
    getPastedHTMLUsingHiddenElement(t2) {
      const e2 = this.getSelectedRange(), i2 = { position: "absolute", left: "".concat(window.pageXOffset, "px"), top: "".concat(window.pageYOffset, "px"), opacity: 0 }, n2 = k({ style: i2, tagName: "div", editable: true });
      return document.body.appendChild(n2), n2.focus(), requestAnimationFrame(() => {
        const i3 = n2.innerHTML;
        return R(n2), this.setSelectedRange(e2), t2(i3);
      });
    }
  };
  Ae(Qi, "events", { keydown(t2) {
    this.isComposing() || this.resetInputSummary(), this.inputSummary.didInput = true;
    const e2 = Xi[t2.keyCode];
    if (e2) {
      var i2;
      let n3 = this.keys;
      ["ctrl", "alt", "shift", "meta"].forEach((e3) => {
        var i3;
        t2["".concat(e3, "Key")] && (e3 === "ctrl" && (e3 = "control"), n3 = (i3 = n3) === null || i3 === void 0 ? void 0 : i3[e3]);
      }), ((i2 = n3) === null || i2 === void 0 ? void 0 : i2[e2]) != null && (this.setInputSummary({ keyName: e2 }), It.reset(), n3[e2].call(this, t2));
    }
    if (Rt(t2)) {
      const e3 = String.fromCharCode(t2.keyCode).toLowerCase();
      if (e3) {
        var n2;
        const i3 = ["alt", "shift"].map((e4) => {
          if (t2["".concat(e4, "Key")])
            return e4;
        }).filter((t3) => t3);
        i3.push(e3), (n2 = this.delegate) !== null && n2 !== void 0 && n2.inputControllerDidReceiveKeyboardCommand(i3) && t2.preventDefault();
      }
    }
  }, keypress(t2) {
    if (this.inputSummary.eventName != null)
      return;
    if (t2.metaKey)
      return;
    if (t2.ctrlKey && !t2.altKey)
      return;
    const e2 = en(t2);
    var i2, n2;
    return e2 ? ((i2 = this.delegate) === null || i2 === void 0 || i2.inputControllerWillPerformTyping(), (n2 = this.responder) === null || n2 === void 0 || n2.insertString(e2), this.setInputSummary({ textAdded: e2, didDelete: this.selectionIsExpanded() })) : void 0;
  }, textInput(t2) {
    const { data: e2 } = t2, { textAdded: i2 } = this.inputSummary;
    if (i2 && i2 !== e2 && i2.toUpperCase() === e2) {
      var n2;
      const t3 = this.getSelectedRange();
      return this.setSelectedRange([t3[0], t3[1] + i2.length]), (n2 = this.responder) === null || n2 === void 0 || n2.insertString(e2), this.setInputSummary({ textAdded: e2 }), this.setSelectedRange(t3);
    }
  }, dragenter(t2) {
    t2.preventDefault();
  }, dragstart(t2) {
    var e2, i2;
    return this.serializeSelectionToDataTransfer(t2.dataTransfer), this.draggedRange = this.getSelectedRange(), (e2 = this.delegate) === null || e2 === void 0 || (i2 = e2.inputControllerDidStartDrag) === null || i2 === void 0 ? void 0 : i2.call(e2);
  }, dragover(t2) {
    if (this.draggedRange || this.canAcceptDataTransfer(t2.dataTransfer)) {
      t2.preventDefault();
      const n2 = { x: t2.clientX, y: t2.clientY };
      var e2, i2;
      if (!kt(n2, this.draggingPoint))
        return this.draggingPoint = n2, (e2 = this.delegate) === null || e2 === void 0 || (i2 = e2.inputControllerDidReceiveDragOverPoint) === null || i2 === void 0 ? void 0 : i2.call(e2, this.draggingPoint);
    }
  }, dragend(t2) {
    var e2, i2;
    (e2 = this.delegate) === null || e2 === void 0 || (i2 = e2.inputControllerDidCancelDrag) === null || i2 === void 0 || i2.call(e2), this.draggedRange = null, this.draggingPoint = null;
  }, drop(t2) {
    var e2, i2;
    t2.preventDefault();
    const n2 = (e2 = t2.dataTransfer) === null || e2 === void 0 ? void 0 : e2.files, r2 = t2.dataTransfer.getData("application/x-trix-document"), o2 = { x: t2.clientX, y: t2.clientY };
    if ((i2 = this.responder) === null || i2 === void 0 || i2.setLocationRangeFromPointRange(o2), n2 != null && n2.length)
      this.attachFiles(n2);
    else if (this.draggedRange) {
      var s2, a2;
      (s2 = this.delegate) === null || s2 === void 0 || s2.inputControllerWillMoveText(), (a2 = this.responder) === null || a2 === void 0 || a2.moveTextFromRange(this.draggedRange), this.draggedRange = null, this.requestRender();
    } else if (r2) {
      var l2;
      const t3 = qe.fromJSONString(r2);
      (l2 = this.responder) === null || l2 === void 0 || l2.insertDocument(t3), this.requestRender();
    }
    this.draggedRange = null, this.draggingPoint = null;
  }, cut(t2) {
    var e2, i2;
    if ((e2 = this.responder) !== null && e2 !== void 0 && e2.selectionIsExpanded() && (this.serializeSelectionToDataTransfer(t2.clipboardData) && t2.preventDefault(), (i2 = this.delegate) === null || i2 === void 0 || i2.inputControllerWillCutText(), this.deleteInDirection("backward"), t2.defaultPrevented))
      return this.requestRender();
  }, copy(t2) {
    var e2;
    (e2 = this.responder) !== null && e2 !== void 0 && e2.selectionIsExpanded() && this.serializeSelectionToDataTransfer(t2.clipboardData) && t2.preventDefault();
  }, paste(t2) {
    const e2 = t2.clipboardData || t2.testClipboardData, i2 = { clipboard: e2 };
    if (!e2 || nn(t2))
      return void this.getPastedHTMLUsingHiddenElement((t3) => {
        var e3, n3, r3;
        return i2.type = "text/html", i2.html = t3, (e3 = this.delegate) === null || e3 === void 0 || e3.inputControllerWillPaste(i2), (n3 = this.responder) === null || n3 === void 0 || n3.insertHTML(i2.html), this.requestRender(), (r3 = this.delegate) === null || r3 === void 0 ? void 0 : r3.inputControllerDidPaste(i2);
      });
    const n2 = e2.getData("URL"), r2 = e2.getData("text/html"), o2 = e2.getData("public.url-name");
    if (n2) {
      var s2, a2, l2;
      let t3;
      i2.type = "text/html", t3 = o2 ? qt(o2).trim() : n2, i2.html = this.createLinkHTML(n2, t3), (s2 = this.delegate) === null || s2 === void 0 || s2.inputControllerWillPaste(i2), this.setInputSummary({ textAdded: t3, didDelete: this.selectionIsExpanded() }), (a2 = this.responder) === null || a2 === void 0 || a2.insertHTML(i2.html), this.requestRender(), (l2 = this.delegate) === null || l2 === void 0 || l2.inputControllerDidPaste(i2);
    } else if (Ct(e2)) {
      var c2, h3, u2;
      i2.type = "text/plain", i2.string = e2.getData("text/plain"), (c2 = this.delegate) === null || c2 === void 0 || c2.inputControllerWillPaste(i2), this.setInputSummary({ textAdded: i2.string, didDelete: this.selectionIsExpanded() }), (h3 = this.responder) === null || h3 === void 0 || h3.insertString(i2.string), this.requestRender(), (u2 = this.delegate) === null || u2 === void 0 || u2.inputControllerDidPaste(i2);
    } else if (r2) {
      var d2, g2, m2;
      i2.type = "text/html", i2.html = r2, (d2 = this.delegate) === null || d2 === void 0 || d2.inputControllerWillPaste(i2), (g2 = this.responder) === null || g2 === void 0 || g2.insertHTML(i2.html), this.requestRender(), (m2 = this.delegate) === null || m2 === void 0 || m2.inputControllerDidPaste(i2);
    } else if (Array.from(e2.types).includes("Files")) {
      var p2, f2;
      const t3 = (p2 = e2.items) === null || p2 === void 0 || (p2 = p2[0]) === null || p2 === void 0 || (f2 = p2.getAsFile) === null || f2 === void 0 ? void 0 : f2.call(p2);
      if (t3) {
        var b2, v2, A2;
        const e3 = Zi(t3);
        !t3.name && e3 && (t3.name = "pasted-file-".concat(++Yi, ".").concat(e3)), i2.type = "File", i2.file = t3, (b2 = this.delegate) === null || b2 === void 0 || b2.inputControllerWillAttachFiles(), (v2 = this.responder) === null || v2 === void 0 || v2.insertFile(i2.file), this.requestRender(), (A2 = this.delegate) === null || A2 === void 0 || A2.inputControllerDidPaste(i2);
      }
    }
    t2.preventDefault();
  }, compositionstart(t2) {
    return this.getCompositionInput().start(t2.data);
  }, compositionupdate(t2) {
    return this.getCompositionInput().update(t2.data);
  }, compositionend(t2) {
    return this.getCompositionInput().end(t2.data);
  }, beforeinput(t2) {
    this.inputSummary.didInput = true;
  }, input(t2) {
    return this.inputSummary.didInput = true, t2.stopPropagation();
  } }), Ae(Qi, "keys", { backspace(t2) {
    var e2;
    return (e2 = this.delegate) === null || e2 === void 0 || e2.inputControllerWillPerformTyping(), this.deleteInDirection("backward", t2);
  }, delete(t2) {
    var e2;
    return (e2 = this.delegate) === null || e2 === void 0 || e2.inputControllerWillPerformTyping(), this.deleteInDirection("forward", t2);
  }, return(t2) {
    var e2, i2;
    return this.setInputSummary({ preferDocument: true }), (e2 = this.delegate) === null || e2 === void 0 || e2.inputControllerWillPerformTyping(), (i2 = this.responder) === null || i2 === void 0 ? void 0 : i2.insertLineBreak();
  }, tab(t2) {
    var e2, i2;
    (e2 = this.responder) !== null && e2 !== void 0 && e2.canIncreaseNestingLevel() && ((i2 = this.responder) === null || i2 === void 0 || i2.increaseNestingLevel(), this.requestRender(), t2.preventDefault());
  }, left(t2) {
    var e2;
    if (this.selectionIsInCursorTarget())
      return t2.preventDefault(), (e2 = this.responder) === null || e2 === void 0 ? void 0 : e2.moveCursorInDirection("backward");
  }, right(t2) {
    var e2;
    if (this.selectionIsInCursorTarget())
      return t2.preventDefault(), (e2 = this.responder) === null || e2 === void 0 ? void 0 : e2.moveCursorInDirection("forward");
  }, control: { d(t2) {
    var e2;
    return (e2 = this.delegate) === null || e2 === void 0 || e2.inputControllerWillPerformTyping(), this.deleteInDirection("forward", t2);
  }, h(t2) {
    var e2;
    return (e2 = this.delegate) === null || e2 === void 0 || e2.inputControllerWillPerformTyping(), this.deleteInDirection("backward", t2);
  }, o(t2) {
    var e2, i2;
    return t2.preventDefault(), (e2 = this.delegate) === null || e2 === void 0 || e2.inputControllerWillPerformTyping(), (i2 = this.responder) === null || i2 === void 0 || i2.insertString("\n", { updatePosition: false }), this.requestRender();
  } }, shift: { return(t2) {
    var e2, i2;
    (e2 = this.delegate) === null || e2 === void 0 || e2.inputControllerWillPerformTyping(), (i2 = this.responder) === null || i2 === void 0 || i2.insertString("\n"), this.requestRender(), t2.preventDefault();
  }, tab(t2) {
    var e2, i2;
    (e2 = this.responder) !== null && e2 !== void 0 && e2.canDecreaseNestingLevel() && ((i2 = this.responder) === null || i2 === void 0 || i2.decreaseNestingLevel(), this.requestRender(), t2.preventDefault());
  }, left(t2) {
    if (this.selectionIsInCursorTarget())
      return t2.preventDefault(), this.expandSelectionInDirection("backward");
  }, right(t2) {
    if (this.selectionIsInCursorTarget())
      return t2.preventDefault(), this.expandSelectionInDirection("forward");
  } }, alt: { backspace(t2) {
    var e2;
    return this.setInputSummary({ preferDocument: false }), (e2 = this.delegate) === null || e2 === void 0 ? void 0 : e2.inputControllerWillPerformTyping();
  } }, meta: { backspace(t2) {
    var e2;
    return this.setInputSummary({ preferDocument: false }), (e2 = this.delegate) === null || e2 === void 0 ? void 0 : e2.inputControllerWillPerformTyping();
  } } }), Qi.proxyMethod("responder?.getSelectedRange"), Qi.proxyMethod("responder?.setSelectedRange"), Qi.proxyMethod("responder?.expandSelectionInDirection"), Qi.proxyMethod("responder?.selectionIsInCursorTarget"), Qi.proxyMethod("responder?.selectionIsExpanded");
  var Zi = (t2) => {
    var e2;
    return (e2 = t2.type) === null || e2 === void 0 || (e2 = e2.match(/\/(\w+)$/)) === null || e2 === void 0 ? void 0 : e2[1];
  };
  var tn = !((Gi = " ".codePointAt) === null || Gi === void 0 || !Gi.call(" ", 0));
  var en = function(t2) {
    if (t2.key && tn && t2.key.codePointAt(0) === t2.keyCode)
      return t2.key;
    {
      let e2;
      if (t2.which === null ? e2 = t2.keyCode : t2.which !== 0 && t2.charCode !== 0 && (e2 = t2.charCode), e2 != null && Xi[e2] !== "escape")
        return X.fromCodepoints([e2]).toString();
    }
  };
  var nn = function(t2) {
    const e2 = t2.clipboardData;
    if (e2) {
      if (e2.types.includes("text/html")) {
        for (const t3 of e2.types) {
          const i2 = /^CorePasteboardFlavorType/.test(t3), n2 = /^dyn\./.test(t3) && e2.getData(t3);
          if (i2 || n2)
            return true;
        }
        return false;
      }
      {
        const t3 = e2.types.includes("com.apple.webarchive"), i2 = e2.types.includes("com.apple.flat-rtfd");
        return t3 || i2;
      }
    }
  };
  var rn = class extends z {
    constructor(t2) {
      super(...arguments), this.inputController = t2, this.responder = this.inputController.responder, this.delegate = this.inputController.delegate, this.inputSummary = this.inputController.inputSummary, this.data = {};
    }
    start(t2) {
      if (this.data.start = t2, this.isSignificant()) {
        var e2, i2;
        if (this.inputSummary.eventName === "keypress" && this.inputSummary.textAdded)
          (i2 = this.responder) === null || i2 === void 0 || i2.deleteInDirection("left");
        this.selectionIsExpanded() || (this.insertPlaceholder(), this.requestRender()), this.range = (e2 = this.responder) === null || e2 === void 0 ? void 0 : e2.getSelectedRange();
      }
    }
    update(t2) {
      if (this.data.update = t2, this.isSignificant()) {
        const t3 = this.selectPlaceholder();
        t3 && (this.forgetPlaceholder(), this.range = t3);
      }
    }
    end(t2) {
      return this.data.end = t2, this.isSignificant() ? (this.forgetPlaceholder(), this.canApplyToDocument() ? (this.setInputSummary({ preferDocument: true, didInput: false }), (e2 = this.delegate) === null || e2 === void 0 || e2.inputControllerWillPerformTyping(), (i2 = this.responder) === null || i2 === void 0 || i2.setSelectedRange(this.range), (n2 = this.responder) === null || n2 === void 0 || n2.insertString(this.data.end), (r2 = this.responder) === null || r2 === void 0 ? void 0 : r2.setSelectedRange(this.range[0] + this.data.end.length)) : this.data.start != null || this.data.update != null ? (this.requestReparse(), this.inputController.reset()) : void 0) : this.inputController.reset();
      var e2, i2, n2, r2;
    }
    getEndData() {
      return this.data.end;
    }
    isEnded() {
      return this.getEndData() != null;
    }
    isSignificant() {
      return !$i.composesExistingText || this.inputSummary.didInput;
    }
    canApplyToDocument() {
      var t2, e2;
      return ((t2 = this.data.start) === null || t2 === void 0 ? void 0 : t2.length) === 0 && ((e2 = this.data.end) === null || e2 === void 0 ? void 0 : e2.length) > 0 && this.range;
    }
  };
  rn.proxyMethod("inputController.setInputSummary"), rn.proxyMethod("inputController.requestRender"), rn.proxyMethod("inputController.requestReparse"), rn.proxyMethod("responder?.selectionIsExpanded"), rn.proxyMethod("responder?.insertPlaceholder"), rn.proxyMethod("responder?.selectPlaceholder"), rn.proxyMethod("responder?.forgetPlaceholder");
  var on = class extends Ki {
    constructor() {
      super(...arguments), this.render = this.render.bind(this);
    }
    elementDidMutate() {
      return this.scheduledRender ? this.composing ? (t2 = this.delegate) === null || t2 === void 0 || (e2 = t2.inputControllerDidAllowUnhandledInput) === null || e2 === void 0 ? void 0 : e2.call(t2) : void 0 : this.reparse();
      var t2, e2;
    }
    scheduleRender() {
      return this.scheduledRender ? this.scheduledRender : this.scheduledRender = requestAnimationFrame(this.render);
    }
    render() {
      var t2, e2;
      (cancelAnimationFrame(this.scheduledRender), this.scheduledRender = null, this.composing) || ((e2 = this.delegate) === null || e2 === void 0 || e2.render());
      (t2 = this.afterRender) === null || t2 === void 0 || t2.call(this), this.afterRender = null;
    }
    reparse() {
      var t2;
      return (t2 = this.delegate) === null || t2 === void 0 ? void 0 : t2.reparse();
    }
    insertString() {
      var t2;
      let e2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : "", i2 = arguments.length > 1 ? arguments[1] : void 0;
      return (t2 = this.delegate) === null || t2 === void 0 || t2.inputControllerWillPerformTyping(), this.withTargetDOMRange(function() {
        var t3;
        return (t3 = this.responder) === null || t3 === void 0 ? void 0 : t3.insertString(e2, i2);
      });
    }
    toggleAttributeIfSupported(t2) {
      var e2;
      if (dt().includes(t2))
        return (e2 = this.delegate) === null || e2 === void 0 || e2.inputControllerWillPerformFormatting(t2), this.withTargetDOMRange(function() {
          var e3;
          return (e3 = this.responder) === null || e3 === void 0 ? void 0 : e3.toggleCurrentAttribute(t2);
        });
    }
    activateAttributeIfSupported(t2, e2) {
      var i2;
      if (dt().includes(t2))
        return (i2 = this.delegate) === null || i2 === void 0 || i2.inputControllerWillPerformFormatting(t2), this.withTargetDOMRange(function() {
          var i3;
          return (i3 = this.responder) === null || i3 === void 0 ? void 0 : i3.setCurrentAttribute(t2, e2);
        });
    }
    deleteInDirection(t2) {
      let { recordUndoEntry: e2 } = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : { recordUndoEntry: true };
      var i2;
      e2 && ((i2 = this.delegate) === null || i2 === void 0 || i2.inputControllerWillPerformTyping());
      const n2 = () => {
        var e3;
        return (e3 = this.responder) === null || e3 === void 0 ? void 0 : e3.deleteInDirection(t2);
      }, r2 = this.getTargetDOMRange({ minLength: 2 });
      return r2 ? this.withTargetDOMRange(r2, n2) : n2();
    }
    withTargetDOMRange(t2, e2) {
      var i2;
      return typeof t2 == "function" && (e2 = t2, t2 = this.getTargetDOMRange()), t2 ? (i2 = this.responder) === null || i2 === void 0 ? void 0 : i2.withTargetDOMRange(t2, e2.bind(this)) : (It.reset(), e2.call(this));
    }
    getTargetDOMRange() {
      var t2, e2;
      let { minLength: i2 } = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : { minLength: 0 };
      const n2 = (t2 = (e2 = this.event).getTargetRanges) === null || t2 === void 0 ? void 0 : t2.call(e2);
      if (n2 && n2.length) {
        const t3 = sn(n2[0]);
        if (i2 === 0 || t3.toString().length >= i2)
          return t3;
      }
    }
    withEvent(t2, e2) {
      let i2;
      this.event = t2;
      try {
        i2 = e2.call(this);
      } finally {
        this.event = null;
      }
      return i2;
    }
  };
  Ae(on, "events", { keydown(t2) {
    if (Rt(t2)) {
      var e2;
      const i2 = hn(t2);
      (e2 = this.delegate) !== null && e2 !== void 0 && e2.inputControllerDidReceiveKeyboardCommand(i2) && t2.preventDefault();
    } else {
      let e3 = t2.key;
      t2.altKey && (e3 += "+Alt"), t2.shiftKey && (e3 += "+Shift");
      const i2 = this.constructor.keys[e3];
      if (i2)
        return this.withEvent(t2, i2);
    }
  }, paste(t2) {
    var e2;
    let i2;
    const n2 = (e2 = t2.clipboardData) === null || e2 === void 0 ? void 0 : e2.getData("URL");
    return ln(t2) ? (t2.preventDefault(), this.attachFiles(t2.clipboardData.files)) : cn(t2) ? (t2.preventDefault(), i2 = { type: "text/plain", string: t2.clipboardData.getData("text/plain") }, (r2 = this.delegate) === null || r2 === void 0 || r2.inputControllerWillPaste(i2), (o2 = this.responder) === null || o2 === void 0 || o2.insertString(i2.string), this.render(), (s2 = this.delegate) === null || s2 === void 0 ? void 0 : s2.inputControllerDidPaste(i2)) : n2 ? (t2.preventDefault(), i2 = { type: "text/html", html: this.createLinkHTML(n2) }, (a2 = this.delegate) === null || a2 === void 0 || a2.inputControllerWillPaste(i2), (l2 = this.responder) === null || l2 === void 0 || l2.insertHTML(i2.html), this.render(), (c2 = this.delegate) === null || c2 === void 0 ? void 0 : c2.inputControllerDidPaste(i2)) : void 0;
    var r2, o2, s2, a2, l2, c2;
  }, beforeinput(t2) {
    const e2 = this.constructor.inputTypes[t2.inputType];
    e2 && (this.withEvent(t2, e2), this.scheduleRender());
  }, input(t2) {
    It.reset();
  }, dragstart(t2) {
    var e2, i2;
    (e2 = this.responder) !== null && e2 !== void 0 && e2.selectionContainsAttachments() && (t2.dataTransfer.setData("application/x-trix-dragging", true), this.dragging = { range: (i2 = this.responder) === null || i2 === void 0 ? void 0 : i2.getSelectedRange(), point: un(t2) });
  }, dragenter(t2) {
    an(t2) && t2.preventDefault();
  }, dragover(t2) {
    if (this.dragging) {
      t2.preventDefault();
      const i2 = un(t2);
      var e2;
      if (!kt(i2, this.dragging.point))
        return this.dragging.point = i2, (e2 = this.responder) === null || e2 === void 0 ? void 0 : e2.setLocationRangeFromPointRange(i2);
    } else
      an(t2) && t2.preventDefault();
  }, drop(t2) {
    var e2, i2;
    if (this.dragging)
      return t2.preventDefault(), (e2 = this.delegate) === null || e2 === void 0 || e2.inputControllerWillMoveText(), (i2 = this.responder) === null || i2 === void 0 || i2.moveTextFromRange(this.dragging.range), this.dragging = null, this.scheduleRender();
    if (an(t2)) {
      var n2;
      t2.preventDefault();
      const e3 = un(t2);
      return (n2 = this.responder) === null || n2 === void 0 || n2.setLocationRangeFromPointRange(e3), this.attachFiles(t2.dataTransfer.files);
    }
  }, dragend() {
    var t2;
    this.dragging && ((t2 = this.responder) === null || t2 === void 0 || t2.setSelectedRange(this.dragging.range), this.dragging = null);
  }, compositionend(t2) {
    this.composing && (this.composing = false, a.recentAndroid || this.scheduleRender());
  } }), Ae(on, "keys", { ArrowLeft() {
    var t2, e2;
    if ((t2 = this.responder) !== null && t2 !== void 0 && t2.shouldManageMovingCursorInDirection("backward"))
      return this.event.preventDefault(), (e2 = this.responder) === null || e2 === void 0 ? void 0 : e2.moveCursorInDirection("backward");
  }, ArrowRight() {
    var t2, e2;
    if ((t2 = this.responder) !== null && t2 !== void 0 && t2.shouldManageMovingCursorInDirection("forward"))
      return this.event.preventDefault(), (e2 = this.responder) === null || e2 === void 0 ? void 0 : e2.moveCursorInDirection("forward");
  }, Backspace() {
    var t2, e2, i2;
    if ((t2 = this.responder) !== null && t2 !== void 0 && t2.shouldManageDeletingInDirection("backward"))
      return this.event.preventDefault(), (e2 = this.delegate) === null || e2 === void 0 || e2.inputControllerWillPerformTyping(), (i2 = this.responder) === null || i2 === void 0 || i2.deleteInDirection("backward"), this.render();
  }, Tab() {
    var t2, e2;
    if ((t2 = this.responder) !== null && t2 !== void 0 && t2.canIncreaseNestingLevel())
      return this.event.preventDefault(), (e2 = this.responder) === null || e2 === void 0 || e2.increaseNestingLevel(), this.render();
  }, "Tab+Shift"() {
    var t2, e2;
    if ((t2 = this.responder) !== null && t2 !== void 0 && t2.canDecreaseNestingLevel())
      return this.event.preventDefault(), (e2 = this.responder) === null || e2 === void 0 || e2.decreaseNestingLevel(), this.render();
  } }), Ae(on, "inputTypes", { deleteByComposition() {
    return this.deleteInDirection("backward", { recordUndoEntry: false });
  }, deleteByCut() {
    return this.deleteInDirection("backward");
  }, deleteByDrag() {
    return this.event.preventDefault(), this.withTargetDOMRange(function() {
      var t2;
      this.deleteByDragRange = (t2 = this.responder) === null || t2 === void 0 ? void 0 : t2.getSelectedRange();
    });
  }, deleteCompositionText() {
    return this.deleteInDirection("backward", { recordUndoEntry: false });
  }, deleteContent() {
    return this.deleteInDirection("backward");
  }, deleteContentBackward() {
    return this.deleteInDirection("backward");
  }, deleteContentForward() {
    return this.deleteInDirection("forward");
  }, deleteEntireSoftLine() {
    return this.deleteInDirection("forward");
  }, deleteHardLineBackward() {
    return this.deleteInDirection("backward");
  }, deleteHardLineForward() {
    return this.deleteInDirection("forward");
  }, deleteSoftLineBackward() {
    return this.deleteInDirection("backward");
  }, deleteSoftLineForward() {
    return this.deleteInDirection("forward");
  }, deleteWordBackward() {
    return this.deleteInDirection("backward");
  }, deleteWordForward() {
    return this.deleteInDirection("forward");
  }, formatBackColor() {
    return this.activateAttributeIfSupported("backgroundColor", this.event.data);
  }, formatBold() {
    return this.toggleAttributeIfSupported("bold");
  }, formatFontColor() {
    return this.activateAttributeIfSupported("color", this.event.data);
  }, formatFontName() {
    return this.activateAttributeIfSupported("font", this.event.data);
  }, formatIndent() {
    var t2;
    if ((t2 = this.responder) !== null && t2 !== void 0 && t2.canIncreaseNestingLevel())
      return this.withTargetDOMRange(function() {
        var t3;
        return (t3 = this.responder) === null || t3 === void 0 ? void 0 : t3.increaseNestingLevel();
      });
  }, formatItalic() {
    return this.toggleAttributeIfSupported("italic");
  }, formatJustifyCenter() {
    return this.toggleAttributeIfSupported("justifyCenter");
  }, formatJustifyFull() {
    return this.toggleAttributeIfSupported("justifyFull");
  }, formatJustifyLeft() {
    return this.toggleAttributeIfSupported("justifyLeft");
  }, formatJustifyRight() {
    return this.toggleAttributeIfSupported("justifyRight");
  }, formatOutdent() {
    var t2;
    if ((t2 = this.responder) !== null && t2 !== void 0 && t2.canDecreaseNestingLevel())
      return this.withTargetDOMRange(function() {
        var t3;
        return (t3 = this.responder) === null || t3 === void 0 ? void 0 : t3.decreaseNestingLevel();
      });
  }, formatRemove() {
    this.withTargetDOMRange(function() {
      for (const i2 in (t2 = this.responder) === null || t2 === void 0 ? void 0 : t2.getCurrentAttributes()) {
        var t2, e2;
        (e2 = this.responder) === null || e2 === void 0 || e2.removeCurrentAttribute(i2);
      }
    });
  }, formatSetBlockTextDirection() {
    return this.activateAttributeIfSupported("blockDir", this.event.data);
  }, formatSetInlineTextDirection() {
    return this.activateAttributeIfSupported("textDir", this.event.data);
  }, formatStrikeThrough() {
    return this.toggleAttributeIfSupported("strike");
  }, formatSubscript() {
    return this.toggleAttributeIfSupported("sub");
  }, formatSuperscript() {
    return this.toggleAttributeIfSupported("sup");
  }, formatUnderline() {
    return this.toggleAttributeIfSupported("underline");
  }, historyRedo() {
    var t2;
    return (t2 = this.delegate) === null || t2 === void 0 ? void 0 : t2.inputControllerWillPerformRedo();
  }, historyUndo() {
    var t2;
    return (t2 = this.delegate) === null || t2 === void 0 ? void 0 : t2.inputControllerWillPerformUndo();
  }, insertCompositionText() {
    return this.composing = true, this.insertString(this.event.data);
  }, insertFromComposition() {
    return this.composing = false, this.insertString(this.event.data);
  }, insertFromDrop() {
    const t2 = this.deleteByDragRange;
    var e2;
    if (t2)
      return this.deleteByDragRange = null, (e2 = this.delegate) === null || e2 === void 0 || e2.inputControllerWillMoveText(), this.withTargetDOMRange(function() {
        var e3;
        return (e3 = this.responder) === null || e3 === void 0 ? void 0 : e3.moveTextFromRange(t2);
      });
  }, insertFromPaste() {
    var t2;
    const { dataTransfer: e2 } = this.event, i2 = { dataTransfer: e2 }, n2 = e2.getData("URL"), r2 = e2.getData("text/html");
    if (n2) {
      var o2;
      let t3;
      this.event.preventDefault(), i2.type = "text/html";
      const r3 = e2.getData("public.url-name");
      t3 = r3 ? qt(r3).trim() : n2, i2.html = this.createLinkHTML(n2, t3), (o2 = this.delegate) === null || o2 === void 0 || o2.inputControllerWillPaste(i2), this.withTargetDOMRange(function() {
        var t4;
        return (t4 = this.responder) === null || t4 === void 0 ? void 0 : t4.insertHTML(i2.html);
      }), this.afterRender = () => {
        var t4;
        return (t4 = this.delegate) === null || t4 === void 0 ? void 0 : t4.inputControllerDidPaste(i2);
      };
    } else if (Ct(e2)) {
      var s2;
      i2.type = "text/plain", i2.string = e2.getData("text/plain"), (s2 = this.delegate) === null || s2 === void 0 || s2.inputControllerWillPaste(i2), this.withTargetDOMRange(function() {
        var t3;
        return (t3 = this.responder) === null || t3 === void 0 ? void 0 : t3.insertString(i2.string);
      }), this.afterRender = () => {
        var t3;
        return (t3 = this.delegate) === null || t3 === void 0 ? void 0 : t3.inputControllerDidPaste(i2);
      };
    } else if (r2) {
      var a2;
      this.event.preventDefault(), i2.type = "text/html", i2.html = r2, (a2 = this.delegate) === null || a2 === void 0 || a2.inputControllerWillPaste(i2), this.withTargetDOMRange(function() {
        var t3;
        return (t3 = this.responder) === null || t3 === void 0 ? void 0 : t3.insertHTML(i2.html);
      }), this.afterRender = () => {
        var t3;
        return (t3 = this.delegate) === null || t3 === void 0 ? void 0 : t3.inputControllerDidPaste(i2);
      };
    } else if ((t2 = e2.files) !== null && t2 !== void 0 && t2.length) {
      var l2;
      i2.type = "File", i2.file = e2.files[0], (l2 = this.delegate) === null || l2 === void 0 || l2.inputControllerWillPaste(i2), this.withTargetDOMRange(function() {
        var t3;
        return (t3 = this.responder) === null || t3 === void 0 ? void 0 : t3.insertFile(i2.file);
      }), this.afterRender = () => {
        var t3;
        return (t3 = this.delegate) === null || t3 === void 0 ? void 0 : t3.inputControllerDidPaste(i2);
      };
    }
  }, insertFromYank() {
    return this.insertString(this.event.data);
  }, insertLineBreak() {
    return this.insertString("\n");
  }, insertLink() {
    return this.activateAttributeIfSupported("href", this.event.data);
  }, insertOrderedList() {
    return this.toggleAttributeIfSupported("number");
  }, insertParagraph() {
    var t2;
    return (t2 = this.delegate) === null || t2 === void 0 || t2.inputControllerWillPerformTyping(), this.withTargetDOMRange(function() {
      var t3;
      return (t3 = this.responder) === null || t3 === void 0 ? void 0 : t3.insertLineBreak();
    });
  }, insertReplacementText() {
    const t2 = this.event.dataTransfer.getData("text/plain"), e2 = this.event.getTargetRanges()[0];
    this.withTargetDOMRange(e2, () => {
      this.insertString(t2, { updatePosition: false });
    });
  }, insertText() {
    var t2;
    return this.insertString(this.event.data || ((t2 = this.event.dataTransfer) === null || t2 === void 0 ? void 0 : t2.getData("text/plain")));
  }, insertTranspose() {
    return this.insertString(this.event.data);
  }, insertUnorderedList() {
    return this.toggleAttributeIfSupported("bullet");
  } });
  var sn = function(t2) {
    const e2 = document.createRange();
    return e2.setStart(t2.startContainer, t2.startOffset), e2.setEnd(t2.endContainer, t2.endOffset), e2;
  };
  var an = (t2) => {
    var e2;
    return Array.from(((e2 = t2.dataTransfer) === null || e2 === void 0 ? void 0 : e2.types) || []).includes("Files");
  };
  var ln = function(t2) {
    const e2 = t2.clipboardData;
    if (e2)
      return e2.types.includes("Files") && e2.types.length === 1 && e2.files.length >= 1;
  };
  var cn = function(t2) {
    const e2 = t2.clipboardData;
    if (e2)
      return e2.types.includes("text/plain") && e2.types.length === 1;
  };
  var hn = function(t2) {
    const e2 = [];
    return t2.altKey && e2.push("alt"), t2.shiftKey && e2.push("shift"), e2.push(t2.key), e2;
  };
  var un = (t2) => ({ x: t2.clientX, y: t2.clientY });
  var dn = "[data-trix-attribute]";
  var gn = "[data-trix-action]";
  var mn = "".concat(dn, ", ").concat(gn);
  var pn = "[data-trix-dialog]";
  var fn2 = "".concat(pn, "[data-trix-active]");
  var bn = "".concat(pn, " [data-trix-method]");
  var vn = "".concat(pn, " [data-trix-input]");
  var An = (t2, e2) => (e2 || (e2 = yn(t2)), t2.querySelector("[data-trix-input][name='".concat(e2, "']")));
  var xn = (t2) => t2.getAttribute("data-trix-action");
  var yn = (t2) => t2.getAttribute("data-trix-attribute") || t2.getAttribute("data-trix-dialog-attribute");
  var Cn = class extends z {
    constructor(t2) {
      super(t2), this.didClickActionButton = this.didClickActionButton.bind(this), this.didClickAttributeButton = this.didClickAttributeButton.bind(this), this.didClickDialogButton = this.didClickDialogButton.bind(this), this.didKeyDownDialogInput = this.didKeyDownDialogInput.bind(this), this.element = t2, this.attributes = {}, this.actions = {}, this.resetDialogInputs(), f("mousedown", { onElement: this.element, matchingSelector: gn, withCallback: this.didClickActionButton }), f("mousedown", { onElement: this.element, matchingSelector: dn, withCallback: this.didClickAttributeButton }), f("click", { onElement: this.element, matchingSelector: mn, preventDefault: true }), f("click", { onElement: this.element, matchingSelector: bn, withCallback: this.didClickDialogButton }), f("keydown", { onElement: this.element, matchingSelector: vn, withCallback: this.didKeyDownDialogInput });
    }
    didClickActionButton(t2, e2) {
      var i2;
      (i2 = this.delegate) === null || i2 === void 0 || i2.toolbarDidClickButton(), t2.preventDefault();
      const n2 = xn(e2);
      return this.getDialog(n2) ? this.toggleDialog(n2) : (r2 = this.delegate) === null || r2 === void 0 ? void 0 : r2.toolbarDidInvokeAction(n2, e2);
      var r2;
    }
    didClickAttributeButton(t2, e2) {
      var i2;
      (i2 = this.delegate) === null || i2 === void 0 || i2.toolbarDidClickButton(), t2.preventDefault();
      const n2 = yn(e2);
      var r2;
      this.getDialog(n2) ? this.toggleDialog(n2) : (r2 = this.delegate) === null || r2 === void 0 || r2.toolbarDidToggleAttribute(n2);
      return this.refreshAttributeButtons();
    }
    didClickDialogButton(t2, e2) {
      const i2 = A(e2, { matchingSelector: pn });
      return this[e2.getAttribute("data-trix-method")].call(this, i2);
    }
    didKeyDownDialogInput(t2, e2) {
      if (t2.keyCode === 13) {
        t2.preventDefault();
        const i2 = e2.getAttribute("name"), n2 = this.getDialog(i2);
        this.setAttribute(n2);
      }
      if (t2.keyCode === 27)
        return t2.preventDefault(), this.hideDialog();
    }
    updateActions(t2) {
      return this.actions = t2, this.refreshActionButtons();
    }
    refreshActionButtons() {
      return this.eachActionButton((t2, e2) => {
        t2.disabled = this.actions[e2] === false;
      });
    }
    eachActionButton(t2) {
      return Array.from(this.element.querySelectorAll(gn)).map((e2) => t2(e2, xn(e2)));
    }
    updateAttributes(t2) {
      return this.attributes = t2, this.refreshAttributeButtons();
    }
    refreshAttributeButtons() {
      return this.eachAttributeButton((t2, e2) => (t2.disabled = this.attributes[e2] === false, this.attributes[e2] || this.dialogIsVisible(e2) ? (t2.setAttribute("data-trix-active", ""), t2.classList.add("trix-active")) : (t2.removeAttribute("data-trix-active"), t2.classList.remove("trix-active"))));
    }
    eachAttributeButton(t2) {
      return Array.from(this.element.querySelectorAll(dn)).map((e2) => t2(e2, yn(e2)));
    }
    applyKeyboardCommand(t2) {
      const e2 = JSON.stringify(t2.sort());
      for (const t3 of Array.from(this.element.querySelectorAll("[data-trix-key]"))) {
        const i2 = t3.getAttribute("data-trix-key").split("+");
        if (JSON.stringify(i2.sort()) === e2)
          return b("mousedown", { onElement: t3 }), true;
      }
      return false;
    }
    dialogIsVisible(t2) {
      const e2 = this.getDialog(t2);
      if (e2)
        return e2.hasAttribute("data-trix-active");
    }
    toggleDialog(t2) {
      return this.dialogIsVisible(t2) ? this.hideDialog() : this.showDialog(t2);
    }
    showDialog(t2) {
      var e2, i2;
      this.hideDialog(), (e2 = this.delegate) === null || e2 === void 0 || e2.toolbarWillShowDialog();
      const n2 = this.getDialog(t2);
      n2.setAttribute("data-trix-active", ""), n2.classList.add("trix-active"), Array.from(n2.querySelectorAll("input[disabled]")).forEach((t3) => {
        t3.removeAttribute("disabled");
      });
      const r2 = yn(n2);
      if (r2) {
        const e3 = An(n2, t2);
        e3 && (e3.value = this.attributes[r2] || "", e3.select());
      }
      return (i2 = this.delegate) === null || i2 === void 0 ? void 0 : i2.toolbarDidShowDialog(t2);
    }
    setAttribute(t2) {
      const e2 = yn(t2), i2 = An(t2, e2);
      return i2.willValidate && !i2.checkValidity() ? (i2.setAttribute("data-trix-validate", ""), i2.classList.add("trix-validate"), i2.focus()) : ((n2 = this.delegate) === null || n2 === void 0 || n2.toolbarDidUpdateAttribute(e2, i2.value), this.hideDialog());
      var n2;
    }
    removeAttribute(t2) {
      var e2;
      const i2 = yn(t2);
      return (e2 = this.delegate) === null || e2 === void 0 || e2.toolbarDidRemoveAttribute(i2), this.hideDialog();
    }
    hideDialog() {
      const t2 = this.element.querySelector(fn2);
      var e2;
      if (t2)
        return t2.removeAttribute("data-trix-active"), t2.classList.remove("trix-active"), this.resetDialogInputs(), (e2 = this.delegate) === null || e2 === void 0 ? void 0 : e2.toolbarDidHideDialog(((t3) => t3.getAttribute("data-trix-dialog"))(t2));
    }
    resetDialogInputs() {
      Array.from(this.element.querySelectorAll(vn)).forEach((t2) => {
        t2.setAttribute("disabled", "disabled"), t2.removeAttribute("data-trix-validate"), t2.classList.remove("trix-validate");
      });
    }
    getDialog(t2) {
      return this.element.querySelector("[data-trix-dialog=".concat(t2, "]"));
    }
  };
  var Rn = class extends Oi {
    constructor(t2) {
      let { editorElement: e2, document: i2, html: n2 } = t2;
      super(...arguments), this.editorElement = e2, this.selectionManager = new Li(this.editorElement), this.selectionManager.delegate = this, this.composition = new gi(), this.composition.delegate = this, this.attachmentManager = new ui(this.composition.getAttachments()), this.attachmentManager.delegate = this, this.inputController = M.getLevel() === 2 ? new on(this.editorElement) : new Qi(this.editorElement), this.inputController.delegate = this, this.inputController.responder = this.composition, this.compositionController = new Ni(this.editorElement, this.composition), this.compositionController.delegate = this, this.toolbarController = new Cn(this.editorElement.toolbarElement), this.toolbarController.delegate = this, this.editor = new xi(this.composition, this.selectionManager, this.editorElement), i2 ? this.editor.loadDocument(i2) : this.editor.loadHTML(n2);
    }
    registerSelectionManager() {
      return It.registerSelectionManager(this.selectionManager);
    }
    unregisterSelectionManager() {
      return It.unregisterSelectionManager(this.selectionManager);
    }
    render() {
      return this.compositionController.render();
    }
    reparse() {
      return this.composition.replaceHTML(this.editorElement.innerHTML);
    }
    compositionDidChangeDocument(t2) {
      if (this.notifyEditorElement("document-change"), !this.handlingInput)
        return this.render();
    }
    compositionDidChangeCurrentAttributes(t2) {
      return this.currentAttributes = t2, this.toolbarController.updateAttributes(this.currentAttributes), this.updateCurrentActions(), this.notifyEditorElement("attributes-change", { attributes: this.currentAttributes });
    }
    compositionDidPerformInsertionAtRange(t2) {
      this.pasting && (this.pastedRange = t2);
    }
    compositionShouldAcceptFile(t2) {
      return this.notifyEditorElement("file-accept", { file: t2 });
    }
    compositionDidAddAttachment(t2) {
      const e2 = this.attachmentManager.manageAttachment(t2);
      return this.notifyEditorElement("attachment-add", { attachment: e2 });
    }
    compositionDidEditAttachment(t2) {
      this.compositionController.rerenderViewForObject(t2);
      const e2 = this.attachmentManager.manageAttachment(t2);
      return this.notifyEditorElement("attachment-edit", { attachment: e2 }), this.notifyEditorElement("change");
    }
    compositionDidChangeAttachmentPreviewURL(t2) {
      return this.compositionController.invalidateViewForObject(t2), this.notifyEditorElement("change");
    }
    compositionDidRemoveAttachment(t2) {
      const e2 = this.attachmentManager.unmanageAttachment(t2);
      return this.notifyEditorElement("attachment-remove", { attachment: e2 });
    }
    compositionDidStartEditingAttachment(t2, e2) {
      return this.attachmentLocationRange = this.composition.document.getLocationRangeOfAttachment(t2), this.compositionController.installAttachmentEditorForAttachment(t2, e2), this.selectionManager.setLocationRange(this.attachmentLocationRange);
    }
    compositionDidStopEditingAttachment(t2) {
      this.compositionController.uninstallAttachmentEditor(), this.attachmentLocationRange = null;
    }
    compositionDidRequestChangingSelectionToLocationRange(t2) {
      if (!this.loadingSnapshot || this.isFocused())
        return this.requestedLocationRange = t2, this.compositionRevisionWhenLocationRangeRequested = this.composition.revision, this.handlingInput ? void 0 : this.render();
    }
    compositionWillLoadSnapshot() {
      this.loadingSnapshot = true;
    }
    compositionDidLoadSnapshot() {
      this.compositionController.refreshViewCache(), this.render(), this.loadingSnapshot = false;
    }
    getSelectionManager() {
      return this.selectionManager;
    }
    attachmentManagerDidRequestRemovalOfAttachment(t2) {
      return this.removeAttachment(t2);
    }
    compositionControllerWillSyncDocumentView() {
      return this.inputController.editorWillSyncDocumentView(), this.selectionManager.lock(), this.selectionManager.clearSelection();
    }
    compositionControllerDidSyncDocumentView() {
      return this.inputController.editorDidSyncDocumentView(), this.selectionManager.unlock(), this.updateCurrentActions(), this.notifyEditorElement("sync");
    }
    compositionControllerDidRender() {
      this.requestedLocationRange && (this.compositionRevisionWhenLocationRangeRequested === this.composition.revision && this.selectionManager.setLocationRange(this.requestedLocationRange), this.requestedLocationRange = null, this.compositionRevisionWhenLocationRangeRequested = null), this.renderedCompositionRevision !== this.composition.revision && (this.runEditorFilters(), this.composition.updateCurrentAttributes(), this.notifyEditorElement("render")), this.renderedCompositionRevision = this.composition.revision;
    }
    compositionControllerDidFocus() {
      return this.isFocusedInvisibly() && this.setLocationRange({ index: 0, offset: 0 }), this.toolbarController.hideDialog(), this.notifyEditorElement("focus");
    }
    compositionControllerDidBlur() {
      return this.notifyEditorElement("blur");
    }
    compositionControllerDidSelectAttachment(t2, e2) {
      return this.toolbarController.hideDialog(), this.composition.editAttachment(t2, e2);
    }
    compositionControllerDidRequestDeselectingAttachment(t2) {
      const e2 = this.attachmentLocationRange || this.composition.document.getLocationRangeOfAttachment(t2);
      return this.selectionManager.setLocationRange(e2[1]);
    }
    compositionControllerWillUpdateAttachment(t2) {
      return this.editor.recordUndoEntry("Edit Attachment", { context: t2.id, consolidatable: true });
    }
    compositionControllerDidRequestRemovalOfAttachment(t2) {
      return this.removeAttachment(t2);
    }
    inputControllerWillHandleInput() {
      this.handlingInput = true, this.requestedRender = false;
    }
    inputControllerDidRequestRender() {
      this.requestedRender = true;
    }
    inputControllerDidHandleInput() {
      if (this.handlingInput = false, this.requestedRender)
        return this.requestedRender = false, this.render();
    }
    inputControllerDidAllowUnhandledInput() {
      return this.notifyEditorElement("change");
    }
    inputControllerDidRequestReparse() {
      return this.reparse();
    }
    inputControllerWillPerformTyping() {
      return this.recordTypingUndoEntry();
    }
    inputControllerWillPerformFormatting(t2) {
      return this.recordFormattingUndoEntry(t2);
    }
    inputControllerWillCutText() {
      return this.editor.recordUndoEntry("Cut");
    }
    inputControllerWillPaste(t2) {
      return this.editor.recordUndoEntry("Paste"), this.pasting = true, this.notifyEditorElement("before-paste", { paste: t2 });
    }
    inputControllerDidPaste(t2) {
      return t2.range = this.pastedRange, this.pastedRange = null, this.pasting = null, this.notifyEditorElement("paste", { paste: t2 });
    }
    inputControllerWillMoveText() {
      return this.editor.recordUndoEntry("Move");
    }
    inputControllerWillAttachFiles() {
      return this.editor.recordUndoEntry("Drop Files");
    }
    inputControllerWillPerformUndo() {
      return this.editor.undo();
    }
    inputControllerWillPerformRedo() {
      return this.editor.redo();
    }
    inputControllerDidReceiveKeyboardCommand(t2) {
      return this.toolbarController.applyKeyboardCommand(t2);
    }
    inputControllerDidStartDrag() {
      this.locationRangeBeforeDrag = this.selectionManager.getLocationRange();
    }
    inputControllerDidReceiveDragOverPoint(t2) {
      return this.selectionManager.setLocationRangeFromPointRange(t2);
    }
    inputControllerDidCancelDrag() {
      this.selectionManager.setLocationRange(this.locationRangeBeforeDrag), this.locationRangeBeforeDrag = null;
    }
    locationRangeDidChange(t2) {
      return this.composition.updateCurrentAttributes(), this.updateCurrentActions(), this.attachmentLocationRange && !wt(this.attachmentLocationRange, t2) && this.composition.stopEditingAttachment(), this.notifyEditorElement("selection-change");
    }
    toolbarDidClickButton() {
      if (!this.getLocationRange())
        return this.setLocationRange({ index: 0, offset: 0 });
    }
    toolbarDidInvokeAction(t2, e2) {
      return this.invokeAction(t2, e2);
    }
    toolbarDidToggleAttribute(t2) {
      if (this.recordFormattingUndoEntry(t2), this.composition.toggleCurrentAttribute(t2), this.render(), !this.selectionFrozen)
        return this.editorElement.focus();
    }
    toolbarDidUpdateAttribute(t2, e2) {
      if (this.recordFormattingUndoEntry(t2), this.composition.setCurrentAttribute(t2, e2), this.render(), !this.selectionFrozen)
        return this.editorElement.focus();
    }
    toolbarDidRemoveAttribute(t2) {
      if (this.recordFormattingUndoEntry(t2), this.composition.removeCurrentAttribute(t2), this.render(), !this.selectionFrozen)
        return this.editorElement.focus();
    }
    toolbarWillShowDialog(t2) {
      return this.composition.expandSelectionForEditing(), this.freezeSelection();
    }
    toolbarDidShowDialog(t2) {
      return this.notifyEditorElement("toolbar-dialog-show", { dialogName: t2 });
    }
    toolbarDidHideDialog(t2) {
      return this.thawSelection(), this.editorElement.focus(), this.notifyEditorElement("toolbar-dialog-hide", { dialogName: t2 });
    }
    freezeSelection() {
      if (!this.selectionFrozen)
        return this.selectionManager.lock(), this.composition.freezeSelection(), this.selectionFrozen = true, this.render();
    }
    thawSelection() {
      if (this.selectionFrozen)
        return this.composition.thawSelection(), this.selectionManager.unlock(), this.selectionFrozen = false, this.render();
    }
    canInvokeAction(t2) {
      return !!this.actionIsExternal(t2) || !((e2 = this.actions[t2]) === null || e2 === void 0 || (e2 = e2.test) === null || e2 === void 0 || !e2.call(this));
      var e2;
    }
    invokeAction(t2, e2) {
      return this.actionIsExternal(t2) ? this.notifyEditorElement("action-invoke", { actionName: t2, invokingElement: e2 }) : (i2 = this.actions[t2]) === null || i2 === void 0 || (i2 = i2.perform) === null || i2 === void 0 ? void 0 : i2.call(this);
      var i2;
    }
    actionIsExternal(t2) {
      return /^x-./.test(t2);
    }
    getCurrentActions() {
      const t2 = {};
      for (const e2 in this.actions)
        t2[e2] = this.canInvokeAction(e2);
      return t2;
    }
    updateCurrentActions() {
      const t2 = this.getCurrentActions();
      if (!kt(t2, this.currentActions))
        return this.currentActions = t2, this.toolbarController.updateActions(this.currentActions), this.notifyEditorElement("actions-change", { actions: this.currentActions });
    }
    runEditorFilters() {
      let t2 = this.composition.getSnapshot();
      if (Array.from(this.editor.filters).forEach((e3) => {
        const { document: i3, selectedRange: n2 } = t2;
        t2 = e3.call(this.editor, t2) || {}, t2.document || (t2.document = i3), t2.selectedRange || (t2.selectedRange = n2);
      }), e2 = t2, i2 = this.composition.getSnapshot(), !wt(e2.selectedRange, i2.selectedRange) || !e2.document.isEqualTo(i2.document))
        return this.composition.loadSnapshot(t2);
      var e2, i2;
    }
    updateInputElement() {
      const t2 = function(t3, e2) {
        const i2 = li[e2];
        if (i2)
          return i2(t3);
        throw new Error("unknown content type: ".concat(e2));
      }(this.compositionController.getSerializableElement(), "text/html");
      return this.editorElement.setInputElementValue(t2);
    }
    notifyEditorElement(t2, e2) {
      switch (t2) {
        case "document-change":
          this.documentChangedSinceLastRender = true;
          break;
        case "render":
          this.documentChangedSinceLastRender && (this.documentChangedSinceLastRender = false, this.notifyEditorElement("change"));
          break;
        case "change":
        case "attachment-add":
        case "attachment-edit":
        case "attachment-remove":
          this.updateInputElement();
      }
      return this.editorElement.notify(t2, e2);
    }
    removeAttachment(t2) {
      return this.editor.recordUndoEntry("Delete Attachment"), this.composition.removeAttachment(t2), this.render();
    }
    recordFormattingUndoEntry(t2) {
      const e2 = gt(t2), i2 = this.selectionManager.getLocationRange();
      if (e2 || !Dt(i2))
        return this.editor.recordUndoEntry("Formatting", { context: this.getUndoContext(), consolidatable: true });
    }
    recordTypingUndoEntry() {
      return this.editor.recordUndoEntry("Typing", { context: this.getUndoContext(this.currentAttributes), consolidatable: true });
    }
    getUndoContext() {
      for (var t2 = arguments.length, e2 = new Array(t2), i2 = 0; i2 < t2; i2++)
        e2[i2] = arguments[i2];
      return [this.getLocationContext(), this.getTimeContext(), ...Array.from(e2)];
    }
    getLocationContext() {
      const t2 = this.selectionManager.getLocationRange();
      return Dt(t2) ? t2[0].index : t2;
    }
    getTimeContext() {
      return q.interval > 0 ? Math.floor(new Date().getTime() / q.interval) : 0;
    }
    isFocused() {
      var t2;
      return this.editorElement === ((t2 = this.editorElement.ownerDocument) === null || t2 === void 0 ? void 0 : t2.activeElement);
    }
    isFocusedInvisibly() {
      return this.isFocused() && !this.getLocationRange();
    }
    get actions() {
      return this.constructor.actions;
    }
  };
  Ae(Rn, "actions", { undo: { test() {
    return this.editor.canUndo();
  }, perform() {
    return this.editor.undo();
  } }, redo: { test() {
    return this.editor.canRedo();
  }, perform() {
    return this.editor.redo();
  } }, link: { test() {
    return this.editor.canActivateAttribute("href");
  } }, increaseNestingLevel: { test() {
    return this.editor.canIncreaseNestingLevel();
  }, perform() {
    return this.editor.increaseNestingLevel() && this.render();
  } }, decreaseNestingLevel: { test() {
    return this.editor.canDecreaseNestingLevel();
  }, perform() {
    return this.editor.decreaseNestingLevel() && this.render();
  } }, attachFiles: { test: () => true, perform() {
    return M.pickFiles(this.editor.insertFiles);
  } } }), Rn.proxyMethod("getSelectionManager().setLocationRange"), Rn.proxyMethod("getSelectionManager().getLocationRange");
  var Sn = Object.freeze({ __proto__: null, AttachmentEditorController: Pi, CompositionController: Ni, Controller: Oi, EditorController: Rn, InputController: Ki, Level0InputController: Qi, Level2InputController: on, ToolbarController: Cn });
  var En = Object.freeze({ __proto__: null, MutationObserver: Ui, SelectionChangeObserver: Ft });
  var kn = Object.freeze({ __proto__: null, FileVerificationOperation: Vi, ImagePreloadOperation: Ce });
  bt("trix-toolbar", "%t {\n  display: block;\n}\n\n%t {\n  white-space: nowrap;\n}\n\n%t [data-trix-dialog] {\n  display: none;\n}\n\n%t [data-trix-dialog][data-trix-active] {\n  display: block;\n}\n\n%t [data-trix-dialog] [data-trix-validate]:invalid {\n  background-color: #ffdddd;\n}");
  var Ln = class extends HTMLElement {
    connectedCallback() {
      this.innerHTML === "" && (this.innerHTML = U.getDefaultHTML());
    }
  };
  var Dn = 0;
  var wn = function(t2) {
    if (!t2.hasAttribute("contenteditable"))
      return t2.setAttribute("contenteditable", ""), function(t3) {
        let e2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
        return e2.times = 1, f(t3, e2);
      }("focus", { onElement: t2, withCallback: () => Tn(t2) });
  };
  var Tn = function(t2) {
    return Bn(t2), Fn(t2);
  };
  var Bn = function(t2) {
    var e2, i2;
    if ((e2 = (i2 = document).queryCommandSupported) !== null && e2 !== void 0 && e2.call(i2, "enableObjectResizing"))
      return document.execCommand("enableObjectResizing", false, false), f("mscontrolselect", { onElement: t2, preventDefault: true });
  };
  var Fn = function(t2) {
    var e2, i2;
    if ((e2 = (i2 = document).queryCommandSupported) !== null && e2 !== void 0 && e2.call(i2, "DefaultParagraphSeparator")) {
      const { tagName: t3 } = n.default;
      if (["div", "p"].includes(t3))
        return document.execCommand("DefaultParagraphSeparator", false, t3);
    }
  };
  var In = a.forcesObjectResizing ? { display: "inline", width: "auto" } : { display: "inline-block", width: "1px" };
  bt("trix-editor", "%t {\n    display: block;\n}\n\n%t:empty:not(:focus)::before {\n    content: attr(placeholder);\n    color: graytext;\n    cursor: text;\n    pointer-events: none;\n    white-space: pre-line;\n}\n\n%t a[contenteditable=false] {\n    cursor: text;\n}\n\n%t img {\n    max-width: 100%;\n    height: auto;\n}\n\n%t ".concat(e, " figcaption textarea {\n    resize: none;\n}\n\n%t ").concat(e, " figcaption textarea.trix-autoresize-clone {\n    position: absolute;\n    left: -9999px;\n    max-height: 0px;\n}\n\n%t ").concat(e, " figcaption[data-trix-placeholder]:empty::before {\n    content: attr(data-trix-placeholder);\n    color: graytext;\n}\n\n%t [data-trix-cursor-target] {\n    display: ").concat(In.display, " !important;\n    width: ").concat(In.width, " !important;\n    padding: 0 !important;\n    margin: 0 !important;\n    border: none !important;\n}\n\n%t [data-trix-cursor-target=left] {\n    vertical-align: top !important;\n    margin-left: -1px !important;\n}\n\n%t [data-trix-cursor-target=right] {\n    vertical-align: bottom !important;\n    margin-right: -1px !important;\n}"));
  var Pn = class extends HTMLElement {
    get trixId() {
      return this.hasAttribute("trix-id") ? this.getAttribute("trix-id") : (this.setAttribute("trix-id", ++Dn), this.trixId);
    }
    get labels() {
      const t2 = [];
      this.id && this.ownerDocument && t2.push(...Array.from(this.ownerDocument.querySelectorAll("label[for='".concat(this.id, "']")) || []));
      const e2 = A(this, { matchingSelector: "label" });
      return e2 && [this, null].includes(e2.control) && t2.push(e2), t2;
    }
    get toolbarElement() {
      var t2;
      if (this.hasAttribute("toolbar"))
        return (t2 = this.ownerDocument) === null || t2 === void 0 ? void 0 : t2.getElementById(this.getAttribute("toolbar"));
      if (this.parentNode) {
        const t3 = "trix-toolbar-".concat(this.trixId);
        this.setAttribute("toolbar", t3);
        const e2 = k("trix-toolbar", { id: t3 });
        return this.parentNode.insertBefore(e2, this), e2;
      }
    }
    get form() {
      var t2;
      return (t2 = this.inputElement) === null || t2 === void 0 ? void 0 : t2.form;
    }
    get inputElement() {
      var t2;
      if (this.hasAttribute("input"))
        return (t2 = this.ownerDocument) === null || t2 === void 0 ? void 0 : t2.getElementById(this.getAttribute("input"));
      if (this.parentNode) {
        const t3 = "trix-input-".concat(this.trixId);
        this.setAttribute("input", t3);
        const e2 = k("input", { type: "hidden", id: t3 });
        return this.parentNode.insertBefore(e2, this.nextElementSibling), e2;
      }
    }
    get editor() {
      var t2;
      return (t2 = this.editorController) === null || t2 === void 0 ? void 0 : t2.editor;
    }
    get name() {
      var t2;
      return (t2 = this.inputElement) === null || t2 === void 0 ? void 0 : t2.name;
    }
    get value() {
      var t2;
      return (t2 = this.inputElement) === null || t2 === void 0 ? void 0 : t2.value;
    }
    set value(t2) {
      var e2;
      this.defaultValue = t2, (e2 = this.editor) === null || e2 === void 0 || e2.loadHTML(this.defaultValue);
    }
    notify(t2, e2) {
      if (this.editorController)
        return b("trix-".concat(t2), { onElement: this, attributes: e2 });
    }
    setInputElementValue(t2) {
      this.inputElement && (this.inputElement.value = t2);
    }
    connectedCallback() {
      this.hasAttribute("data-trix-internal") || (wn(this), function(t2) {
        if (!t2.hasAttribute("role"))
          t2.setAttribute("role", "textbox");
      }(this), function(t2) {
        if (t2.hasAttribute("aria-label") || t2.hasAttribute("aria-labelledby"))
          return;
        const e2 = function() {
          const e3 = Array.from(t2.labels).map((e4) => {
            if (!e4.contains(t2))
              return e4.textContent;
          }).filter((t3) => t3), i2 = e3.join(" ");
          return i2 ? t2.setAttribute("aria-label", i2) : t2.removeAttribute("aria-label");
        };
        e2(), f("focus", { onElement: t2, withCallback: e2 });
      }(this), this.editorController || (b("trix-before-initialize", { onElement: this }), this.editorController = new Rn({ editorElement: this, html: this.defaultValue = this.value }), requestAnimationFrame(() => b("trix-initialize", { onElement: this }))), this.editorController.registerSelectionManager(), this.registerResetListener(), this.registerClickListener(), function(t2) {
        if (!document.querySelector(":focus") && t2.hasAttribute("autofocus") && document.querySelector("[autofocus]") === t2)
          t2.focus();
      }(this));
    }
    disconnectedCallback() {
      var t2;
      return (t2 = this.editorController) === null || t2 === void 0 || t2.unregisterSelectionManager(), this.unregisterResetListener(), this.unregisterClickListener();
    }
    registerResetListener() {
      return this.resetListener = this.resetBubbled.bind(this), window.addEventListener("reset", this.resetListener, false);
    }
    unregisterResetListener() {
      return window.removeEventListener("reset", this.resetListener, false);
    }
    registerClickListener() {
      return this.clickListener = this.clickBubbled.bind(this), window.addEventListener("click", this.clickListener, false);
    }
    unregisterClickListener() {
      return window.removeEventListener("click", this.clickListener, false);
    }
    resetBubbled(t2) {
      if (!t2.defaultPrevented && t2.target === this.form)
        return this.reset();
    }
    clickBubbled(t2) {
      if (t2.defaultPrevented)
        return;
      if (this.contains(t2.target))
        return;
      const e2 = A(t2.target, { matchingSelector: "label" });
      return e2 && Array.from(this.labels).includes(e2) ? this.focus() : void 0;
    }
    reset() {
      this.value = this.defaultValue;
    }
  };
  var Nn = { VERSION: t, config: V, core: ci, models: Di, views: wi, controllers: Sn, observers: En, operations: kn, elements: Object.freeze({ __proto__: null, TrixEditorElement: Pn, TrixToolbarElement: Ln }), filters: Object.freeze({ __proto__: null, Filter: bi, attachmentGalleryFilter: vi }) };
  Object.assign(Nn, Di), window.Trix = Nn, setTimeout(function() {
    customElements.get("trix-toolbar") || customElements.define("trix-toolbar", Ln), customElements.get("trix-editor") || customElements.define("trix-editor", Pn);
  }, 0);

  // ../../node_modules/@rails/actiontext/app/assets/javascripts/actiontext.esm.js
  var sparkMd5 = {
    exports: {}
  };
  (function(module, exports) {
    (function(factory) {
      {
        module.exports = factory();
      }
    })(function(undefined$1) {
      var hex_chr = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"];
      function md5cycle(x2, k2) {
        var a2 = x2[0], b2 = x2[1], c2 = x2[2], d2 = x2[3];
        a2 += (b2 & c2 | ~b2 & d2) + k2[0] - 680876936 | 0;
        a2 = (a2 << 7 | a2 >>> 25) + b2 | 0;
        d2 += (a2 & b2 | ~a2 & c2) + k2[1] - 389564586 | 0;
        d2 = (d2 << 12 | d2 >>> 20) + a2 | 0;
        c2 += (d2 & a2 | ~d2 & b2) + k2[2] + 606105819 | 0;
        c2 = (c2 << 17 | c2 >>> 15) + d2 | 0;
        b2 += (c2 & d2 | ~c2 & a2) + k2[3] - 1044525330 | 0;
        b2 = (b2 << 22 | b2 >>> 10) + c2 | 0;
        a2 += (b2 & c2 | ~b2 & d2) + k2[4] - 176418897 | 0;
        a2 = (a2 << 7 | a2 >>> 25) + b2 | 0;
        d2 += (a2 & b2 | ~a2 & c2) + k2[5] + 1200080426 | 0;
        d2 = (d2 << 12 | d2 >>> 20) + a2 | 0;
        c2 += (d2 & a2 | ~d2 & b2) + k2[6] - 1473231341 | 0;
        c2 = (c2 << 17 | c2 >>> 15) + d2 | 0;
        b2 += (c2 & d2 | ~c2 & a2) + k2[7] - 45705983 | 0;
        b2 = (b2 << 22 | b2 >>> 10) + c2 | 0;
        a2 += (b2 & c2 | ~b2 & d2) + k2[8] + 1770035416 | 0;
        a2 = (a2 << 7 | a2 >>> 25) + b2 | 0;
        d2 += (a2 & b2 | ~a2 & c2) + k2[9] - 1958414417 | 0;
        d2 = (d2 << 12 | d2 >>> 20) + a2 | 0;
        c2 += (d2 & a2 | ~d2 & b2) + k2[10] - 42063 | 0;
        c2 = (c2 << 17 | c2 >>> 15) + d2 | 0;
        b2 += (c2 & d2 | ~c2 & a2) + k2[11] - 1990404162 | 0;
        b2 = (b2 << 22 | b2 >>> 10) + c2 | 0;
        a2 += (b2 & c2 | ~b2 & d2) + k2[12] + 1804603682 | 0;
        a2 = (a2 << 7 | a2 >>> 25) + b2 | 0;
        d2 += (a2 & b2 | ~a2 & c2) + k2[13] - 40341101 | 0;
        d2 = (d2 << 12 | d2 >>> 20) + a2 | 0;
        c2 += (d2 & a2 | ~d2 & b2) + k2[14] - 1502002290 | 0;
        c2 = (c2 << 17 | c2 >>> 15) + d2 | 0;
        b2 += (c2 & d2 | ~c2 & a2) + k2[15] + 1236535329 | 0;
        b2 = (b2 << 22 | b2 >>> 10) + c2 | 0;
        a2 += (b2 & d2 | c2 & ~d2) + k2[1] - 165796510 | 0;
        a2 = (a2 << 5 | a2 >>> 27) + b2 | 0;
        d2 += (a2 & c2 | b2 & ~c2) + k2[6] - 1069501632 | 0;
        d2 = (d2 << 9 | d2 >>> 23) + a2 | 0;
        c2 += (d2 & b2 | a2 & ~b2) + k2[11] + 643717713 | 0;
        c2 = (c2 << 14 | c2 >>> 18) + d2 | 0;
        b2 += (c2 & a2 | d2 & ~a2) + k2[0] - 373897302 | 0;
        b2 = (b2 << 20 | b2 >>> 12) + c2 | 0;
        a2 += (b2 & d2 | c2 & ~d2) + k2[5] - 701558691 | 0;
        a2 = (a2 << 5 | a2 >>> 27) + b2 | 0;
        d2 += (a2 & c2 | b2 & ~c2) + k2[10] + 38016083 | 0;
        d2 = (d2 << 9 | d2 >>> 23) + a2 | 0;
        c2 += (d2 & b2 | a2 & ~b2) + k2[15] - 660478335 | 0;
        c2 = (c2 << 14 | c2 >>> 18) + d2 | 0;
        b2 += (c2 & a2 | d2 & ~a2) + k2[4] - 405537848 | 0;
        b2 = (b2 << 20 | b2 >>> 12) + c2 | 0;
        a2 += (b2 & d2 | c2 & ~d2) + k2[9] + 568446438 | 0;
        a2 = (a2 << 5 | a2 >>> 27) + b2 | 0;
        d2 += (a2 & c2 | b2 & ~c2) + k2[14] - 1019803690 | 0;
        d2 = (d2 << 9 | d2 >>> 23) + a2 | 0;
        c2 += (d2 & b2 | a2 & ~b2) + k2[3] - 187363961 | 0;
        c2 = (c2 << 14 | c2 >>> 18) + d2 | 0;
        b2 += (c2 & a2 | d2 & ~a2) + k2[8] + 1163531501 | 0;
        b2 = (b2 << 20 | b2 >>> 12) + c2 | 0;
        a2 += (b2 & d2 | c2 & ~d2) + k2[13] - 1444681467 | 0;
        a2 = (a2 << 5 | a2 >>> 27) + b2 | 0;
        d2 += (a2 & c2 | b2 & ~c2) + k2[2] - 51403784 | 0;
        d2 = (d2 << 9 | d2 >>> 23) + a2 | 0;
        c2 += (d2 & b2 | a2 & ~b2) + k2[7] + 1735328473 | 0;
        c2 = (c2 << 14 | c2 >>> 18) + d2 | 0;
        b2 += (c2 & a2 | d2 & ~a2) + k2[12] - 1926607734 | 0;
        b2 = (b2 << 20 | b2 >>> 12) + c2 | 0;
        a2 += (b2 ^ c2 ^ d2) + k2[5] - 378558 | 0;
        a2 = (a2 << 4 | a2 >>> 28) + b2 | 0;
        d2 += (a2 ^ b2 ^ c2) + k2[8] - 2022574463 | 0;
        d2 = (d2 << 11 | d2 >>> 21) + a2 | 0;
        c2 += (d2 ^ a2 ^ b2) + k2[11] + 1839030562 | 0;
        c2 = (c2 << 16 | c2 >>> 16) + d2 | 0;
        b2 += (c2 ^ d2 ^ a2) + k2[14] - 35309556 | 0;
        b2 = (b2 << 23 | b2 >>> 9) + c2 | 0;
        a2 += (b2 ^ c2 ^ d2) + k2[1] - 1530992060 | 0;
        a2 = (a2 << 4 | a2 >>> 28) + b2 | 0;
        d2 += (a2 ^ b2 ^ c2) + k2[4] + 1272893353 | 0;
        d2 = (d2 << 11 | d2 >>> 21) + a2 | 0;
        c2 += (d2 ^ a2 ^ b2) + k2[7] - 155497632 | 0;
        c2 = (c2 << 16 | c2 >>> 16) + d2 | 0;
        b2 += (c2 ^ d2 ^ a2) + k2[10] - 1094730640 | 0;
        b2 = (b2 << 23 | b2 >>> 9) + c2 | 0;
        a2 += (b2 ^ c2 ^ d2) + k2[13] + 681279174 | 0;
        a2 = (a2 << 4 | a2 >>> 28) + b2 | 0;
        d2 += (a2 ^ b2 ^ c2) + k2[0] - 358537222 | 0;
        d2 = (d2 << 11 | d2 >>> 21) + a2 | 0;
        c2 += (d2 ^ a2 ^ b2) + k2[3] - 722521979 | 0;
        c2 = (c2 << 16 | c2 >>> 16) + d2 | 0;
        b2 += (c2 ^ d2 ^ a2) + k2[6] + 76029189 | 0;
        b2 = (b2 << 23 | b2 >>> 9) + c2 | 0;
        a2 += (b2 ^ c2 ^ d2) + k2[9] - 640364487 | 0;
        a2 = (a2 << 4 | a2 >>> 28) + b2 | 0;
        d2 += (a2 ^ b2 ^ c2) + k2[12] - 421815835 | 0;
        d2 = (d2 << 11 | d2 >>> 21) + a2 | 0;
        c2 += (d2 ^ a2 ^ b2) + k2[15] + 530742520 | 0;
        c2 = (c2 << 16 | c2 >>> 16) + d2 | 0;
        b2 += (c2 ^ d2 ^ a2) + k2[2] - 995338651 | 0;
        b2 = (b2 << 23 | b2 >>> 9) + c2 | 0;
        a2 += (c2 ^ (b2 | ~d2)) + k2[0] - 198630844 | 0;
        a2 = (a2 << 6 | a2 >>> 26) + b2 | 0;
        d2 += (b2 ^ (a2 | ~c2)) + k2[7] + 1126891415 | 0;
        d2 = (d2 << 10 | d2 >>> 22) + a2 | 0;
        c2 += (a2 ^ (d2 | ~b2)) + k2[14] - 1416354905 | 0;
        c2 = (c2 << 15 | c2 >>> 17) + d2 | 0;
        b2 += (d2 ^ (c2 | ~a2)) + k2[5] - 57434055 | 0;
        b2 = (b2 << 21 | b2 >>> 11) + c2 | 0;
        a2 += (c2 ^ (b2 | ~d2)) + k2[12] + 1700485571 | 0;
        a2 = (a2 << 6 | a2 >>> 26) + b2 | 0;
        d2 += (b2 ^ (a2 | ~c2)) + k2[3] - 1894986606 | 0;
        d2 = (d2 << 10 | d2 >>> 22) + a2 | 0;
        c2 += (a2 ^ (d2 | ~b2)) + k2[10] - 1051523 | 0;
        c2 = (c2 << 15 | c2 >>> 17) + d2 | 0;
        b2 += (d2 ^ (c2 | ~a2)) + k2[1] - 2054922799 | 0;
        b2 = (b2 << 21 | b2 >>> 11) + c2 | 0;
        a2 += (c2 ^ (b2 | ~d2)) + k2[8] + 1873313359 | 0;
        a2 = (a2 << 6 | a2 >>> 26) + b2 | 0;
        d2 += (b2 ^ (a2 | ~c2)) + k2[15] - 30611744 | 0;
        d2 = (d2 << 10 | d2 >>> 22) + a2 | 0;
        c2 += (a2 ^ (d2 | ~b2)) + k2[6] - 1560198380 | 0;
        c2 = (c2 << 15 | c2 >>> 17) + d2 | 0;
        b2 += (d2 ^ (c2 | ~a2)) + k2[13] + 1309151649 | 0;
        b2 = (b2 << 21 | b2 >>> 11) + c2 | 0;
        a2 += (c2 ^ (b2 | ~d2)) + k2[4] - 145523070 | 0;
        a2 = (a2 << 6 | a2 >>> 26) + b2 | 0;
        d2 += (b2 ^ (a2 | ~c2)) + k2[11] - 1120210379 | 0;
        d2 = (d2 << 10 | d2 >>> 22) + a2 | 0;
        c2 += (a2 ^ (d2 | ~b2)) + k2[2] + 718787259 | 0;
        c2 = (c2 << 15 | c2 >>> 17) + d2 | 0;
        b2 += (d2 ^ (c2 | ~a2)) + k2[9] - 343485551 | 0;
        b2 = (b2 << 21 | b2 >>> 11) + c2 | 0;
        x2[0] = a2 + x2[0] | 0;
        x2[1] = b2 + x2[1] | 0;
        x2[2] = c2 + x2[2] | 0;
        x2[3] = d2 + x2[3] | 0;
      }
      function md5blk(s2) {
        var md5blks = [], i2;
        for (i2 = 0; i2 < 64; i2 += 4) {
          md5blks[i2 >> 2] = s2.charCodeAt(i2) + (s2.charCodeAt(i2 + 1) << 8) + (s2.charCodeAt(i2 + 2) << 16) + (s2.charCodeAt(i2 + 3) << 24);
        }
        return md5blks;
      }
      function md5blk_array(a2) {
        var md5blks = [], i2;
        for (i2 = 0; i2 < 64; i2 += 4) {
          md5blks[i2 >> 2] = a2[i2] + (a2[i2 + 1] << 8) + (a2[i2 + 2] << 16) + (a2[i2 + 3] << 24);
        }
        return md5blks;
      }
      function md51(s2) {
        var n2 = s2.length, state = [1732584193, -271733879, -1732584194, 271733878], i2, length, tail, tmp, lo, hi2;
        for (i2 = 64; i2 <= n2; i2 += 64) {
          md5cycle(state, md5blk(s2.substring(i2 - 64, i2)));
        }
        s2 = s2.substring(i2 - 64);
        length = s2.length;
        tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
        for (i2 = 0; i2 < length; i2 += 1) {
          tail[i2 >> 2] |= s2.charCodeAt(i2) << (i2 % 4 << 3);
        }
        tail[i2 >> 2] |= 128 << (i2 % 4 << 3);
        if (i2 > 55) {
          md5cycle(state, tail);
          for (i2 = 0; i2 < 16; i2 += 1) {
            tail[i2] = 0;
          }
        }
        tmp = n2 * 8;
        tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
        lo = parseInt(tmp[2], 16);
        hi2 = parseInt(tmp[1], 16) || 0;
        tail[14] = lo;
        tail[15] = hi2;
        md5cycle(state, tail);
        return state;
      }
      function md51_array(a2) {
        var n2 = a2.length, state = [1732584193, -271733879, -1732584194, 271733878], i2, length, tail, tmp, lo, hi2;
        for (i2 = 64; i2 <= n2; i2 += 64) {
          md5cycle(state, md5blk_array(a2.subarray(i2 - 64, i2)));
        }
        a2 = i2 - 64 < n2 ? a2.subarray(i2 - 64) : new Uint8Array(0);
        length = a2.length;
        tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
        for (i2 = 0; i2 < length; i2 += 1) {
          tail[i2 >> 2] |= a2[i2] << (i2 % 4 << 3);
        }
        tail[i2 >> 2] |= 128 << (i2 % 4 << 3);
        if (i2 > 55) {
          md5cycle(state, tail);
          for (i2 = 0; i2 < 16; i2 += 1) {
            tail[i2] = 0;
          }
        }
        tmp = n2 * 8;
        tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
        lo = parseInt(tmp[2], 16);
        hi2 = parseInt(tmp[1], 16) || 0;
        tail[14] = lo;
        tail[15] = hi2;
        md5cycle(state, tail);
        return state;
      }
      function rhex(n2) {
        var s2 = "", j2;
        for (j2 = 0; j2 < 4; j2 += 1) {
          s2 += hex_chr[n2 >> j2 * 8 + 4 & 15] + hex_chr[n2 >> j2 * 8 & 15];
        }
        return s2;
      }
      function hex2(x2) {
        var i2;
        for (i2 = 0; i2 < x2.length; i2 += 1) {
          x2[i2] = rhex(x2[i2]);
        }
        return x2.join("");
      }
      if (hex2(md51("hello")) !== "5d41402abc4b2a76b9719d911017c592")
        ;
      if (typeof ArrayBuffer !== "undefined" && !ArrayBuffer.prototype.slice) {
        (function() {
          function clamp(val, length) {
            val = val | 0 || 0;
            if (val < 0) {
              return Math.max(val + length, 0);
            }
            return Math.min(val, length);
          }
          ArrayBuffer.prototype.slice = function(from, to) {
            var length = this.byteLength, begin = clamp(from, length), end2 = length, num, target, targetArray, sourceArray;
            if (to !== undefined$1) {
              end2 = clamp(to, length);
            }
            if (begin > end2) {
              return new ArrayBuffer(0);
            }
            num = end2 - begin;
            target = new ArrayBuffer(num);
            targetArray = new Uint8Array(target);
            sourceArray = new Uint8Array(this, begin, num);
            targetArray.set(sourceArray);
            return target;
          };
        })();
      }
      function toUtf8(str) {
        if (/[\u0080-\uFFFF]/.test(str)) {
          str = unescape(encodeURIComponent(str));
        }
        return str;
      }
      function utf8Str2ArrayBuffer(str, returnUInt8Array) {
        var length = str.length, buff = new ArrayBuffer(length), arr = new Uint8Array(buff), i2;
        for (i2 = 0; i2 < length; i2 += 1) {
          arr[i2] = str.charCodeAt(i2);
        }
        return returnUInt8Array ? arr : buff;
      }
      function arrayBuffer2Utf8Str(buff) {
        return String.fromCharCode.apply(null, new Uint8Array(buff));
      }
      function concatenateArrayBuffers(first, second, returnUInt8Array) {
        var result = new Uint8Array(first.byteLength + second.byteLength);
        result.set(new Uint8Array(first));
        result.set(new Uint8Array(second), first.byteLength);
        return returnUInt8Array ? result : result.buffer;
      }
      function hexToBinaryString(hex3) {
        var bytes = [], length = hex3.length, x2;
        for (x2 = 0; x2 < length - 1; x2 += 2) {
          bytes.push(parseInt(hex3.substr(x2, 2), 16));
        }
        return String.fromCharCode.apply(String, bytes);
      }
      function SparkMD52() {
        this.reset();
      }
      SparkMD52.prototype.append = function(str) {
        this.appendBinary(toUtf8(str));
        return this;
      };
      SparkMD52.prototype.appendBinary = function(contents) {
        this._buff += contents;
        this._length += contents.length;
        var length = this._buff.length, i2;
        for (i2 = 64; i2 <= length; i2 += 64) {
          md5cycle(this._hash, md5blk(this._buff.substring(i2 - 64, i2)));
        }
        this._buff = this._buff.substring(i2 - 64);
        return this;
      };
      SparkMD52.prototype.end = function(raw) {
        var buff = this._buff, length = buff.length, i2, tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ret;
        for (i2 = 0; i2 < length; i2 += 1) {
          tail[i2 >> 2] |= buff.charCodeAt(i2) << (i2 % 4 << 3);
        }
        this._finish(tail, length);
        ret = hex2(this._hash);
        if (raw) {
          ret = hexToBinaryString(ret);
        }
        this.reset();
        return ret;
      };
      SparkMD52.prototype.reset = function() {
        this._buff = "";
        this._length = 0;
        this._hash = [1732584193, -271733879, -1732584194, 271733878];
        return this;
      };
      SparkMD52.prototype.getState = function() {
        return {
          buff: this._buff,
          length: this._length,
          hash: this._hash.slice()
        };
      };
      SparkMD52.prototype.setState = function(state) {
        this._buff = state.buff;
        this._length = state.length;
        this._hash = state.hash;
        return this;
      };
      SparkMD52.prototype.destroy = function() {
        delete this._hash;
        delete this._buff;
        delete this._length;
      };
      SparkMD52.prototype._finish = function(tail, length) {
        var i2 = length, tmp, lo, hi2;
        tail[i2 >> 2] |= 128 << (i2 % 4 << 3);
        if (i2 > 55) {
          md5cycle(this._hash, tail);
          for (i2 = 0; i2 < 16; i2 += 1) {
            tail[i2] = 0;
          }
        }
        tmp = this._length * 8;
        tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
        lo = parseInt(tmp[2], 16);
        hi2 = parseInt(tmp[1], 16) || 0;
        tail[14] = lo;
        tail[15] = hi2;
        md5cycle(this._hash, tail);
      };
      SparkMD52.hash = function(str, raw) {
        return SparkMD52.hashBinary(toUtf8(str), raw);
      };
      SparkMD52.hashBinary = function(content, raw) {
        var hash3 = md51(content), ret = hex2(hash3);
        return raw ? hexToBinaryString(ret) : ret;
      };
      SparkMD52.ArrayBuffer = function() {
        this.reset();
      };
      SparkMD52.ArrayBuffer.prototype.append = function(arr) {
        var buff = concatenateArrayBuffers(this._buff.buffer, arr, true), length = buff.length, i2;
        this._length += arr.byteLength;
        for (i2 = 64; i2 <= length; i2 += 64) {
          md5cycle(this._hash, md5blk_array(buff.subarray(i2 - 64, i2)));
        }
        this._buff = i2 - 64 < length ? new Uint8Array(buff.buffer.slice(i2 - 64)) : new Uint8Array(0);
        return this;
      };
      SparkMD52.ArrayBuffer.prototype.end = function(raw) {
        var buff = this._buff, length = buff.length, tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], i2, ret;
        for (i2 = 0; i2 < length; i2 += 1) {
          tail[i2 >> 2] |= buff[i2] << (i2 % 4 << 3);
        }
        this._finish(tail, length);
        ret = hex2(this._hash);
        if (raw) {
          ret = hexToBinaryString(ret);
        }
        this.reset();
        return ret;
      };
      SparkMD52.ArrayBuffer.prototype.reset = function() {
        this._buff = new Uint8Array(0);
        this._length = 0;
        this._hash = [1732584193, -271733879, -1732584194, 271733878];
        return this;
      };
      SparkMD52.ArrayBuffer.prototype.getState = function() {
        var state = SparkMD52.prototype.getState.call(this);
        state.buff = arrayBuffer2Utf8Str(state.buff);
        return state;
      };
      SparkMD52.ArrayBuffer.prototype.setState = function(state) {
        state.buff = utf8Str2ArrayBuffer(state.buff, true);
        return SparkMD52.prototype.setState.call(this, state);
      };
      SparkMD52.ArrayBuffer.prototype.destroy = SparkMD52.prototype.destroy;
      SparkMD52.ArrayBuffer.prototype._finish = SparkMD52.prototype._finish;
      SparkMD52.ArrayBuffer.hash = function(arr, raw) {
        var hash3 = md51_array(new Uint8Array(arr)), ret = hex2(hash3);
        return raw ? hexToBinaryString(ret) : ret;
      };
      return SparkMD52;
    });
  })(sparkMd5);
  var SparkMD5 = sparkMd5.exports;
  var fileSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice;
  var FileChecksum = class {
    static create(file, callback2) {
      const instance = new FileChecksum(file);
      instance.create(callback2);
    }
    constructor(file) {
      this.file = file;
      this.chunkSize = 2097152;
      this.chunkCount = Math.ceil(this.file.size / this.chunkSize);
      this.chunkIndex = 0;
    }
    create(callback2) {
      this.callback = callback2;
      this.md5Buffer = new SparkMD5.ArrayBuffer();
      this.fileReader = new FileReader();
      this.fileReader.addEventListener("load", (event) => this.fileReaderDidLoad(event));
      this.fileReader.addEventListener("error", (event) => this.fileReaderDidError(event));
      this.readNextChunk();
    }
    fileReaderDidLoad(event) {
      this.md5Buffer.append(event.target.result);
      if (!this.readNextChunk()) {
        const binaryDigest = this.md5Buffer.end(true);
        const base64digest = btoa(binaryDigest);
        this.callback(null, base64digest);
      }
    }
    fileReaderDidError(event) {
      this.callback(`Error reading ${this.file.name}`);
    }
    readNextChunk() {
      if (this.chunkIndex < this.chunkCount || this.chunkIndex == 0 && this.chunkCount == 0) {
        const start4 = this.chunkIndex * this.chunkSize;
        const end2 = Math.min(start4 + this.chunkSize, this.file.size);
        const bytes = fileSlice.call(this.file, start4, end2);
        this.fileReader.readAsArrayBuffer(bytes);
        this.chunkIndex++;
        return true;
      } else {
        return false;
      }
    }
  };
  function getMetaValue(name) {
    const element = findElement(document.head, `meta[name="${name}"]`);
    if (element) {
      return element.getAttribute("content");
    }
  }
  function findElements(root, selector) {
    if (typeof root == "string") {
      selector = root;
      root = document;
    }
    const elements2 = root.querySelectorAll(selector);
    return toArray(elements2);
  }
  function findElement(root, selector) {
    if (typeof root == "string") {
      selector = root;
      root = document;
    }
    return root.querySelector(selector);
  }
  function dispatchEvent2(element, type, eventInit = {}) {
    const { disabled } = element;
    const { bubbles, cancelable, detail } = eventInit;
    const event = document.createEvent("Event");
    event.initEvent(type, bubbles || true, cancelable || true);
    event.detail = detail || {};
    try {
      element.disabled = false;
      element.dispatchEvent(event);
    } finally {
      element.disabled = disabled;
    }
    return event;
  }
  function toArray(value) {
    if (Array.isArray(value)) {
      return value;
    } else if (Array.from) {
      return Array.from(value);
    } else {
      return [].slice.call(value);
    }
  }
  var BlobRecord = class {
    constructor(file, checksum, url, customHeaders = {}) {
      this.file = file;
      this.attributes = {
        filename: file.name,
        content_type: file.type || "application/octet-stream",
        byte_size: file.size,
        checksum
      };
      this.xhr = new XMLHttpRequest();
      this.xhr.open("POST", url, true);
      this.xhr.responseType = "json";
      this.xhr.setRequestHeader("Content-Type", "application/json");
      this.xhr.setRequestHeader("Accept", "application/json");
      this.xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
      Object.keys(customHeaders).forEach((headerKey) => {
        this.xhr.setRequestHeader(headerKey, customHeaders[headerKey]);
      });
      const csrfToken = getMetaValue("csrf-token");
      if (csrfToken != void 0) {
        this.xhr.setRequestHeader("X-CSRF-Token", csrfToken);
      }
      this.xhr.addEventListener("load", (event) => this.requestDidLoad(event));
      this.xhr.addEventListener("error", (event) => this.requestDidError(event));
    }
    get status() {
      return this.xhr.status;
    }
    get response() {
      const { responseType, response } = this.xhr;
      if (responseType == "json") {
        return response;
      } else {
        return JSON.parse(response);
      }
    }
    create(callback2) {
      this.callback = callback2;
      this.xhr.send(JSON.stringify({
        blob: this.attributes
      }));
    }
    requestDidLoad(event) {
      if (this.status >= 200 && this.status < 300) {
        const { response } = this;
        const { direct_upload } = response;
        delete response.direct_upload;
        this.attributes = response;
        this.directUploadData = direct_upload;
        this.callback(null, this.toJSON());
      } else {
        this.requestDidError(event);
      }
    }
    requestDidError(event) {
      this.callback(`Error creating Blob for "${this.file.name}". Status: ${this.status}`);
    }
    toJSON() {
      const result = {};
      for (const key in this.attributes) {
        result[key] = this.attributes[key];
      }
      return result;
    }
  };
  var BlobUpload = class {
    constructor(blob) {
      this.blob = blob;
      this.file = blob.file;
      const { url, headers } = blob.directUploadData;
      this.xhr = new XMLHttpRequest();
      this.xhr.open("PUT", url, true);
      this.xhr.responseType = "text";
      for (const key in headers) {
        this.xhr.setRequestHeader(key, headers[key]);
      }
      this.xhr.addEventListener("load", (event) => this.requestDidLoad(event));
      this.xhr.addEventListener("error", (event) => this.requestDidError(event));
    }
    create(callback2) {
      this.callback = callback2;
      this.xhr.send(this.file.slice());
    }
    requestDidLoad(event) {
      const { status, response } = this.xhr;
      if (status >= 200 && status < 300) {
        this.callback(null, response);
      } else {
        this.requestDidError(event);
      }
    }
    requestDidError(event) {
      this.callback(`Error storing "${this.file.name}". Status: ${this.xhr.status}`);
    }
  };
  var id = 0;
  var DirectUpload = class {
    constructor(file, url, delegate, customHeaders = {}) {
      this.id = ++id;
      this.file = file;
      this.url = url;
      this.delegate = delegate;
      this.customHeaders = customHeaders;
    }
    create(callback2) {
      FileChecksum.create(this.file, (error3, checksum) => {
        if (error3) {
          callback2(error3);
          return;
        }
        const blob = new BlobRecord(this.file, checksum, this.url, this.customHeaders);
        notify(this.delegate, "directUploadWillCreateBlobWithXHR", blob.xhr);
        blob.create((error4) => {
          if (error4) {
            callback2(error4);
          } else {
            const upload = new BlobUpload(blob);
            notify(this.delegate, "directUploadWillStoreFileWithXHR", upload.xhr);
            upload.create((error5) => {
              if (error5) {
                callback2(error5);
              } else {
                callback2(null, blob.toJSON());
              }
            });
          }
        });
      });
    }
  };
  function notify(object, methodName, ...messages) {
    if (object && typeof object[methodName] == "function") {
      return object[methodName](...messages);
    }
  }
  var DirectUploadController = class {
    constructor(input, file) {
      this.input = input;
      this.file = file;
      this.directUpload = new DirectUpload(this.file, this.url, this);
      this.dispatch("initialize");
    }
    start(callback2) {
      const hiddenInput = document.createElement("input");
      hiddenInput.type = "hidden";
      hiddenInput.name = this.input.name;
      this.input.insertAdjacentElement("beforebegin", hiddenInput);
      this.dispatch("start");
      this.directUpload.create((error3, attributes) => {
        if (error3) {
          hiddenInput.parentNode.removeChild(hiddenInput);
          this.dispatchError(error3);
        } else {
          hiddenInput.value = attributes.signed_id;
        }
        this.dispatch("end");
        callback2(error3);
      });
    }
    uploadRequestDidProgress(event) {
      const progress = event.loaded / event.total * 100;
      if (progress) {
        this.dispatch("progress", {
          progress
        });
      }
    }
    get url() {
      return this.input.getAttribute("data-direct-upload-url");
    }
    dispatch(name, detail = {}) {
      detail.file = this.file;
      detail.id = this.directUpload.id;
      return dispatchEvent2(this.input, `direct-upload:${name}`, {
        detail
      });
    }
    dispatchError(error3) {
      const event = this.dispatch("error", {
        error: error3
      });
      if (!event.defaultPrevented) {
        alert(error3);
      }
    }
    directUploadWillCreateBlobWithXHR(xhr) {
      this.dispatch("before-blob-request", {
        xhr
      });
    }
    directUploadWillStoreFileWithXHR(xhr) {
      this.dispatch("before-storage-request", {
        xhr
      });
      xhr.upload.addEventListener("progress", (event) => this.uploadRequestDidProgress(event));
    }
  };
  var inputSelector = "input[type=file][data-direct-upload-url]:not([disabled])";
  var DirectUploadsController = class {
    constructor(form) {
      this.form = form;
      this.inputs = findElements(form, inputSelector).filter((input) => input.files.length);
    }
    start(callback2) {
      const controllers2 = this.createDirectUploadControllers();
      const startNextController = () => {
        const controller = controllers2.shift();
        if (controller) {
          controller.start((error3) => {
            if (error3) {
              callback2(error3);
              this.dispatch("end");
            } else {
              startNextController();
            }
          });
        } else {
          callback2();
          this.dispatch("end");
        }
      };
      this.dispatch("start");
      startNextController();
    }
    createDirectUploadControllers() {
      const controllers2 = [];
      this.inputs.forEach((input) => {
        toArray(input.files).forEach((file) => {
          const controller = new DirectUploadController(input, file);
          controllers2.push(controller);
        });
      });
      return controllers2;
    }
    dispatch(name, detail = {}) {
      return dispatchEvent2(this.form, `direct-uploads:${name}`, {
        detail
      });
    }
  };
  var processingAttribute = "data-direct-uploads-processing";
  var submitButtonsByForm = /* @__PURE__ */ new WeakMap();
  var started = false;
  function start3() {
    if (!started) {
      started = true;
      document.addEventListener("click", didClick, true);
      document.addEventListener("submit", didSubmitForm, true);
      document.addEventListener("ajax:before", didSubmitRemoteElement);
    }
  }
  function didClick(event) {
    const button = event.target.closest("button, input");
    if (button && button.type === "submit" && button.form) {
      submitButtonsByForm.set(button.form, button);
    }
  }
  function didSubmitForm(event) {
    handleFormSubmissionEvent(event);
  }
  function didSubmitRemoteElement(event) {
    if (event.target.tagName == "FORM") {
      handleFormSubmissionEvent(event);
    }
  }
  function handleFormSubmissionEvent(event) {
    const form = event.target;
    if (form.hasAttribute(processingAttribute)) {
      event.preventDefault();
      return;
    }
    const controller = new DirectUploadsController(form);
    const { inputs } = controller;
    if (inputs.length) {
      event.preventDefault();
      form.setAttribute(processingAttribute, "");
      inputs.forEach(disable);
      controller.start((error3) => {
        form.removeAttribute(processingAttribute);
        if (error3) {
          inputs.forEach(enable);
        } else {
          submitForm(form);
        }
      });
    }
  }
  function submitForm(form) {
    let button = submitButtonsByForm.get(form) || findElement(form, "input[type=submit], button[type=submit]");
    if (button) {
      const { disabled } = button;
      button.disabled = false;
      button.focus();
      button.click();
      button.disabled = disabled;
    } else {
      button = document.createElement("input");
      button.type = "submit";
      button.style.display = "none";
      form.appendChild(button);
      button.click();
      form.removeChild(button);
    }
    submitButtonsByForm.delete(form);
  }
  function disable(input) {
    input.disabled = true;
  }
  function enable(input) {
    input.disabled = false;
  }
  function autostart() {
    if (window.ActiveStorage) {
      start3();
    }
  }
  setTimeout(autostart, 1);
  var AttachmentUpload = class {
    constructor(attachment, element) {
      this.attachment = attachment;
      this.element = element;
      this.directUpload = new DirectUpload(attachment.file, this.directUploadUrl, this);
    }
    start() {
      this.directUpload.create(this.directUploadDidComplete.bind(this));
    }
    directUploadWillStoreFileWithXHR(xhr) {
      xhr.upload.addEventListener("progress", (event) => {
        const progress = event.loaded / event.total * 100;
        this.attachment.setUploadProgress(progress);
      });
    }
    directUploadDidComplete(error3, attributes) {
      if (error3) {
        throw new Error(`Direct upload failed: ${error3}`);
      }
      this.attachment.setAttributes({
        sgid: attributes.attachable_sgid,
        url: this.createBlobUrl(attributes.signed_id, attributes.filename)
      });
    }
    createBlobUrl(signedId, filename) {
      return this.blobUrlTemplate.replace(":signed_id", signedId).replace(":filename", encodeURIComponent(filename));
    }
    get directUploadUrl() {
      return this.element.dataset.directUploadUrl;
    }
    get blobUrlTemplate() {
      return this.element.dataset.blobUrlTemplate;
    }
  };
  addEventListener("trix-attachment-add", (event) => {
    const { attachment, target } = event;
    if (attachment.file) {
      const upload = new AttachmentUpload(attachment, target);
      upload.start();
    }
  });

  // application-esbuild.js
  var import_bootstrap_datetime_picker = __toESM(require_bootstrap_datetimepicker());

  // ../../node_modules/chartkick/chart.js/chart.esm.js
  var import_chartkick = __toESM(require_chartkick());

  // ../../node_modules/chart.js/dist/chunks/helpers.segment.js
  var requestAnimFrame = function() {
    if (typeof window === "undefined") {
      return function(callback2) {
        return callback2();
      };
    }
    return window.requestAnimationFrame;
  }();
  function throttled(fn3, thisArg, updateFn) {
    const updateArgs = updateFn || ((args2) => Array.prototype.slice.call(args2));
    let ticking = false;
    let args = [];
    return function(...rest) {
      args = updateArgs(rest);
      if (!ticking) {
        ticking = true;
        requestAnimFrame.call(window, () => {
          ticking = false;
          fn3.apply(thisArg, args);
        });
      }
    };
  }
  function debounce3(fn3, delay) {
    let timeout;
    return function() {
      if (delay) {
        clearTimeout(timeout);
        timeout = setTimeout(fn3, delay);
      } else {
        fn3();
      }
      return delay;
    };
  }
  var _toLeftRightCenter = (align) => align === "start" ? "left" : align === "end" ? "right" : "center";
  var _alignStartEnd = (align, start4, end2) => align === "start" ? start4 : align === "end" ? end2 : (start4 + end2) / 2;
  var _textX = (align, left2, right2, rtl) => {
    const check = rtl ? "left" : "right";
    return align === check ? right2 : align === "center" ? (left2 + right2) / 2 : left2;
  };
  function noop2() {
  }
  var uid = function() {
    let id2 = 0;
    return function() {
      return id2++;
    };
  }();
  function isNullOrUndef(value) {
    return value === null || typeof value === "undefined";
  }
  function isArray(value) {
    if (Array.isArray && Array.isArray(value)) {
      return true;
    }
    const type = Object.prototype.toString.call(value);
    if (type.substr(0, 7) === "[object" && type.substr(-6) === "Array]") {
      return true;
    }
    return false;
  }
  function isObject(value) {
    return value !== null && Object.prototype.toString.call(value) === "[object Object]";
  }
  var isNumberFinite = (value) => (typeof value === "number" || value instanceof Number) && isFinite(+value);
  function finiteOrDefault(value, defaultValue) {
    return isNumberFinite(value) ? value : defaultValue;
  }
  function valueOrDefault(value, defaultValue) {
    return typeof value === "undefined" ? defaultValue : value;
  }
  var toPercentage = (value, dimension) => typeof value === "string" && value.endsWith("%") ? parseFloat(value) / 100 : value / dimension;
  var toDimension = (value, dimension) => typeof value === "string" && value.endsWith("%") ? parseFloat(value) / 100 * dimension : +value;
  function callback(fn3, args, thisArg) {
    if (fn3 && typeof fn3.call === "function") {
      return fn3.apply(thisArg, args);
    }
  }
  function each(loopable, fn3, thisArg, reverse) {
    let i2, len, keys;
    if (isArray(loopable)) {
      len = loopable.length;
      if (reverse) {
        for (i2 = len - 1; i2 >= 0; i2--) {
          fn3.call(thisArg, loopable[i2], i2);
        }
      } else {
        for (i2 = 0; i2 < len; i2++) {
          fn3.call(thisArg, loopable[i2], i2);
        }
      }
    } else if (isObject(loopable)) {
      keys = Object.keys(loopable);
      len = keys.length;
      for (i2 = 0; i2 < len; i2++) {
        fn3.call(thisArg, loopable[keys[i2]], keys[i2]);
      }
    }
  }
  function _elementsEqual(a0, a1) {
    let i2, ilen, v0, v1;
    if (!a0 || !a1 || a0.length !== a1.length) {
      return false;
    }
    for (i2 = 0, ilen = a0.length; i2 < ilen; ++i2) {
      v0 = a0[i2];
      v1 = a1[i2];
      if (v0.datasetIndex !== v1.datasetIndex || v0.index !== v1.index) {
        return false;
      }
    }
    return true;
  }
  function clone$1(source) {
    if (isArray(source)) {
      return source.map(clone$1);
    }
    if (isObject(source)) {
      const target = /* @__PURE__ */ Object.create(null);
      const keys = Object.keys(source);
      const klen = keys.length;
      let k2 = 0;
      for (; k2 < klen; ++k2) {
        target[keys[k2]] = clone$1(source[keys[k2]]);
      }
      return target;
    }
    return source;
  }
  function isValidKey(key) {
    return ["__proto__", "prototype", "constructor"].indexOf(key) === -1;
  }
  function _merger(key, target, source, options) {
    if (!isValidKey(key)) {
      return;
    }
    const tval = target[key];
    const sval = source[key];
    if (isObject(tval) && isObject(sval)) {
      merge(tval, sval, options);
    } else {
      target[key] = clone$1(sval);
    }
  }
  function merge(target, source, options) {
    const sources = isArray(source) ? source : [source];
    const ilen = sources.length;
    if (!isObject(target)) {
      return target;
    }
    options = options || {};
    const merger = options.merger || _merger;
    for (let i2 = 0; i2 < ilen; ++i2) {
      source = sources[i2];
      if (!isObject(source)) {
        continue;
      }
      const keys = Object.keys(source);
      for (let k2 = 0, klen = keys.length; k2 < klen; ++k2) {
        merger(keys[k2], target, source, options);
      }
    }
    return target;
  }
  function mergeIf(target, source) {
    return merge(target, source, { merger: _mergerIf });
  }
  function _mergerIf(key, target, source) {
    if (!isValidKey(key)) {
      return;
    }
    const tval = target[key];
    const sval = source[key];
    if (isObject(tval) && isObject(sval)) {
      mergeIf(tval, sval);
    } else if (!Object.prototype.hasOwnProperty.call(target, key)) {
      target[key] = clone$1(sval);
    }
  }
  var emptyString = "";
  var dot = ".";
  function indexOfDotOrLength(key, start4) {
    const idx = key.indexOf(dot, start4);
    return idx === -1 ? key.length : idx;
  }
  function resolveObjectKey(obj, key) {
    if (key === emptyString) {
      return obj;
    }
    let pos = 0;
    let idx = indexOfDotOrLength(key, pos);
    while (obj && idx > pos) {
      obj = obj[key.substr(pos, idx - pos)];
      pos = idx + 1;
      idx = indexOfDotOrLength(key, pos);
    }
    return obj;
  }
  function _capitalize(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
  }
  var defined = (value) => typeof value !== "undefined";
  var isFunction = (value) => typeof value === "function";
  var setsEqual = (a2, b2) => {
    if (a2.size !== b2.size) {
      return false;
    }
    for (const item of a2) {
      if (!b2.has(item)) {
        return false;
      }
    }
    return true;
  };
  var PI = Math.PI;
  var TAU = 2 * PI;
  var PITAU = TAU + PI;
  var INFINITY = Number.POSITIVE_INFINITY;
  var RAD_PER_DEG = PI / 180;
  var HALF_PI = PI / 2;
  var QUARTER_PI = PI / 4;
  var TWO_THIRDS_PI = PI * 2 / 3;
  var log10 = Math.log10;
  var sign = Math.sign;
  function niceNum(range) {
    const roundedRange = Math.round(range);
    range = almostEquals(range, roundedRange, range / 1e3) ? roundedRange : range;
    const niceRange = Math.pow(10, Math.floor(log10(range)));
    const fraction = range / niceRange;
    const niceFraction = fraction <= 1 ? 1 : fraction <= 2 ? 2 : fraction <= 5 ? 5 : 10;
    return niceFraction * niceRange;
  }
  function _factorize(value) {
    const result = [];
    const sqrt = Math.sqrt(value);
    let i2;
    for (i2 = 1; i2 < sqrt; i2++) {
      if (value % i2 === 0) {
        result.push(i2);
        result.push(value / i2);
      }
    }
    if (sqrt === (sqrt | 0)) {
      result.push(sqrt);
    }
    result.sort((a2, b2) => a2 - b2).pop();
    return result;
  }
  function isNumber(n2) {
    return !isNaN(parseFloat(n2)) && isFinite(n2);
  }
  function almostEquals(x2, y2, epsilon) {
    return Math.abs(x2 - y2) < epsilon;
  }
  function almostWhole(x2, epsilon) {
    const rounded = Math.round(x2);
    return rounded - epsilon <= x2 && rounded + epsilon >= x2;
  }
  function _setMinAndMaxByKey(array, target, property) {
    let i2, ilen, value;
    for (i2 = 0, ilen = array.length; i2 < ilen; i2++) {
      value = array[i2][property];
      if (!isNaN(value)) {
        target.min = Math.min(target.min, value);
        target.max = Math.max(target.max, value);
      }
    }
  }
  function toRadians(degrees) {
    return degrees * (PI / 180);
  }
  function toDegrees(radians) {
    return radians * (180 / PI);
  }
  function _decimalPlaces(x2) {
    if (!isNumberFinite(x2)) {
      return;
    }
    let e2 = 1;
    let p2 = 0;
    while (Math.round(x2 * e2) / e2 !== x2) {
      e2 *= 10;
      p2++;
    }
    return p2;
  }
  function getAngleFromPoint(centrePoint, anglePoint) {
    const distanceFromXCenter = anglePoint.x - centrePoint.x;
    const distanceFromYCenter = anglePoint.y - centrePoint.y;
    const radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);
    let angle = Math.atan2(distanceFromYCenter, distanceFromXCenter);
    if (angle < -0.5 * PI) {
      angle += TAU;
    }
    return {
      angle,
      distance: radialDistanceFromCenter
    };
  }
  function distanceBetweenPoints(pt1, pt2) {
    return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2));
  }
  function _angleDiff(a2, b2) {
    return (a2 - b2 + PITAU) % TAU - PI;
  }
  function _normalizeAngle(a2) {
    return (a2 % TAU + TAU) % TAU;
  }
  function _angleBetween(angle, start4, end2, sameAngleIsFullCircle) {
    const a2 = _normalizeAngle(angle);
    const s2 = _normalizeAngle(start4);
    const e2 = _normalizeAngle(end2);
    const angleToStart = _normalizeAngle(s2 - a2);
    const angleToEnd = _normalizeAngle(e2 - a2);
    const startToAngle = _normalizeAngle(a2 - s2);
    const endToAngle = _normalizeAngle(a2 - e2);
    return a2 === s2 || a2 === e2 || sameAngleIsFullCircle && s2 === e2 || angleToStart > angleToEnd && startToAngle < endToAngle;
  }
  function _limitValue(value, min2, max2) {
    return Math.max(min2, Math.min(max2, value));
  }
  function _int16Range(value) {
    return _limitValue(value, -32768, 32767);
  }
  var atEdge = (t2) => t2 === 0 || t2 === 1;
  var elasticIn = (t2, s2, p2) => -(Math.pow(2, 10 * (t2 -= 1)) * Math.sin((t2 - s2) * TAU / p2));
  var elasticOut = (t2, s2, p2) => Math.pow(2, -10 * t2) * Math.sin((t2 - s2) * TAU / p2) + 1;
  var effects = {
    linear: (t2) => t2,
    easeInQuad: (t2) => t2 * t2,
    easeOutQuad: (t2) => -t2 * (t2 - 2),
    easeInOutQuad: (t2) => (t2 /= 0.5) < 1 ? 0.5 * t2 * t2 : -0.5 * (--t2 * (t2 - 2) - 1),
    easeInCubic: (t2) => t2 * t2 * t2,
    easeOutCubic: (t2) => (t2 -= 1) * t2 * t2 + 1,
    easeInOutCubic: (t2) => (t2 /= 0.5) < 1 ? 0.5 * t2 * t2 * t2 : 0.5 * ((t2 -= 2) * t2 * t2 + 2),
    easeInQuart: (t2) => t2 * t2 * t2 * t2,
    easeOutQuart: (t2) => -((t2 -= 1) * t2 * t2 * t2 - 1),
    easeInOutQuart: (t2) => (t2 /= 0.5) < 1 ? 0.5 * t2 * t2 * t2 * t2 : -0.5 * ((t2 -= 2) * t2 * t2 * t2 - 2),
    easeInQuint: (t2) => t2 * t2 * t2 * t2 * t2,
    easeOutQuint: (t2) => (t2 -= 1) * t2 * t2 * t2 * t2 + 1,
    easeInOutQuint: (t2) => (t2 /= 0.5) < 1 ? 0.5 * t2 * t2 * t2 * t2 * t2 : 0.5 * ((t2 -= 2) * t2 * t2 * t2 * t2 + 2),
    easeInSine: (t2) => -Math.cos(t2 * HALF_PI) + 1,
    easeOutSine: (t2) => Math.sin(t2 * HALF_PI),
    easeInOutSine: (t2) => -0.5 * (Math.cos(PI * t2) - 1),
    easeInExpo: (t2) => t2 === 0 ? 0 : Math.pow(2, 10 * (t2 - 1)),
    easeOutExpo: (t2) => t2 === 1 ? 1 : -Math.pow(2, -10 * t2) + 1,
    easeInOutExpo: (t2) => atEdge(t2) ? t2 : t2 < 0.5 ? 0.5 * Math.pow(2, 10 * (t2 * 2 - 1)) : 0.5 * (-Math.pow(2, -10 * (t2 * 2 - 1)) + 2),
    easeInCirc: (t2) => t2 >= 1 ? t2 : -(Math.sqrt(1 - t2 * t2) - 1),
    easeOutCirc: (t2) => Math.sqrt(1 - (t2 -= 1) * t2),
    easeInOutCirc: (t2) => (t2 /= 0.5) < 1 ? -0.5 * (Math.sqrt(1 - t2 * t2) - 1) : 0.5 * (Math.sqrt(1 - (t2 -= 2) * t2) + 1),
    easeInElastic: (t2) => atEdge(t2) ? t2 : elasticIn(t2, 0.075, 0.3),
    easeOutElastic: (t2) => atEdge(t2) ? t2 : elasticOut(t2, 0.075, 0.3),
    easeInOutElastic(t2) {
      const s2 = 0.1125;
      const p2 = 0.45;
      return atEdge(t2) ? t2 : t2 < 0.5 ? 0.5 * elasticIn(t2 * 2, s2, p2) : 0.5 + 0.5 * elasticOut(t2 * 2 - 1, s2, p2);
    },
    easeInBack(t2) {
      const s2 = 1.70158;
      return t2 * t2 * ((s2 + 1) * t2 - s2);
    },
    easeOutBack(t2) {
      const s2 = 1.70158;
      return (t2 -= 1) * t2 * ((s2 + 1) * t2 + s2) + 1;
    },
    easeInOutBack(t2) {
      let s2 = 1.70158;
      if ((t2 /= 0.5) < 1) {
        return 0.5 * (t2 * t2 * (((s2 *= 1.525) + 1) * t2 - s2));
      }
      return 0.5 * ((t2 -= 2) * t2 * (((s2 *= 1.525) + 1) * t2 + s2) + 2);
    },
    easeInBounce: (t2) => 1 - effects.easeOutBounce(1 - t2),
    easeOutBounce(t2) {
      const m2 = 7.5625;
      const d2 = 2.75;
      if (t2 < 1 / d2) {
        return m2 * t2 * t2;
      }
      if (t2 < 2 / d2) {
        return m2 * (t2 -= 1.5 / d2) * t2 + 0.75;
      }
      if (t2 < 2.5 / d2) {
        return m2 * (t2 -= 2.25 / d2) * t2 + 0.9375;
      }
      return m2 * (t2 -= 2.625 / d2) * t2 + 0.984375;
    },
    easeInOutBounce: (t2) => t2 < 0.5 ? effects.easeInBounce(t2 * 2) * 0.5 : effects.easeOutBounce(t2 * 2 - 1) * 0.5 + 0.5
  };
  var map = { 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, A: 10, B: 11, C: 12, D: 13, E: 14, F: 15, a: 10, b: 11, c: 12, d: 13, e: 14, f: 15 };
  var hex = "0123456789ABCDEF";
  var h1 = (b2) => hex[b2 & 15];
  var h2 = (b2) => hex[(b2 & 240) >> 4] + hex[b2 & 15];
  var eq = (b2) => (b2 & 240) >> 4 === (b2 & 15);
  function isShort(v2) {
    return eq(v2.r) && eq(v2.g) && eq(v2.b) && eq(v2.a);
  }
  function hexParse(str) {
    var len = str.length;
    var ret;
    if (str[0] === "#") {
      if (len === 4 || len === 5) {
        ret = {
          r: 255 & map[str[1]] * 17,
          g: 255 & map[str[2]] * 17,
          b: 255 & map[str[3]] * 17,
          a: len === 5 ? map[str[4]] * 17 : 255
        };
      } else if (len === 7 || len === 9) {
        ret = {
          r: map[str[1]] << 4 | map[str[2]],
          g: map[str[3]] << 4 | map[str[4]],
          b: map[str[5]] << 4 | map[str[6]],
          a: len === 9 ? map[str[7]] << 4 | map[str[8]] : 255
        };
      }
    }
    return ret;
  }
  function hexString(v2) {
    var f2 = isShort(v2) ? h1 : h2;
    return v2 ? "#" + f2(v2.r) + f2(v2.g) + f2(v2.b) + (v2.a < 255 ? f2(v2.a) : "") : v2;
  }
  function round2(v2) {
    return v2 + 0.5 | 0;
  }
  var lim = (v2, l2, h3) => Math.max(Math.min(v2, h3), l2);
  function p2b(v2) {
    return lim(round2(v2 * 2.55), 0, 255);
  }
  function n2b(v2) {
    return lim(round2(v2 * 255), 0, 255);
  }
  function b2n(v2) {
    return lim(round2(v2 / 2.55) / 100, 0, 1);
  }
  function n2p(v2) {
    return lim(round2(v2 * 100), 0, 100);
  }
  var RGB_RE = /^rgba?\(\s*([-+.\d]+)(%)?[\s,]+([-+.e\d]+)(%)?[\s,]+([-+.e\d]+)(%)?(?:[\s,/]+([-+.e\d]+)(%)?)?\s*\)$/;
  function rgbParse(str) {
    const m2 = RGB_RE.exec(str);
    let a2 = 255;
    let r2, g2, b2;
    if (!m2) {
      return;
    }
    if (m2[7] !== r2) {
      const v2 = +m2[7];
      a2 = 255 & (m2[8] ? p2b(v2) : v2 * 255);
    }
    r2 = +m2[1];
    g2 = +m2[3];
    b2 = +m2[5];
    r2 = 255 & (m2[2] ? p2b(r2) : r2);
    g2 = 255 & (m2[4] ? p2b(g2) : g2);
    b2 = 255 & (m2[6] ? p2b(b2) : b2);
    return {
      r: r2,
      g: g2,
      b: b2,
      a: a2
    };
  }
  function rgbString(v2) {
    return v2 && (v2.a < 255 ? `rgba(${v2.r}, ${v2.g}, ${v2.b}, ${b2n(v2.a)})` : `rgb(${v2.r}, ${v2.g}, ${v2.b})`);
  }
  var HUE_RE = /^(hsla?|hwb|hsv)\(\s*([-+.e\d]+)(?:deg)?[\s,]+([-+.e\d]+)%[\s,]+([-+.e\d]+)%(?:[\s,]+([-+.e\d]+)(%)?)?\s*\)$/;
  function hsl2rgbn(h3, s2, l2) {
    const a2 = s2 * Math.min(l2, 1 - l2);
    const f2 = (n2, k2 = (n2 + h3 / 30) % 12) => l2 - a2 * Math.max(Math.min(k2 - 3, 9 - k2, 1), -1);
    return [f2(0), f2(8), f2(4)];
  }
  function hsv2rgbn(h3, s2, v2) {
    const f2 = (n2, k2 = (n2 + h3 / 60) % 6) => v2 - v2 * s2 * Math.max(Math.min(k2, 4 - k2, 1), 0);
    return [f2(5), f2(3), f2(1)];
  }
  function hwb2rgbn(h3, w2, b2) {
    const rgb = hsl2rgbn(h3, 1, 0.5);
    let i2;
    if (w2 + b2 > 1) {
      i2 = 1 / (w2 + b2);
      w2 *= i2;
      b2 *= i2;
    }
    for (i2 = 0; i2 < 3; i2++) {
      rgb[i2] *= 1 - w2 - b2;
      rgb[i2] += w2;
    }
    return rgb;
  }
  function rgb2hsl(v2) {
    const range = 255;
    const r2 = v2.r / range;
    const g2 = v2.g / range;
    const b2 = v2.b / range;
    const max2 = Math.max(r2, g2, b2);
    const min2 = Math.min(r2, g2, b2);
    const l2 = (max2 + min2) / 2;
    let h3, s2, d2;
    if (max2 !== min2) {
      d2 = max2 - min2;
      s2 = l2 > 0.5 ? d2 / (2 - max2 - min2) : d2 / (max2 + min2);
      h3 = max2 === r2 ? (g2 - b2) / d2 + (g2 < b2 ? 6 : 0) : max2 === g2 ? (b2 - r2) / d2 + 2 : (r2 - g2) / d2 + 4;
      h3 = h3 * 60 + 0.5;
    }
    return [h3 | 0, s2 || 0, l2];
  }
  function calln(f2, a2, b2, c2) {
    return (Array.isArray(a2) ? f2(a2[0], a2[1], a2[2]) : f2(a2, b2, c2)).map(n2b);
  }
  function hsl2rgb(h3, s2, l2) {
    return calln(hsl2rgbn, h3, s2, l2);
  }
  function hwb2rgb(h3, w2, b2) {
    return calln(hwb2rgbn, h3, w2, b2);
  }
  function hsv2rgb(h3, s2, v2) {
    return calln(hsv2rgbn, h3, s2, v2);
  }
  function hue(h3) {
    return (h3 % 360 + 360) % 360;
  }
  function hueParse(str) {
    const m2 = HUE_RE.exec(str);
    let a2 = 255;
    let v2;
    if (!m2) {
      return;
    }
    if (m2[5] !== v2) {
      a2 = m2[6] ? p2b(+m2[5]) : n2b(+m2[5]);
    }
    const h3 = hue(+m2[2]);
    const p1 = +m2[3] / 100;
    const p2 = +m2[4] / 100;
    if (m2[1] === "hwb") {
      v2 = hwb2rgb(h3, p1, p2);
    } else if (m2[1] === "hsv") {
      v2 = hsv2rgb(h3, p1, p2);
    } else {
      v2 = hsl2rgb(h3, p1, p2);
    }
    return {
      r: v2[0],
      g: v2[1],
      b: v2[2],
      a: a2
    };
  }
  function rotate(v2, deg) {
    var h3 = rgb2hsl(v2);
    h3[0] = hue(h3[0] + deg);
    h3 = hsl2rgb(h3);
    v2.r = h3[0];
    v2.g = h3[1];
    v2.b = h3[2];
  }
  function hslString(v2) {
    if (!v2) {
      return;
    }
    const a2 = rgb2hsl(v2);
    const h3 = a2[0];
    const s2 = n2p(a2[1]);
    const l2 = n2p(a2[2]);
    return v2.a < 255 ? `hsla(${h3}, ${s2}%, ${l2}%, ${b2n(v2.a)})` : `hsl(${h3}, ${s2}%, ${l2}%)`;
  }
  var map$1 = {
    x: "dark",
    Z: "light",
    Y: "re",
    X: "blu",
    W: "gr",
    V: "medium",
    U: "slate",
    A: "ee",
    T: "ol",
    S: "or",
    B: "ra",
    C: "lateg",
    D: "ights",
    R: "in",
    Q: "turquois",
    E: "hi",
    P: "ro",
    O: "al",
    N: "le",
    M: "de",
    L: "yello",
    F: "en",
    K: "ch",
    G: "arks",
    H: "ea",
    I: "ightg",
    J: "wh"
  };
  var names = {
    OiceXe: "f0f8ff",
    antiquewEte: "faebd7",
    aqua: "ffff",
    aquamarRe: "7fffd4",
    azuY: "f0ffff",
    beige: "f5f5dc",
    bisque: "ffe4c4",
    black: "0",
    blanKedOmond: "ffebcd",
    Xe: "ff",
    XeviTet: "8a2be2",
    bPwn: "a52a2a",
    burlywood: "deb887",
    caMtXe: "5f9ea0",
    KartYuse: "7fff00",
    KocTate: "d2691e",
    cSO: "ff7f50",
    cSnflowerXe: "6495ed",
    cSnsilk: "fff8dc",
    crimson: "dc143c",
    cyan: "ffff",
    xXe: "8b",
    xcyan: "8b8b",
    xgTMnPd: "b8860b",
    xWay: "a9a9a9",
    xgYF: "6400",
    xgYy: "a9a9a9",
    xkhaki: "bdb76b",
    xmagFta: "8b008b",
    xTivegYF: "556b2f",
    xSange: "ff8c00",
    xScEd: "9932cc",
    xYd: "8b0000",
    xsOmon: "e9967a",
    xsHgYF: "8fbc8f",
    xUXe: "483d8b",
    xUWay: "2f4f4f",
    xUgYy: "2f4f4f",
    xQe: "ced1",
    xviTet: "9400d3",
    dAppRk: "ff1493",
    dApskyXe: "bfff",
    dimWay: "696969",
    dimgYy: "696969",
    dodgerXe: "1e90ff",
    fiYbrick: "b22222",
    flSOwEte: "fffaf0",
    foYstWAn: "228b22",
    fuKsia: "ff00ff",
    gaRsbSo: "dcdcdc",
    ghostwEte: "f8f8ff",
    gTd: "ffd700",
    gTMnPd: "daa520",
    Way: "808080",
    gYF: "8000",
    gYFLw: "adff2f",
    gYy: "808080",
    honeyMw: "f0fff0",
    hotpRk: "ff69b4",
    RdianYd: "cd5c5c",
    Rdigo: "4b0082",
    ivSy: "fffff0",
    khaki: "f0e68c",
    lavFMr: "e6e6fa",
    lavFMrXsh: "fff0f5",
    lawngYF: "7cfc00",
    NmoncEffon: "fffacd",
    ZXe: "add8e6",
    ZcSO: "f08080",
    Zcyan: "e0ffff",
    ZgTMnPdLw: "fafad2",
    ZWay: "d3d3d3",
    ZgYF: "90ee90",
    ZgYy: "d3d3d3",
    ZpRk: "ffb6c1",
    ZsOmon: "ffa07a",
    ZsHgYF: "20b2aa",
    ZskyXe: "87cefa",
    ZUWay: "778899",
    ZUgYy: "778899",
    ZstAlXe: "b0c4de",
    ZLw: "ffffe0",
    lime: "ff00",
    limegYF: "32cd32",
    lRF: "faf0e6",
    magFta: "ff00ff",
    maPon: "800000",
    VaquamarRe: "66cdaa",
    VXe: "cd",
    VScEd: "ba55d3",
    VpurpN: "9370db",
    VsHgYF: "3cb371",
    VUXe: "7b68ee",
    VsprRggYF: "fa9a",
    VQe: "48d1cc",
    VviTetYd: "c71585",
    midnightXe: "191970",
    mRtcYam: "f5fffa",
    mistyPse: "ffe4e1",
    moccasR: "ffe4b5",
    navajowEte: "ffdead",
    navy: "80",
    Tdlace: "fdf5e6",
    Tive: "808000",
    TivedBb: "6b8e23",
    Sange: "ffa500",
    SangeYd: "ff4500",
    ScEd: "da70d6",
    pOegTMnPd: "eee8aa",
    pOegYF: "98fb98",
    pOeQe: "afeeee",
    pOeviTetYd: "db7093",
    papayawEp: "ffefd5",
    pHKpuff: "ffdab9",
    peru: "cd853f",
    pRk: "ffc0cb",
    plum: "dda0dd",
    powMrXe: "b0e0e6",
    purpN: "800080",
    YbeccapurpN: "663399",
    Yd: "ff0000",
    Psybrown: "bc8f8f",
    PyOXe: "4169e1",
    saddNbPwn: "8b4513",
    sOmon: "fa8072",
    sandybPwn: "f4a460",
    sHgYF: "2e8b57",
    sHshell: "fff5ee",
    siFna: "a0522d",
    silver: "c0c0c0",
    skyXe: "87ceeb",
    UXe: "6a5acd",
    UWay: "708090",
    UgYy: "708090",
    snow: "fffafa",
    sprRggYF: "ff7f",
    stAlXe: "4682b4",
    tan: "d2b48c",
    teO: "8080",
    tEstN: "d8bfd8",
    tomato: "ff6347",
    Qe: "40e0d0",
    viTet: "ee82ee",
    JHt: "f5deb3",
    wEte: "ffffff",
    wEtesmoke: "f5f5f5",
    Lw: "ffff00",
    LwgYF: "9acd32"
  };
  function unpack() {
    const unpacked = {};
    const keys = Object.keys(names);
    const tkeys = Object.keys(map$1);
    let i2, j2, k2, ok, nk;
    for (i2 = 0; i2 < keys.length; i2++) {
      ok = nk = keys[i2];
      for (j2 = 0; j2 < tkeys.length; j2++) {
        k2 = tkeys[j2];
        nk = nk.replace(k2, map$1[k2]);
      }
      k2 = parseInt(names[ok], 16);
      unpacked[nk] = [k2 >> 16 & 255, k2 >> 8 & 255, k2 & 255];
    }
    return unpacked;
  }
  var names$1;
  function nameParse(str) {
    if (!names$1) {
      names$1 = unpack();
      names$1.transparent = [0, 0, 0, 0];
    }
    const a2 = names$1[str.toLowerCase()];
    return a2 && {
      r: a2[0],
      g: a2[1],
      b: a2[2],
      a: a2.length === 4 ? a2[3] : 255
    };
  }
  function modHSL(v2, i2, ratio) {
    if (v2) {
      let tmp = rgb2hsl(v2);
      tmp[i2] = Math.max(0, Math.min(tmp[i2] + tmp[i2] * ratio, i2 === 0 ? 360 : 1));
      tmp = hsl2rgb(tmp);
      v2.r = tmp[0];
      v2.g = tmp[1];
      v2.b = tmp[2];
    }
  }
  function clone(v2, proto) {
    return v2 ? Object.assign(proto || {}, v2) : v2;
  }
  function fromObject(input) {
    var v2 = { r: 0, g: 0, b: 0, a: 255 };
    if (Array.isArray(input)) {
      if (input.length >= 3) {
        v2 = { r: input[0], g: input[1], b: input[2], a: 255 };
        if (input.length > 3) {
          v2.a = n2b(input[3]);
        }
      }
    } else {
      v2 = clone(input, { r: 0, g: 0, b: 0, a: 1 });
      v2.a = n2b(v2.a);
    }
    return v2;
  }
  function functionParse(str) {
    if (str.charAt(0) === "r") {
      return rgbParse(str);
    }
    return hueParse(str);
  }
  var Color = class {
    constructor(input) {
      if (input instanceof Color) {
        return input;
      }
      const type = typeof input;
      let v2;
      if (type === "object") {
        v2 = fromObject(input);
      } else if (type === "string") {
        v2 = hexParse(input) || nameParse(input) || functionParse(input);
      }
      this._rgb = v2;
      this._valid = !!v2;
    }
    get valid() {
      return this._valid;
    }
    get rgb() {
      var v2 = clone(this._rgb);
      if (v2) {
        v2.a = b2n(v2.a);
      }
      return v2;
    }
    set rgb(obj) {
      this._rgb = fromObject(obj);
    }
    rgbString() {
      return this._valid ? rgbString(this._rgb) : this._rgb;
    }
    hexString() {
      return this._valid ? hexString(this._rgb) : this._rgb;
    }
    hslString() {
      return this._valid ? hslString(this._rgb) : this._rgb;
    }
    mix(color2, weight) {
      const me2 = this;
      if (color2) {
        const c1 = me2.rgb;
        const c2 = color2.rgb;
        let w2;
        const p2 = weight === w2 ? 0.5 : weight;
        const w3 = 2 * p2 - 1;
        const a2 = c1.a - c2.a;
        const w1 = ((w3 * a2 === -1 ? w3 : (w3 + a2) / (1 + w3 * a2)) + 1) / 2;
        w2 = 1 - w1;
        c1.r = 255 & w1 * c1.r + w2 * c2.r + 0.5;
        c1.g = 255 & w1 * c1.g + w2 * c2.g + 0.5;
        c1.b = 255 & w1 * c1.b + w2 * c2.b + 0.5;
        c1.a = p2 * c1.a + (1 - p2) * c2.a;
        me2.rgb = c1;
      }
      return me2;
    }
    clone() {
      return new Color(this.rgb);
    }
    alpha(a2) {
      this._rgb.a = n2b(a2);
      return this;
    }
    clearer(ratio) {
      const rgb = this._rgb;
      rgb.a *= 1 - ratio;
      return this;
    }
    greyscale() {
      const rgb = this._rgb;
      const val = round2(rgb.r * 0.3 + rgb.g * 0.59 + rgb.b * 0.11);
      rgb.r = rgb.g = rgb.b = val;
      return this;
    }
    opaquer(ratio) {
      const rgb = this._rgb;
      rgb.a *= 1 + ratio;
      return this;
    }
    negate() {
      const v2 = this._rgb;
      v2.r = 255 - v2.r;
      v2.g = 255 - v2.g;
      v2.b = 255 - v2.b;
      return this;
    }
    lighten(ratio) {
      modHSL(this._rgb, 2, ratio);
      return this;
    }
    darken(ratio) {
      modHSL(this._rgb, 2, -ratio);
      return this;
    }
    saturate(ratio) {
      modHSL(this._rgb, 1, ratio);
      return this;
    }
    desaturate(ratio) {
      modHSL(this._rgb, 1, -ratio);
      return this;
    }
    rotate(deg) {
      rotate(this._rgb, deg);
      return this;
    }
  };
  function index_esm(input) {
    return new Color(input);
  }
  var isPatternOrGradient = (value) => value instanceof CanvasGradient || value instanceof CanvasPattern;
  function color(value) {
    return isPatternOrGradient(value) ? value : index_esm(value);
  }
  function getHoverColor(value) {
    return isPatternOrGradient(value) ? value : index_esm(value).saturate(0.5).darken(0.1).hexString();
  }
  var overrides = /* @__PURE__ */ Object.create(null);
  var descriptors = /* @__PURE__ */ Object.create(null);
  function getScope$1(node, key) {
    if (!key) {
      return node;
    }
    const keys = key.split(".");
    for (let i2 = 0, n2 = keys.length; i2 < n2; ++i2) {
      const k2 = keys[i2];
      node = node[k2] || (node[k2] = /* @__PURE__ */ Object.create(null));
    }
    return node;
  }
  function set(root, scope, values) {
    if (typeof scope === "string") {
      return merge(getScope$1(root, scope), values);
    }
    return merge(getScope$1(root, ""), scope);
  }
  var Defaults = class {
    constructor(_descriptors2) {
      this.animation = void 0;
      this.backgroundColor = "rgba(0,0,0,0.1)";
      this.borderColor = "rgba(0,0,0,0.1)";
      this.color = "#666";
      this.datasets = {};
      this.devicePixelRatio = (context) => context.chart.platform.getDevicePixelRatio();
      this.elements = {};
      this.events = [
        "mousemove",
        "mouseout",
        "click",
        "touchstart",
        "touchmove"
      ];
      this.font = {
        family: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
        size: 12,
        style: "normal",
        lineHeight: 1.2,
        weight: null
      };
      this.hover = {};
      this.hoverBackgroundColor = (ctx, options) => getHoverColor(options.backgroundColor);
      this.hoverBorderColor = (ctx, options) => getHoverColor(options.borderColor);
      this.hoverColor = (ctx, options) => getHoverColor(options.color);
      this.indexAxis = "x";
      this.interaction = {
        mode: "nearest",
        intersect: true
      };
      this.maintainAspectRatio = true;
      this.onHover = null;
      this.onClick = null;
      this.parsing = true;
      this.plugins = {};
      this.responsive = true;
      this.scale = void 0;
      this.scales = {};
      this.showLine = true;
      this.describe(_descriptors2);
    }
    set(scope, values) {
      return set(this, scope, values);
    }
    get(scope) {
      return getScope$1(this, scope);
    }
    describe(scope, values) {
      return set(descriptors, scope, values);
    }
    override(scope, values) {
      return set(overrides, scope, values);
    }
    route(scope, name, targetScope, targetName) {
      const scopeObject = getScope$1(this, scope);
      const targetScopeObject = getScope$1(this, targetScope);
      const privateName = "_" + name;
      Object.defineProperties(scopeObject, {
        [privateName]: {
          value: scopeObject[name],
          writable: true
        },
        [name]: {
          enumerable: true,
          get() {
            const local = this[privateName];
            const target = targetScopeObject[targetName];
            if (isObject(local)) {
              return Object.assign({}, target, local);
            }
            return valueOrDefault(local, target);
          },
          set(value) {
            this[privateName] = value;
          }
        }
      });
    }
  };
  var defaults = new Defaults({
    _scriptable: (name) => !name.startsWith("on"),
    _indexable: (name) => name !== "events",
    hover: {
      _fallback: "interaction"
    },
    interaction: {
      _scriptable: false,
      _indexable: false
    }
  });
  function toFontString(font) {
    if (!font || isNullOrUndef(font.size) || isNullOrUndef(font.family)) {
      return null;
    }
    return (font.style ? font.style + " " : "") + (font.weight ? font.weight + " " : "") + font.size + "px " + font.family;
  }
  function _measureText(ctx, data, gc, longest, string) {
    let textWidth = data[string];
    if (!textWidth) {
      textWidth = data[string] = ctx.measureText(string).width;
      gc.push(string);
    }
    if (textWidth > longest) {
      longest = textWidth;
    }
    return longest;
  }
  function _longestText(ctx, font, arrayOfThings, cache2) {
    cache2 = cache2 || {};
    let data = cache2.data = cache2.data || {};
    let gc = cache2.garbageCollect = cache2.garbageCollect || [];
    if (cache2.font !== font) {
      data = cache2.data = {};
      gc = cache2.garbageCollect = [];
      cache2.font = font;
    }
    ctx.save();
    ctx.font = font;
    let longest = 0;
    const ilen = arrayOfThings.length;
    let i2, j2, jlen, thing, nestedThing;
    for (i2 = 0; i2 < ilen; i2++) {
      thing = arrayOfThings[i2];
      if (thing !== void 0 && thing !== null && isArray(thing) !== true) {
        longest = _measureText(ctx, data, gc, longest, thing);
      } else if (isArray(thing)) {
        for (j2 = 0, jlen = thing.length; j2 < jlen; j2++) {
          nestedThing = thing[j2];
          if (nestedThing !== void 0 && nestedThing !== null && !isArray(nestedThing)) {
            longest = _measureText(ctx, data, gc, longest, nestedThing);
          }
        }
      }
    }
    ctx.restore();
    const gcLen = gc.length / 2;
    if (gcLen > arrayOfThings.length) {
      for (i2 = 0; i2 < gcLen; i2++) {
        delete data[gc[i2]];
      }
      gc.splice(0, gcLen);
    }
    return longest;
  }
  function _alignPixel(chart, pixel, width) {
    const devicePixelRatio = chart.currentDevicePixelRatio;
    const halfWidth = width !== 0 ? Math.max(width / 2, 0.5) : 0;
    return Math.round((pixel - halfWidth) * devicePixelRatio) / devicePixelRatio + halfWidth;
  }
  function clearCanvas(canvas, ctx) {
    ctx = ctx || canvas.getContext("2d");
    ctx.save();
    ctx.resetTransform();
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.restore();
  }
  function drawPoint(ctx, options, x2, y2) {
    let type, xOffset, yOffset, size, cornerRadius;
    const style = options.pointStyle;
    const rotation = options.rotation;
    const radius = options.radius;
    let rad = (rotation || 0) * RAD_PER_DEG;
    if (style && typeof style === "object") {
      type = style.toString();
      if (type === "[object HTMLImageElement]" || type === "[object HTMLCanvasElement]") {
        ctx.save();
        ctx.translate(x2, y2);
        ctx.rotate(rad);
        ctx.drawImage(style, -style.width / 2, -style.height / 2, style.width, style.height);
        ctx.restore();
        return;
      }
    }
    if (isNaN(radius) || radius <= 0) {
      return;
    }
    ctx.beginPath();
    switch (style) {
      default:
        ctx.arc(x2, y2, radius, 0, TAU);
        ctx.closePath();
        break;
      case "triangle":
        ctx.moveTo(x2 + Math.sin(rad) * radius, y2 - Math.cos(rad) * radius);
        rad += TWO_THIRDS_PI;
        ctx.lineTo(x2 + Math.sin(rad) * radius, y2 - Math.cos(rad) * radius);
        rad += TWO_THIRDS_PI;
        ctx.lineTo(x2 + Math.sin(rad) * radius, y2 - Math.cos(rad) * radius);
        ctx.closePath();
        break;
      case "rectRounded":
        cornerRadius = radius * 0.516;
        size = radius - cornerRadius;
        xOffset = Math.cos(rad + QUARTER_PI) * size;
        yOffset = Math.sin(rad + QUARTER_PI) * size;
        ctx.arc(x2 - xOffset, y2 - yOffset, cornerRadius, rad - PI, rad - HALF_PI);
        ctx.arc(x2 + yOffset, y2 - xOffset, cornerRadius, rad - HALF_PI, rad);
        ctx.arc(x2 + xOffset, y2 + yOffset, cornerRadius, rad, rad + HALF_PI);
        ctx.arc(x2 - yOffset, y2 + xOffset, cornerRadius, rad + HALF_PI, rad + PI);
        ctx.closePath();
        break;
      case "rect":
        if (!rotation) {
          size = Math.SQRT1_2 * radius;
          ctx.rect(x2 - size, y2 - size, 2 * size, 2 * size);
          break;
        }
        rad += QUARTER_PI;
      case "rectRot":
        xOffset = Math.cos(rad) * radius;
        yOffset = Math.sin(rad) * radius;
        ctx.moveTo(x2 - xOffset, y2 - yOffset);
        ctx.lineTo(x2 + yOffset, y2 - xOffset);
        ctx.lineTo(x2 + xOffset, y2 + yOffset);
        ctx.lineTo(x2 - yOffset, y2 + xOffset);
        ctx.closePath();
        break;
      case "crossRot":
        rad += QUARTER_PI;
      case "cross":
        xOffset = Math.cos(rad) * radius;
        yOffset = Math.sin(rad) * radius;
        ctx.moveTo(x2 - xOffset, y2 - yOffset);
        ctx.lineTo(x2 + xOffset, y2 + yOffset);
        ctx.moveTo(x2 + yOffset, y2 - xOffset);
        ctx.lineTo(x2 - yOffset, y2 + xOffset);
        break;
      case "star":
        xOffset = Math.cos(rad) * radius;
        yOffset = Math.sin(rad) * radius;
        ctx.moveTo(x2 - xOffset, y2 - yOffset);
        ctx.lineTo(x2 + xOffset, y2 + yOffset);
        ctx.moveTo(x2 + yOffset, y2 - xOffset);
        ctx.lineTo(x2 - yOffset, y2 + xOffset);
        rad += QUARTER_PI;
        xOffset = Math.cos(rad) * radius;
        yOffset = Math.sin(rad) * radius;
        ctx.moveTo(x2 - xOffset, y2 - yOffset);
        ctx.lineTo(x2 + xOffset, y2 + yOffset);
        ctx.moveTo(x2 + yOffset, y2 - xOffset);
        ctx.lineTo(x2 - yOffset, y2 + xOffset);
        break;
      case "line":
        xOffset = Math.cos(rad) * radius;
        yOffset = Math.sin(rad) * radius;
        ctx.moveTo(x2 - xOffset, y2 - yOffset);
        ctx.lineTo(x2 + xOffset, y2 + yOffset);
        break;
      case "dash":
        ctx.moveTo(x2, y2);
        ctx.lineTo(x2 + Math.cos(rad) * radius, y2 + Math.sin(rad) * radius);
        break;
    }
    ctx.fill();
    if (options.borderWidth > 0) {
      ctx.stroke();
    }
  }
  function _isPointInArea(point, area, margin) {
    margin = margin || 0.5;
    return point && area && point.x > area.left - margin && point.x < area.right + margin && point.y > area.top - margin && point.y < area.bottom + margin;
  }
  function clipArea(ctx, area) {
    ctx.save();
    ctx.beginPath();
    ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top);
    ctx.clip();
  }
  function unclipArea(ctx) {
    ctx.restore();
  }
  function _steppedLineTo(ctx, previous, target, flip2, mode) {
    if (!previous) {
      return ctx.lineTo(target.x, target.y);
    }
    if (mode === "middle") {
      const midpoint = (previous.x + target.x) / 2;
      ctx.lineTo(midpoint, previous.y);
      ctx.lineTo(midpoint, target.y);
    } else if (mode === "after" !== !!flip2) {
      ctx.lineTo(previous.x, target.y);
    } else {
      ctx.lineTo(target.x, previous.y);
    }
    ctx.lineTo(target.x, target.y);
  }
  function _bezierCurveTo(ctx, previous, target, flip2) {
    if (!previous) {
      return ctx.lineTo(target.x, target.y);
    }
    ctx.bezierCurveTo(flip2 ? previous.cp1x : previous.cp2x, flip2 ? previous.cp1y : previous.cp2y, flip2 ? target.cp2x : target.cp1x, flip2 ? target.cp2y : target.cp1y, target.x, target.y);
  }
  function renderText(ctx, text, x2, y2, font, opts = {}) {
    const lines = isArray(text) ? text : [text];
    const stroke = opts.strokeWidth > 0 && opts.strokeColor !== "";
    let i2, line;
    ctx.save();
    ctx.font = font.string;
    setRenderOpts(ctx, opts);
    for (i2 = 0; i2 < lines.length; ++i2) {
      line = lines[i2];
      if (stroke) {
        if (opts.strokeColor) {
          ctx.strokeStyle = opts.strokeColor;
        }
        if (!isNullOrUndef(opts.strokeWidth)) {
          ctx.lineWidth = opts.strokeWidth;
        }
        ctx.strokeText(line, x2, y2, opts.maxWidth);
      }
      ctx.fillText(line, x2, y2, opts.maxWidth);
      decorateText(ctx, x2, y2, line, opts);
      y2 += font.lineHeight;
    }
    ctx.restore();
  }
  function setRenderOpts(ctx, opts) {
    if (opts.translation) {
      ctx.translate(opts.translation[0], opts.translation[1]);
    }
    if (!isNullOrUndef(opts.rotation)) {
      ctx.rotate(opts.rotation);
    }
    if (opts.color) {
      ctx.fillStyle = opts.color;
    }
    if (opts.textAlign) {
      ctx.textAlign = opts.textAlign;
    }
    if (opts.textBaseline) {
      ctx.textBaseline = opts.textBaseline;
    }
  }
  function decorateText(ctx, x2, y2, line, opts) {
    if (opts.strikethrough || opts.underline) {
      const metrics = ctx.measureText(line);
      const left2 = x2 - metrics.actualBoundingBoxLeft;
      const right2 = x2 + metrics.actualBoundingBoxRight;
      const top2 = y2 - metrics.actualBoundingBoxAscent;
      const bottom2 = y2 + metrics.actualBoundingBoxDescent;
      const yDecoration = opts.strikethrough ? (top2 + bottom2) / 2 : bottom2;
      ctx.strokeStyle = ctx.fillStyle;
      ctx.beginPath();
      ctx.lineWidth = opts.decorationWidth || 2;
      ctx.moveTo(left2, yDecoration);
      ctx.lineTo(right2, yDecoration);
      ctx.stroke();
    }
  }
  function addRoundedRectPath(ctx, rect) {
    const { x: x2, y: y2, w: w2, h: h3, radius } = rect;
    ctx.arc(x2 + radius.topLeft, y2 + radius.topLeft, radius.topLeft, -HALF_PI, PI, true);
    ctx.lineTo(x2, y2 + h3 - radius.bottomLeft);
    ctx.arc(x2 + radius.bottomLeft, y2 + h3 - radius.bottomLeft, radius.bottomLeft, PI, HALF_PI, true);
    ctx.lineTo(x2 + w2 - radius.bottomRight, y2 + h3);
    ctx.arc(x2 + w2 - radius.bottomRight, y2 + h3 - radius.bottomRight, radius.bottomRight, HALF_PI, 0, true);
    ctx.lineTo(x2 + w2, y2 + radius.topRight);
    ctx.arc(x2 + w2 - radius.topRight, y2 + radius.topRight, radius.topRight, 0, -HALF_PI, true);
    ctx.lineTo(x2 + radius.topLeft, y2);
  }
  var LINE_HEIGHT = new RegExp(/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/);
  var FONT_STYLE = new RegExp(/^(normal|italic|initial|inherit|unset|(oblique( -?[0-9]?[0-9]deg)?))$/);
  function toLineHeight(value, size) {
    const matches = ("" + value).match(LINE_HEIGHT);
    if (!matches || matches[1] === "normal") {
      return size * 1.2;
    }
    value = +matches[2];
    switch (matches[3]) {
      case "px":
        return value;
      case "%":
        value /= 100;
        break;
    }
    return size * value;
  }
  var numberOrZero = (v2) => +v2 || 0;
  function _readValueToProps(value, props) {
    const ret = {};
    const objProps = isObject(props);
    const keys = objProps ? Object.keys(props) : props;
    const read2 = isObject(value) ? objProps ? (prop) => valueOrDefault(value[prop], value[props[prop]]) : (prop) => value[prop] : () => value;
    for (const prop of keys) {
      ret[prop] = numberOrZero(read2(prop));
    }
    return ret;
  }
  function toTRBL(value) {
    return _readValueToProps(value, { top: "y", right: "x", bottom: "y", left: "x" });
  }
  function toTRBLCorners(value) {
    return _readValueToProps(value, ["topLeft", "topRight", "bottomLeft", "bottomRight"]);
  }
  function toPadding(value) {
    const obj = toTRBL(value);
    obj.width = obj.left + obj.right;
    obj.height = obj.top + obj.bottom;
    return obj;
  }
  function toFont(options, fallback) {
    options = options || {};
    fallback = fallback || defaults.font;
    let size = valueOrDefault(options.size, fallback.size);
    if (typeof size === "string") {
      size = parseInt(size, 10);
    }
    let style = valueOrDefault(options.style, fallback.style);
    if (style && !("" + style).match(FONT_STYLE)) {
      console.warn('Invalid font style specified: "' + style + '"');
      style = "";
    }
    const font = {
      family: valueOrDefault(options.family, fallback.family),
      lineHeight: toLineHeight(valueOrDefault(options.lineHeight, fallback.lineHeight), size),
      size,
      style,
      weight: valueOrDefault(options.weight, fallback.weight),
      string: ""
    };
    font.string = toFontString(font);
    return font;
  }
  function resolve(inputs, context, index, info) {
    let cacheable = true;
    let i2, ilen, value;
    for (i2 = 0, ilen = inputs.length; i2 < ilen; ++i2) {
      value = inputs[i2];
      if (value === void 0) {
        continue;
      }
      if (context !== void 0 && typeof value === "function") {
        value = value(context);
        cacheable = false;
      }
      if (index !== void 0 && isArray(value)) {
        value = value[index % value.length];
        cacheable = false;
      }
      if (value !== void 0) {
        if (info && !cacheable) {
          info.cacheable = false;
        }
        return value;
      }
    }
  }
  function _addGrace(minmax, grace) {
    const { min: min2, max: max2 } = minmax;
    return {
      min: min2 - Math.abs(toDimension(grace, min2)),
      max: max2 + toDimension(grace, max2)
    };
  }
  function _lookup(table, value, cmp) {
    cmp = cmp || ((index) => table[index] < value);
    let hi2 = table.length - 1;
    let lo = 0;
    let mid;
    while (hi2 - lo > 1) {
      mid = lo + hi2 >> 1;
      if (cmp(mid)) {
        lo = mid;
      } else {
        hi2 = mid;
      }
    }
    return { lo, hi: hi2 };
  }
  var _lookupByKey = (table, key, value) => _lookup(table, value, (index) => table[index][key] < value);
  var _rlookupByKey = (table, key, value) => _lookup(table, value, (index) => table[index][key] >= value);
  function _filterBetween(values, min2, max2) {
    let start4 = 0;
    let end2 = values.length;
    while (start4 < end2 && values[start4] < min2) {
      start4++;
    }
    while (end2 > start4 && values[end2 - 1] > max2) {
      end2--;
    }
    return start4 > 0 || end2 < values.length ? values.slice(start4, end2) : values;
  }
  var arrayEvents = ["push", "pop", "shift", "splice", "unshift"];
  function listenArrayEvents(array, listener) {
    if (array._chartjs) {
      array._chartjs.listeners.push(listener);
      return;
    }
    Object.defineProperty(array, "_chartjs", {
      configurable: true,
      enumerable: false,
      value: {
        listeners: [listener]
      }
    });
    arrayEvents.forEach((key) => {
      const method = "_onData" + _capitalize(key);
      const base = array[key];
      Object.defineProperty(array, key, {
        configurable: true,
        enumerable: false,
        value(...args) {
          const res = base.apply(this, args);
          array._chartjs.listeners.forEach((object) => {
            if (typeof object[method] === "function") {
              object[method](...args);
            }
          });
          return res;
        }
      });
    });
  }
  function unlistenArrayEvents(array, listener) {
    const stub = array._chartjs;
    if (!stub) {
      return;
    }
    const listeners = stub.listeners;
    const index = listeners.indexOf(listener);
    if (index !== -1) {
      listeners.splice(index, 1);
    }
    if (listeners.length > 0) {
      return;
    }
    arrayEvents.forEach((key) => {
      delete array[key];
    });
    delete array._chartjs;
  }
  function _arrayUnique(items) {
    const set2 = /* @__PURE__ */ new Set();
    let i2, ilen;
    for (i2 = 0, ilen = items.length; i2 < ilen; ++i2) {
      set2.add(items[i2]);
    }
    if (set2.size === ilen) {
      return items;
    }
    return Array.from(set2);
  }
  function _createResolver(scopes, prefixes = [""], rootScopes = scopes, fallback, getTarget2 = () => scopes[0]) {
    if (!defined(fallback)) {
      fallback = _resolve("_fallback", scopes);
    }
    const cache2 = {
      [Symbol.toStringTag]: "Object",
      _cacheable: true,
      _scopes: scopes,
      _rootScopes: rootScopes,
      _fallback: fallback,
      _getTarget: getTarget2,
      override: (scope) => _createResolver([scope, ...scopes], prefixes, rootScopes, fallback)
    };
    return new Proxy(cache2, {
      deleteProperty(target, prop) {
        delete target[prop];
        delete target._keys;
        delete scopes[0][prop];
        return true;
      },
      get(target, prop) {
        return _cached(target, prop, () => _resolveWithPrefixes(prop, prefixes, scopes, target));
      },
      getOwnPropertyDescriptor(target, prop) {
        return Reflect.getOwnPropertyDescriptor(target._scopes[0], prop);
      },
      getPrototypeOf() {
        return Reflect.getPrototypeOf(scopes[0]);
      },
      has(target, prop) {
        return getKeysFromAllScopes(target).includes(prop);
      },
      ownKeys(target) {
        return getKeysFromAllScopes(target);
      },
      set(target, prop, value) {
        const storage = target._storage || (target._storage = getTarget2());
        storage[prop] = value;
        delete target[prop];
        delete target._keys;
        return true;
      }
    });
  }
  function _attachContext(proxy, context, subProxy, descriptorDefaults) {
    const cache2 = {
      _cacheable: false,
      _proxy: proxy,
      _context: context,
      _subProxy: subProxy,
      _stack: /* @__PURE__ */ new Set(),
      _descriptors: _descriptors(proxy, descriptorDefaults),
      setContext: (ctx) => _attachContext(proxy, ctx, subProxy, descriptorDefaults),
      override: (scope) => _attachContext(proxy.override(scope), context, subProxy, descriptorDefaults)
    };
    return new Proxy(cache2, {
      deleteProperty(target, prop) {
        delete target[prop];
        delete proxy[prop];
        return true;
      },
      get(target, prop, receiver) {
        return _cached(target, prop, () => _resolveWithContext(target, prop, receiver));
      },
      getOwnPropertyDescriptor(target, prop) {
        return target._descriptors.allKeys ? Reflect.has(proxy, prop) ? { enumerable: true, configurable: true } : void 0 : Reflect.getOwnPropertyDescriptor(proxy, prop);
      },
      getPrototypeOf() {
        return Reflect.getPrototypeOf(proxy);
      },
      has(target, prop) {
        return Reflect.has(proxy, prop);
      },
      ownKeys() {
        return Reflect.ownKeys(proxy);
      },
      set(target, prop, value) {
        proxy[prop] = value;
        delete target[prop];
        return true;
      }
    });
  }
  function _descriptors(proxy, defaults2 = { scriptable: true, indexable: true }) {
    const { _scriptable = defaults2.scriptable, _indexable = defaults2.indexable, _allKeys = defaults2.allKeys } = proxy;
    return {
      allKeys: _allKeys,
      scriptable: _scriptable,
      indexable: _indexable,
      isScriptable: isFunction(_scriptable) ? _scriptable : () => _scriptable,
      isIndexable: isFunction(_indexable) ? _indexable : () => _indexable
    };
  }
  var readKey = (prefix, name) => prefix ? prefix + _capitalize(name) : name;
  var needsSubResolver = (prop, value) => isObject(value) && prop !== "adapters";
  function _cached(target, prop, resolve2) {
    let value = target[prop];
    if (defined(value)) {
      return value;
    }
    value = resolve2();
    if (defined(value)) {
      target[prop] = value;
    }
    return value;
  }
  function _resolveWithContext(target, prop, receiver) {
    const { _proxy, _context, _subProxy, _descriptors: descriptors2 } = target;
    let value = _proxy[prop];
    if (isFunction(value) && descriptors2.isScriptable(prop)) {
      value = _resolveScriptable(prop, value, target, receiver);
    }
    if (isArray(value) && value.length) {
      value = _resolveArray(prop, value, target, descriptors2.isIndexable);
    }
    if (needsSubResolver(prop, value)) {
      value = _attachContext(value, _context, _subProxy && _subProxy[prop], descriptors2);
    }
    return value;
  }
  function _resolveScriptable(prop, value, target, receiver) {
    const { _proxy, _context, _subProxy, _stack } = target;
    if (_stack.has(prop)) {
      throw new Error("Recursion detected: " + Array.from(_stack).join("->") + "->" + prop);
    }
    _stack.add(prop);
    value = value(_context, _subProxy || receiver);
    _stack.delete(prop);
    if (isObject(value)) {
      value = createSubResolver(_proxy._scopes, _proxy, prop, value);
    }
    return value;
  }
  function _resolveArray(prop, value, target, isIndexable) {
    const { _proxy, _context, _subProxy, _descriptors: descriptors2 } = target;
    if (defined(_context.index) && isIndexable(prop)) {
      value = value[_context.index % value.length];
    } else if (isObject(value[0])) {
      const arr = value;
      const scopes = _proxy._scopes.filter((s2) => s2 !== arr);
      value = [];
      for (const item of arr) {
        const resolver = createSubResolver(scopes, _proxy, prop, item);
        value.push(_attachContext(resolver, _context, _subProxy && _subProxy[prop], descriptors2));
      }
    }
    return value;
  }
  function resolveFallback(fallback, prop, value) {
    return isFunction(fallback) ? fallback(prop, value) : fallback;
  }
  var getScope = (key, parent) => key === true ? parent : typeof key === "string" ? resolveObjectKey(parent, key) : void 0;
  function addScopes(set2, parentScopes, key, parentFallback) {
    for (const parent of parentScopes) {
      const scope = getScope(key, parent);
      if (scope) {
        set2.add(scope);
        const fallback = resolveFallback(scope._fallback, key, scope);
        if (defined(fallback) && fallback !== key && fallback !== parentFallback) {
          return fallback;
        }
      } else if (scope === false && defined(parentFallback) && key !== parentFallback) {
        return null;
      }
    }
    return false;
  }
  function createSubResolver(parentScopes, resolver, prop, value) {
    const rootScopes = resolver._rootScopes;
    const fallback = resolveFallback(resolver._fallback, prop, value);
    const allScopes = [...parentScopes, ...rootScopes];
    const set2 = /* @__PURE__ */ new Set();
    set2.add(value);
    let key = addScopesFromKey(set2, allScopes, prop, fallback || prop);
    if (key === null) {
      return false;
    }
    if (defined(fallback) && fallback !== prop) {
      key = addScopesFromKey(set2, allScopes, fallback, key);
      if (key === null) {
        return false;
      }
    }
    return _createResolver(Array.from(set2), [""], rootScopes, fallback, () => subGetTarget(resolver, prop, value));
  }
  function addScopesFromKey(set2, allScopes, key, fallback) {
    while (key) {
      key = addScopes(set2, allScopes, key, fallback);
    }
    return key;
  }
  function subGetTarget(resolver, prop, value) {
    const parent = resolver._getTarget();
    if (!(prop in parent)) {
      parent[prop] = {};
    }
    const target = parent[prop];
    if (isArray(target) && isObject(value)) {
      return value;
    }
    return target;
  }
  function _resolveWithPrefixes(prop, prefixes, scopes, proxy) {
    let value;
    for (const prefix of prefixes) {
      value = _resolve(readKey(prefix, prop), scopes);
      if (defined(value)) {
        return needsSubResolver(prop, value) ? createSubResolver(scopes, proxy, prop, value) : value;
      }
    }
  }
  function _resolve(key, scopes) {
    for (const scope of scopes) {
      if (!scope) {
        continue;
      }
      const value = scope[key];
      if (defined(value)) {
        return value;
      }
    }
  }
  function getKeysFromAllScopes(target) {
    let keys = target._keys;
    if (!keys) {
      keys = target._keys = resolveKeysFromAllScopes(target._scopes);
    }
    return keys;
  }
  function resolveKeysFromAllScopes(scopes) {
    const set2 = /* @__PURE__ */ new Set();
    for (const scope of scopes) {
      for (const key of Object.keys(scope).filter((k2) => !k2.startsWith("_"))) {
        set2.add(key);
      }
    }
    return Array.from(set2);
  }
  var EPSILON = Number.EPSILON || 1e-14;
  var getPoint = (points, i2) => i2 < points.length && !points[i2].skip && points[i2];
  var getValueAxis = (indexAxis) => indexAxis === "x" ? "y" : "x";
  function splineCurve(firstPoint, middlePoint, afterPoint, t2) {
    const previous = firstPoint.skip ? middlePoint : firstPoint;
    const current = middlePoint;
    const next = afterPoint.skip ? middlePoint : afterPoint;
    const d01 = distanceBetweenPoints(current, previous);
    const d12 = distanceBetweenPoints(next, current);
    let s01 = d01 / (d01 + d12);
    let s12 = d12 / (d01 + d12);
    s01 = isNaN(s01) ? 0 : s01;
    s12 = isNaN(s12) ? 0 : s12;
    const fa = t2 * s01;
    const fb = t2 * s12;
    return {
      previous: {
        x: current.x - fa * (next.x - previous.x),
        y: current.y - fa * (next.y - previous.y)
      },
      next: {
        x: current.x + fb * (next.x - previous.x),
        y: current.y + fb * (next.y - previous.y)
      }
    };
  }
  function monotoneAdjust(points, deltaK, mK) {
    const pointsLen = points.length;
    let alphaK, betaK, tauK, squaredMagnitude, pointCurrent;
    let pointAfter = getPoint(points, 0);
    for (let i2 = 0; i2 < pointsLen - 1; ++i2) {
      pointCurrent = pointAfter;
      pointAfter = getPoint(points, i2 + 1);
      if (!pointCurrent || !pointAfter) {
        continue;
      }
      if (almostEquals(deltaK[i2], 0, EPSILON)) {
        mK[i2] = mK[i2 + 1] = 0;
        continue;
      }
      alphaK = mK[i2] / deltaK[i2];
      betaK = mK[i2 + 1] / deltaK[i2];
      squaredMagnitude = Math.pow(alphaK, 2) + Math.pow(betaK, 2);
      if (squaredMagnitude <= 9) {
        continue;
      }
      tauK = 3 / Math.sqrt(squaredMagnitude);
      mK[i2] = alphaK * tauK * deltaK[i2];
      mK[i2 + 1] = betaK * tauK * deltaK[i2];
    }
  }
  function monotoneCompute(points, mK, indexAxis = "x") {
    const valueAxis = getValueAxis(indexAxis);
    const pointsLen = points.length;
    let delta, pointBefore, pointCurrent;
    let pointAfter = getPoint(points, 0);
    for (let i2 = 0; i2 < pointsLen; ++i2) {
      pointBefore = pointCurrent;
      pointCurrent = pointAfter;
      pointAfter = getPoint(points, i2 + 1);
      if (!pointCurrent) {
        continue;
      }
      const iPixel = pointCurrent[indexAxis];
      const vPixel = pointCurrent[valueAxis];
      if (pointBefore) {
        delta = (iPixel - pointBefore[indexAxis]) / 3;
        pointCurrent[`cp1${indexAxis}`] = iPixel - delta;
        pointCurrent[`cp1${valueAxis}`] = vPixel - delta * mK[i2];
      }
      if (pointAfter) {
        delta = (pointAfter[indexAxis] - iPixel) / 3;
        pointCurrent[`cp2${indexAxis}`] = iPixel + delta;
        pointCurrent[`cp2${valueAxis}`] = vPixel + delta * mK[i2];
      }
    }
  }
  function splineCurveMonotone(points, indexAxis = "x") {
    const valueAxis = getValueAxis(indexAxis);
    const pointsLen = points.length;
    const deltaK = Array(pointsLen).fill(0);
    const mK = Array(pointsLen);
    let i2, pointBefore, pointCurrent;
    let pointAfter = getPoint(points, 0);
    for (i2 = 0; i2 < pointsLen; ++i2) {
      pointBefore = pointCurrent;
      pointCurrent = pointAfter;
      pointAfter = getPoint(points, i2 + 1);
      if (!pointCurrent) {
        continue;
      }
      if (pointAfter) {
        const slopeDelta = pointAfter[indexAxis] - pointCurrent[indexAxis];
        deltaK[i2] = slopeDelta !== 0 ? (pointAfter[valueAxis] - pointCurrent[valueAxis]) / slopeDelta : 0;
      }
      mK[i2] = !pointBefore ? deltaK[i2] : !pointAfter ? deltaK[i2 - 1] : sign(deltaK[i2 - 1]) !== sign(deltaK[i2]) ? 0 : (deltaK[i2 - 1] + deltaK[i2]) / 2;
    }
    monotoneAdjust(points, deltaK, mK);
    monotoneCompute(points, mK, indexAxis);
  }
  function capControlPoint(pt2, min2, max2) {
    return Math.max(Math.min(pt2, max2), min2);
  }
  function capBezierPoints(points, area) {
    let i2, ilen, point, inArea, inAreaPrev;
    let inAreaNext = _isPointInArea(points[0], area);
    for (i2 = 0, ilen = points.length; i2 < ilen; ++i2) {
      inAreaPrev = inArea;
      inArea = inAreaNext;
      inAreaNext = i2 < ilen - 1 && _isPointInArea(points[i2 + 1], area);
      if (!inArea) {
        continue;
      }
      point = points[i2];
      if (inAreaPrev) {
        point.cp1x = capControlPoint(point.cp1x, area.left, area.right);
        point.cp1y = capControlPoint(point.cp1y, area.top, area.bottom);
      }
      if (inAreaNext) {
        point.cp2x = capControlPoint(point.cp2x, area.left, area.right);
        point.cp2y = capControlPoint(point.cp2y, area.top, area.bottom);
      }
    }
  }
  function _updateBezierControlPoints(points, options, area, loop, indexAxis) {
    let i2, ilen, point, controlPoints;
    if (options.spanGaps) {
      points = points.filter((pt2) => !pt2.skip);
    }
    if (options.cubicInterpolationMode === "monotone") {
      splineCurveMonotone(points, indexAxis);
    } else {
      let prev = loop ? points[points.length - 1] : points[0];
      for (i2 = 0, ilen = points.length; i2 < ilen; ++i2) {
        point = points[i2];
        controlPoints = splineCurve(prev, point, points[Math.min(i2 + 1, ilen - (loop ? 0 : 1)) % ilen], options.tension);
        point.cp1x = controlPoints.previous.x;
        point.cp1y = controlPoints.previous.y;
        point.cp2x = controlPoints.next.x;
        point.cp2y = controlPoints.next.y;
        prev = point;
      }
    }
    if (options.capBezierPoints) {
      capBezierPoints(points, area);
    }
  }
  function _isDomSupported() {
    return typeof window !== "undefined" && typeof document !== "undefined";
  }
  function _getParentNode(domNode) {
    let parent = domNode.parentNode;
    if (parent && parent.toString() === "[object ShadowRoot]") {
      parent = parent.host;
    }
    return parent;
  }
  function parseMaxStyle(styleValue, node, parentProperty) {
    let valueInPixels;
    if (typeof styleValue === "string") {
      valueInPixels = parseInt(styleValue, 10);
      if (styleValue.indexOf("%") !== -1) {
        valueInPixels = valueInPixels / 100 * node.parentNode[parentProperty];
      }
    } else {
      valueInPixels = styleValue;
    }
    return valueInPixels;
  }
  var getComputedStyle3 = (element) => window.getComputedStyle(element, null);
  function getStyle(el, property) {
    return getComputedStyle3(el).getPropertyValue(property);
  }
  var positions = ["top", "right", "bottom", "left"];
  function getPositionedStyle(styles, style, suffix) {
    const result = {};
    suffix = suffix ? "-" + suffix : "";
    for (let i2 = 0; i2 < 4; i2++) {
      const pos = positions[i2];
      result[pos] = parseFloat(styles[style + "-" + pos + suffix]) || 0;
    }
    result.width = result.left + result.right;
    result.height = result.top + result.bottom;
    return result;
  }
  var useOffsetPos = (x2, y2, target) => (x2 > 0 || y2 > 0) && (!target || !target.shadowRoot);
  function getCanvasPosition(evt, canvas) {
    const e2 = evt.native || evt;
    const touches = e2.touches;
    const source = touches && touches.length ? touches[0] : e2;
    const { offsetX, offsetY } = source;
    let box = false;
    let x2, y2;
    if (useOffsetPos(offsetX, offsetY, e2.target)) {
      x2 = offsetX;
      y2 = offsetY;
    } else {
      const rect = canvas.getBoundingClientRect();
      x2 = source.clientX - rect.left;
      y2 = source.clientY - rect.top;
      box = true;
    }
    return { x: x2, y: y2, box };
  }
  function getRelativePosition(evt, chart) {
    const { canvas, currentDevicePixelRatio } = chart;
    const style = getComputedStyle3(canvas);
    const borderBox = style.boxSizing === "border-box";
    const paddings = getPositionedStyle(style, "padding");
    const borders = getPositionedStyle(style, "border", "width");
    const { x: x2, y: y2, box } = getCanvasPosition(evt, canvas);
    const xOffset = paddings.left + (box && borders.left);
    const yOffset = paddings.top + (box && borders.top);
    let { width, height } = chart;
    if (borderBox) {
      width -= paddings.width + borders.width;
      height -= paddings.height + borders.height;
    }
    return {
      x: Math.round((x2 - xOffset) / width * canvas.width / currentDevicePixelRatio),
      y: Math.round((y2 - yOffset) / height * canvas.height / currentDevicePixelRatio)
    };
  }
  function getContainerSize(canvas, width, height) {
    let maxWidth, maxHeight;
    if (width === void 0 || height === void 0) {
      const container = _getParentNode(canvas);
      if (!container) {
        width = canvas.clientWidth;
        height = canvas.clientHeight;
      } else {
        const rect = container.getBoundingClientRect();
        const containerStyle = getComputedStyle3(container);
        const containerBorder = getPositionedStyle(containerStyle, "border", "width");
        const containerPadding = getPositionedStyle(containerStyle, "padding");
        width = rect.width - containerPadding.width - containerBorder.width;
        height = rect.height - containerPadding.height - containerBorder.height;
        maxWidth = parseMaxStyle(containerStyle.maxWidth, container, "clientWidth");
        maxHeight = parseMaxStyle(containerStyle.maxHeight, container, "clientHeight");
      }
    }
    return {
      width,
      height,
      maxWidth: maxWidth || INFINITY,
      maxHeight: maxHeight || INFINITY
    };
  }
  var round1 = (v2) => Math.round(v2 * 10) / 10;
  function getMaximumSize(canvas, bbWidth, bbHeight, aspectRatio) {
    const style = getComputedStyle3(canvas);
    const margins = getPositionedStyle(style, "margin");
    const maxWidth = parseMaxStyle(style.maxWidth, canvas, "clientWidth") || INFINITY;
    const maxHeight = parseMaxStyle(style.maxHeight, canvas, "clientHeight") || INFINITY;
    const containerSize = getContainerSize(canvas, bbWidth, bbHeight);
    let { width, height } = containerSize;
    if (style.boxSizing === "content-box") {
      const borders = getPositionedStyle(style, "border", "width");
      const paddings = getPositionedStyle(style, "padding");
      width -= paddings.width + borders.width;
      height -= paddings.height + borders.height;
    }
    width = Math.max(0, width - margins.width);
    height = Math.max(0, aspectRatio ? Math.floor(width / aspectRatio) : height - margins.height);
    width = round1(Math.min(width, maxWidth, containerSize.maxWidth));
    height = round1(Math.min(height, maxHeight, containerSize.maxHeight));
    if (width && !height) {
      height = round1(width / 2);
    }
    return {
      width,
      height
    };
  }
  function retinaScale(chart, forceRatio, forceStyle) {
    const pixelRatio = forceRatio || 1;
    const deviceHeight = Math.floor(chart.height * pixelRatio);
    const deviceWidth = Math.floor(chart.width * pixelRatio);
    chart.height = deviceHeight / pixelRatio;
    chart.width = deviceWidth / pixelRatio;
    const canvas = chart.canvas;
    if (canvas.style && (forceStyle || !canvas.style.height && !canvas.style.width)) {
      canvas.style.height = `${chart.height}px`;
      canvas.style.width = `${chart.width}px`;
    }
    if (chart.currentDevicePixelRatio !== pixelRatio || canvas.height !== deviceHeight || canvas.width !== deviceWidth) {
      chart.currentDevicePixelRatio = pixelRatio;
      canvas.height = deviceHeight;
      canvas.width = deviceWidth;
      chart.ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);
      return true;
    }
    return false;
  }
  var supportsEventListenerOptions = function() {
    let passiveSupported = false;
    try {
      const options = {
        get passive() {
          passiveSupported = true;
          return false;
        }
      };
      window.addEventListener("test", null, options);
      window.removeEventListener("test", null, options);
    } catch (e2) {
    }
    return passiveSupported;
  }();
  function readUsedSize(element, property) {
    const value = getStyle(element, property);
    const matches = value && value.match(/^(\d+)(\.\d+)?px$/);
    return matches ? +matches[1] : void 0;
  }
  function _pointInLine(p1, p2, t2, mode) {
    return {
      x: p1.x + t2 * (p2.x - p1.x),
      y: p1.y + t2 * (p2.y - p1.y)
    };
  }
  function _steppedInterpolation(p1, p2, t2, mode) {
    return {
      x: p1.x + t2 * (p2.x - p1.x),
      y: mode === "middle" ? t2 < 0.5 ? p1.y : p2.y : mode === "after" ? t2 < 1 ? p1.y : p2.y : t2 > 0 ? p2.y : p1.y
    };
  }
  function _bezierInterpolation(p1, p2, t2, mode) {
    const cp1 = { x: p1.cp2x, y: p1.cp2y };
    const cp2 = { x: p2.cp1x, y: p2.cp1y };
    const a2 = _pointInLine(p1, cp1, t2);
    const b2 = _pointInLine(cp1, cp2, t2);
    const c2 = _pointInLine(cp2, p2, t2);
    const d2 = _pointInLine(a2, b2, t2);
    const e2 = _pointInLine(b2, c2, t2);
    return _pointInLine(d2, e2, t2);
  }
  var intlCache = /* @__PURE__ */ new Map();
  function getNumberFormat(locale2, options) {
    options = options || {};
    const cacheKey = locale2 + JSON.stringify(options);
    let formatter = intlCache.get(cacheKey);
    if (!formatter) {
      formatter = new Intl.NumberFormat(locale2, options);
      intlCache.set(cacheKey, formatter);
    }
    return formatter;
  }
  function formatNumber(num, locale2, options) {
    return getNumberFormat(locale2, options).format(num);
  }
  var getRightToLeftAdapter = function(rectX, width) {
    return {
      x(x2) {
        return rectX + rectX + width - x2;
      },
      setWidth(w2) {
        width = w2;
      },
      textAlign(align) {
        if (align === "center") {
          return align;
        }
        return align === "right" ? "left" : "right";
      },
      xPlus(x2, value) {
        return x2 - value;
      },
      leftForLtr(x2, itemWidth) {
        return x2 - itemWidth;
      }
    };
  };
  var getLeftToRightAdapter = function() {
    return {
      x(x2) {
        return x2;
      },
      setWidth(w2) {
      },
      textAlign(align) {
        return align;
      },
      xPlus(x2, value) {
        return x2 + value;
      },
      leftForLtr(x2, _itemWidth) {
        return x2;
      }
    };
  };
  function getRtlAdapter(rtl, rectX, width) {
    return rtl ? getRightToLeftAdapter(rectX, width) : getLeftToRightAdapter();
  }
  function overrideTextDirection(ctx, direction) {
    let style, original;
    if (direction === "ltr" || direction === "rtl") {
      style = ctx.canvas.style;
      original = [
        style.getPropertyValue("direction"),
        style.getPropertyPriority("direction")
      ];
      style.setProperty("direction", direction, "important");
      ctx.prevTextDirection = original;
    }
  }
  function restoreTextDirection(ctx, original) {
    if (original !== void 0) {
      delete ctx.prevTextDirection;
      ctx.canvas.style.setProperty("direction", original[0], original[1]);
    }
  }
  function propertyFn(property) {
    if (property === "angle") {
      return {
        between: _angleBetween,
        compare: _angleDiff,
        normalize: _normalizeAngle
      };
    }
    return {
      between: (n2, s2, e2) => n2 >= Math.min(s2, e2) && n2 <= Math.max(e2, s2),
      compare: (a2, b2) => a2 - b2,
      normalize: (x2) => x2
    };
  }
  function normalizeSegment({ start: start4, end: end2, count, loop, style }) {
    return {
      start: start4 % count,
      end: end2 % count,
      loop: loop && (end2 - start4 + 1) % count === 0,
      style
    };
  }
  function getSegment(segment, points, bounds) {
    const { property, start: startBound, end: endBound } = bounds;
    const { between, normalize } = propertyFn(property);
    const count = points.length;
    let { start: start4, end: end2, loop } = segment;
    let i2, ilen;
    if (loop) {
      start4 += count;
      end2 += count;
      for (i2 = 0, ilen = count; i2 < ilen; ++i2) {
        if (!between(normalize(points[start4 % count][property]), startBound, endBound)) {
          break;
        }
        start4--;
        end2--;
      }
      start4 %= count;
      end2 %= count;
    }
    if (end2 < start4) {
      end2 += count;
    }
    return { start: start4, end: end2, loop, style: segment.style };
  }
  function _boundSegment(segment, points, bounds) {
    if (!bounds) {
      return [segment];
    }
    const { property, start: startBound, end: endBound } = bounds;
    const count = points.length;
    const { compare, between, normalize } = propertyFn(property);
    const { start: start4, end: end2, loop, style } = getSegment(segment, points, bounds);
    const result = [];
    let inside = false;
    let subStart = null;
    let value, point, prevValue;
    const startIsBefore = () => between(startBound, prevValue, value) && compare(startBound, prevValue) !== 0;
    const endIsBefore = () => compare(endBound, value) === 0 || between(endBound, prevValue, value);
    const shouldStart = () => inside || startIsBefore();
    const shouldStop = () => !inside || endIsBefore();
    for (let i2 = start4, prev = start4; i2 <= end2; ++i2) {
      point = points[i2 % count];
      if (point.skip) {
        continue;
      }
      value = normalize(point[property]);
      if (value === prevValue) {
        continue;
      }
      inside = between(value, startBound, endBound);
      if (subStart === null && shouldStart()) {
        subStart = compare(value, startBound) === 0 ? i2 : prev;
      }
      if (subStart !== null && shouldStop()) {
        result.push(normalizeSegment({ start: subStart, end: i2, loop, count, style }));
        subStart = null;
      }
      prev = i2;
      prevValue = value;
    }
    if (subStart !== null) {
      result.push(normalizeSegment({ start: subStart, end: end2, loop, count, style }));
    }
    return result;
  }
  function _boundSegments(line, bounds) {
    const result = [];
    const segments = line.segments;
    for (let i2 = 0; i2 < segments.length; i2++) {
      const sub = _boundSegment(segments[i2], line.points, bounds);
      if (sub.length) {
        result.push(...sub);
      }
    }
    return result;
  }
  function findStartAndEnd(points, count, loop, spanGaps) {
    let start4 = 0;
    let end2 = count - 1;
    if (loop && !spanGaps) {
      while (start4 < count && !points[start4].skip) {
        start4++;
      }
    }
    while (start4 < count && points[start4].skip) {
      start4++;
    }
    start4 %= count;
    if (loop) {
      end2 += start4;
    }
    while (end2 > start4 && points[end2 % count].skip) {
      end2--;
    }
    end2 %= count;
    return { start: start4, end: end2 };
  }
  function solidSegments(points, start4, max2, loop) {
    const count = points.length;
    const result = [];
    let last = start4;
    let prev = points[start4];
    let end2;
    for (end2 = start4 + 1; end2 <= max2; ++end2) {
      const cur = points[end2 % count];
      if (cur.skip || cur.stop) {
        if (!prev.skip) {
          loop = false;
          result.push({ start: start4 % count, end: (end2 - 1) % count, loop });
          start4 = last = cur.stop ? end2 : null;
        }
      } else {
        last = end2;
        if (prev.skip) {
          start4 = end2;
        }
      }
      prev = cur;
    }
    if (last !== null) {
      result.push({ start: start4 % count, end: last % count, loop });
    }
    return result;
  }
  function _computeSegments(line, segmentOptions) {
    const points = line.points;
    const spanGaps = line.options.spanGaps;
    const count = points.length;
    if (!count) {
      return [];
    }
    const loop = !!line._loop;
    const { start: start4, end: end2 } = findStartAndEnd(points, count, loop, spanGaps);
    if (spanGaps === true) {
      return splitByStyles(line, [{ start: start4, end: end2, loop }], points, segmentOptions);
    }
    const max2 = end2 < start4 ? end2 + count : end2;
    const completeLoop = !!line._fullLoop && start4 === 0 && end2 === count - 1;
    return splitByStyles(line, solidSegments(points, start4, max2, completeLoop), points, segmentOptions);
  }
  function splitByStyles(line, segments, points, segmentOptions) {
    if (!segmentOptions || !segmentOptions.setContext || !points) {
      return segments;
    }
    return doSplitByStyles(line, segments, points, segmentOptions);
  }
  function doSplitByStyles(line, segments, points, segmentOptions) {
    const baseStyle = readStyle(line.options);
    const count = points.length;
    const result = [];
    let start4 = segments[0].start;
    let i2 = start4;
    for (const segment of segments) {
      let prevStyle = baseStyle;
      let prev = points[start4 % count];
      let style;
      for (i2 = start4 + 1; i2 <= segment.end; i2++) {
        const pt2 = points[i2 % count];
        style = readStyle(segmentOptions.setContext({
          type: "segment",
          p0: prev,
          p1: pt2,
          p0DataIndex: (i2 - 1) % count,
          p1DataIndex: i2 % count,
          datasetIndex: line._datasetIndex
        }));
        if (styleChanged(style, prevStyle)) {
          result.push({ start: start4, end: i2 - 1, loop: segment.loop, style: prevStyle });
          prevStyle = style;
          start4 = i2 - 1;
        }
        prev = pt2;
        prevStyle = style;
      }
      if (start4 < i2 - 1) {
        result.push({ start: start4, end: i2 - 1, loop: segment.loop, style });
        start4 = i2 - 1;
      }
    }
    return result;
  }
  function readStyle(options) {
    return {
      backgroundColor: options.backgroundColor,
      borderCapStyle: options.borderCapStyle,
      borderDash: options.borderDash,
      borderDashOffset: options.borderDashOffset,
      borderJoinStyle: options.borderJoinStyle,
      borderWidth: options.borderWidth,
      borderColor: options.borderColor
    };
  }
  function styleChanged(style, prevStyle) {
    return prevStyle && JSON.stringify(style) !== JSON.stringify(prevStyle);
  }

  // ../../node_modules/chart.js/dist/chart.esm.js
  var Animator = class {
    constructor() {
      this._request = null;
      this._charts = /* @__PURE__ */ new Map();
      this._running = false;
      this._lastDate = void 0;
    }
    _notify(chart, anims, date, type) {
      const callbacks = anims.listeners[type];
      const numSteps = anims.duration;
      callbacks.forEach((fn3) => fn3({
        chart,
        initial: anims.initial,
        numSteps,
        currentStep: Math.min(date - anims.start, numSteps)
      }));
    }
    _refresh() {
      const me2 = this;
      if (me2._request) {
        return;
      }
      me2._running = true;
      me2._request = requestAnimFrame.call(window, () => {
        me2._update();
        me2._request = null;
        if (me2._running) {
          me2._refresh();
        }
      });
    }
    _update(date = Date.now()) {
      const me2 = this;
      let remaining = 0;
      me2._charts.forEach((anims, chart) => {
        if (!anims.running || !anims.items.length) {
          return;
        }
        const items = anims.items;
        let i2 = items.length - 1;
        let draw2 = false;
        let item;
        for (; i2 >= 0; --i2) {
          item = items[i2];
          if (item._active) {
            if (item._total > anims.duration) {
              anims.duration = item._total;
            }
            item.tick(date);
            draw2 = true;
          } else {
            items[i2] = items[items.length - 1];
            items.pop();
          }
        }
        if (draw2) {
          chart.draw();
          me2._notify(chart, anims, date, "progress");
        }
        if (!items.length) {
          anims.running = false;
          me2._notify(chart, anims, date, "complete");
          anims.initial = false;
        }
        remaining += items.length;
      });
      me2._lastDate = date;
      if (remaining === 0) {
        me2._running = false;
      }
    }
    _getAnims(chart) {
      const charts = this._charts;
      let anims = charts.get(chart);
      if (!anims) {
        anims = {
          running: false,
          initial: true,
          items: [],
          listeners: {
            complete: [],
            progress: []
          }
        };
        charts.set(chart, anims);
      }
      return anims;
    }
    listen(chart, event, cb) {
      this._getAnims(chart).listeners[event].push(cb);
    }
    add(chart, items) {
      if (!items || !items.length) {
        return;
      }
      this._getAnims(chart).items.push(...items);
    }
    has(chart) {
      return this._getAnims(chart).items.length > 0;
    }
    start(chart) {
      const anims = this._charts.get(chart);
      if (!anims) {
        return;
      }
      anims.running = true;
      anims.start = Date.now();
      anims.duration = anims.items.reduce((acc, cur) => Math.max(acc, cur._duration), 0);
      this._refresh();
    }
    running(chart) {
      if (!this._running) {
        return false;
      }
      const anims = this._charts.get(chart);
      if (!anims || !anims.running || !anims.items.length) {
        return false;
      }
      return true;
    }
    stop(chart) {
      const anims = this._charts.get(chart);
      if (!anims || !anims.items.length) {
        return;
      }
      const items = anims.items;
      let i2 = items.length - 1;
      for (; i2 >= 0; --i2) {
        items[i2].cancel();
      }
      anims.items = [];
      this._notify(chart, anims, Date.now(), "complete");
    }
    remove(chart) {
      return this._charts.delete(chart);
    }
  };
  var animator = new Animator();
  var transparent = "transparent";
  var interpolators = {
    boolean(from, to, factor) {
      return factor > 0.5 ? to : from;
    },
    color(from, to, factor) {
      const c0 = color(from || transparent);
      const c1 = c0.valid && color(to || transparent);
      return c1 && c1.valid ? c1.mix(c0, factor).hexString() : to;
    },
    number(from, to, factor) {
      return from + (to - from) * factor;
    }
  };
  var Animation = class {
    constructor(cfg, target, prop, to) {
      const currentValue = target[prop];
      to = resolve([cfg.to, to, currentValue, cfg.from]);
      const from = resolve([cfg.from, currentValue, to]);
      this._active = true;
      this._fn = cfg.fn || interpolators[cfg.type || typeof from];
      this._easing = effects[cfg.easing] || effects.linear;
      this._start = Math.floor(Date.now() + (cfg.delay || 0));
      this._duration = this._total = Math.floor(cfg.duration);
      this._loop = !!cfg.loop;
      this._target = target;
      this._prop = prop;
      this._from = from;
      this._to = to;
      this._promises = void 0;
    }
    active() {
      return this._active;
    }
    update(cfg, to, date) {
      const me2 = this;
      if (me2._active) {
        me2._notify(false);
        const currentValue = me2._target[me2._prop];
        const elapsed = date - me2._start;
        const remain = me2._duration - elapsed;
        me2._start = date;
        me2._duration = Math.floor(Math.max(remain, cfg.duration));
        me2._total += elapsed;
        me2._loop = !!cfg.loop;
        me2._to = resolve([cfg.to, to, currentValue, cfg.from]);
        me2._from = resolve([cfg.from, currentValue, to]);
      }
    }
    cancel() {
      const me2 = this;
      if (me2._active) {
        me2.tick(Date.now());
        me2._active = false;
        me2._notify(false);
      }
    }
    tick(date) {
      const me2 = this;
      const elapsed = date - me2._start;
      const duration = me2._duration;
      const prop = me2._prop;
      const from = me2._from;
      const loop = me2._loop;
      const to = me2._to;
      let factor;
      me2._active = from !== to && (loop || elapsed < duration);
      if (!me2._active) {
        me2._target[prop] = to;
        me2._notify(true);
        return;
      }
      if (elapsed < 0) {
        me2._target[prop] = from;
        return;
      }
      factor = elapsed / duration % 2;
      factor = loop && factor > 1 ? 2 - factor : factor;
      factor = me2._easing(Math.min(1, Math.max(0, factor)));
      me2._target[prop] = me2._fn(from, to, factor);
    }
    wait() {
      const promises = this._promises || (this._promises = []);
      return new Promise((res, rej) => {
        promises.push({ res, rej });
      });
    }
    _notify(resolved) {
      const method = resolved ? "res" : "rej";
      const promises = this._promises || [];
      for (let i2 = 0; i2 < promises.length; i2++) {
        promises[i2][method]();
      }
    }
  };
  var numbers = ["x", "y", "borderWidth", "radius", "tension"];
  var colors = ["color", "borderColor", "backgroundColor"];
  defaults.set("animation", {
    delay: void 0,
    duration: 1e3,
    easing: "easeOutQuart",
    fn: void 0,
    from: void 0,
    loop: void 0,
    to: void 0,
    type: void 0
  });
  var animationOptions = Object.keys(defaults.animation);
  defaults.describe("animation", {
    _fallback: false,
    _indexable: false,
    _scriptable: (name) => name !== "onProgress" && name !== "onComplete" && name !== "fn"
  });
  defaults.set("animations", {
    colors: {
      type: "color",
      properties: colors
    },
    numbers: {
      type: "number",
      properties: numbers
    }
  });
  defaults.describe("animations", {
    _fallback: "animation"
  });
  defaults.set("transitions", {
    active: {
      animation: {
        duration: 400
      }
    },
    resize: {
      animation: {
        duration: 0
      }
    },
    show: {
      animations: {
        colors: {
          from: "transparent"
        },
        visible: {
          type: "boolean",
          duration: 0
        }
      }
    },
    hide: {
      animations: {
        colors: {
          to: "transparent"
        },
        visible: {
          type: "boolean",
          easing: "linear",
          fn: (v2) => v2 | 0
        }
      }
    }
  });
  var Animations = class {
    constructor(chart, config) {
      this._chart = chart;
      this._properties = /* @__PURE__ */ new Map();
      this.configure(config);
    }
    configure(config) {
      if (!isObject(config)) {
        return;
      }
      const animatedProps = this._properties;
      Object.getOwnPropertyNames(config).forEach((key) => {
        const cfg = config[key];
        if (!isObject(cfg)) {
          return;
        }
        const resolved = {};
        for (const option of animationOptions) {
          resolved[option] = cfg[option];
        }
        (isArray(cfg.properties) && cfg.properties || [key]).forEach((prop) => {
          if (prop === key || !animatedProps.has(prop)) {
            animatedProps.set(prop, resolved);
          }
        });
      });
    }
    _animateOptions(target, values) {
      const newOptions = values.options;
      const options = resolveTargetOptions(target, newOptions);
      if (!options) {
        return [];
      }
      const animations = this._createAnimations(options, newOptions);
      if (newOptions.$shared) {
        awaitAll(target.options.$animations, newOptions).then(() => {
          target.options = newOptions;
        }, () => {
        });
      }
      return animations;
    }
    _createAnimations(target, values) {
      const animatedProps = this._properties;
      const animations = [];
      const running = target.$animations || (target.$animations = {});
      const props = Object.keys(values);
      const date = Date.now();
      let i2;
      for (i2 = props.length - 1; i2 >= 0; --i2) {
        const prop = props[i2];
        if (prop.charAt(0) === "$") {
          continue;
        }
        if (prop === "options") {
          animations.push(...this._animateOptions(target, values));
          continue;
        }
        const value = values[prop];
        let animation = running[prop];
        const cfg = animatedProps.get(prop);
        if (animation) {
          if (cfg && animation.active()) {
            animation.update(cfg, value, date);
            continue;
          } else {
            animation.cancel();
          }
        }
        if (!cfg || !cfg.duration) {
          target[prop] = value;
          continue;
        }
        running[prop] = animation = new Animation(cfg, target, prop, value);
        animations.push(animation);
      }
      return animations;
    }
    update(target, values) {
      if (this._properties.size === 0) {
        Object.assign(target, values);
        return;
      }
      const animations = this._createAnimations(target, values);
      if (animations.length) {
        animator.add(this._chart, animations);
        return true;
      }
    }
  };
  function awaitAll(animations, properties) {
    const running = [];
    const keys = Object.keys(properties);
    for (let i2 = 0; i2 < keys.length; i2++) {
      const anim = animations[keys[i2]];
      if (anim && anim.active()) {
        running.push(anim.wait());
      }
    }
    return Promise.all(running);
  }
  function resolveTargetOptions(target, newOptions) {
    if (!newOptions) {
      return;
    }
    let options = target.options;
    if (!options) {
      target.options = newOptions;
      return;
    }
    if (options.$shared) {
      target.options = options = Object.assign({}, options, { $shared: false, $animations: {} });
    }
    return options;
  }
  function scaleClip(scale, allowedOverflow) {
    const opts = scale && scale.options || {};
    const reverse = opts.reverse;
    const min2 = opts.min === void 0 ? allowedOverflow : 0;
    const max2 = opts.max === void 0 ? allowedOverflow : 0;
    return {
      start: reverse ? max2 : min2,
      end: reverse ? min2 : max2
    };
  }
  function defaultClip(xScale, yScale, allowedOverflow) {
    if (allowedOverflow === false) {
      return false;
    }
    const x2 = scaleClip(xScale, allowedOverflow);
    const y2 = scaleClip(yScale, allowedOverflow);
    return {
      top: y2.end,
      right: x2.end,
      bottom: y2.start,
      left: x2.start
    };
  }
  function toClip(value) {
    let t2, r2, b2, l2;
    if (isObject(value)) {
      t2 = value.top;
      r2 = value.right;
      b2 = value.bottom;
      l2 = value.left;
    } else {
      t2 = r2 = b2 = l2 = value;
    }
    return {
      top: t2,
      right: r2,
      bottom: b2,
      left: l2,
      disabled: value === false
    };
  }
  function getSortedDatasetIndices(chart, filterVisible) {
    const keys = [];
    const metasets = chart._getSortedDatasetMetas(filterVisible);
    let i2, ilen;
    for (i2 = 0, ilen = metasets.length; i2 < ilen; ++i2) {
      keys.push(metasets[i2].index);
    }
    return keys;
  }
  function applyStack(stack, value, dsIndex, options) {
    const keys = stack.keys;
    const singleMode = options.mode === "single";
    let i2, ilen, datasetIndex, otherValue;
    if (value === null) {
      return;
    }
    for (i2 = 0, ilen = keys.length; i2 < ilen; ++i2) {
      datasetIndex = +keys[i2];
      if (datasetIndex === dsIndex) {
        if (options.all) {
          continue;
        }
        break;
      }
      otherValue = stack.values[datasetIndex];
      if (isNumberFinite(otherValue) && (singleMode || (value === 0 || sign(value) === sign(otherValue)))) {
        value += otherValue;
      }
    }
    return value;
  }
  function convertObjectDataToArray(data) {
    const keys = Object.keys(data);
    const adata = new Array(keys.length);
    let i2, ilen, key;
    for (i2 = 0, ilen = keys.length; i2 < ilen; ++i2) {
      key = keys[i2];
      adata[i2] = {
        x: key,
        y: data[key]
      };
    }
    return adata;
  }
  function isStacked(scale, meta) {
    const stacked = scale && scale.options.stacked;
    return stacked || stacked === void 0 && meta.stack !== void 0;
  }
  function getStackKey(indexScale, valueScale, meta) {
    return `${indexScale.id}.${valueScale.id}.${meta.stack || meta.type}`;
  }
  function getUserBounds(scale) {
    const { min: min2, max: max2, minDefined, maxDefined } = scale.getUserBounds();
    return {
      min: minDefined ? min2 : Number.NEGATIVE_INFINITY,
      max: maxDefined ? max2 : Number.POSITIVE_INFINITY
    };
  }
  function getOrCreateStack(stacks, stackKey, indexValue) {
    const subStack = stacks[stackKey] || (stacks[stackKey] = {});
    return subStack[indexValue] || (subStack[indexValue] = {});
  }
  function getLastIndexInStack(stack, vScale, positive) {
    for (const meta of vScale.getMatchingVisibleMetas("bar").reverse()) {
      const value = stack[meta.index];
      if (positive && value > 0 || !positive && value < 0) {
        return meta.index;
      }
    }
    return null;
  }
  function updateStacks(controller, parsed) {
    const { chart, _cachedMeta: meta } = controller;
    const stacks = chart._stacks || (chart._stacks = {});
    const { iScale, vScale, index: datasetIndex } = meta;
    const iAxis = iScale.axis;
    const vAxis = vScale.axis;
    const key = getStackKey(iScale, vScale, meta);
    const ilen = parsed.length;
    let stack;
    for (let i2 = 0; i2 < ilen; ++i2) {
      const item = parsed[i2];
      const { [iAxis]: index, [vAxis]: value } = item;
      const itemStacks = item._stacks || (item._stacks = {});
      stack = itemStacks[vAxis] = getOrCreateStack(stacks, key, index);
      stack[datasetIndex] = value;
      stack._top = getLastIndexInStack(stack, vScale, true);
      stack._bottom = getLastIndexInStack(stack, vScale, false);
    }
  }
  function getFirstScaleId(chart, axis) {
    const scales2 = chart.scales;
    return Object.keys(scales2).filter((key) => scales2[key].axis === axis).shift();
  }
  function createDatasetContext(parent, index) {
    return Object.assign(Object.create(parent), {
      active: false,
      dataset: void 0,
      datasetIndex: index,
      index,
      mode: "default",
      type: "dataset"
    });
  }
  function createDataContext(parent, index, element) {
    return Object.assign(Object.create(parent), {
      active: false,
      dataIndex: index,
      parsed: void 0,
      raw: void 0,
      element,
      index,
      mode: "default",
      type: "data"
    });
  }
  function clearStacks(meta, items) {
    const datasetIndex = meta.controller.index;
    const axis = meta.vScale && meta.vScale.axis;
    if (!axis) {
      return;
    }
    items = items || meta._parsed;
    for (const parsed of items) {
      const stacks = parsed._stacks;
      if (!stacks || stacks[axis] === void 0 || stacks[axis][datasetIndex] === void 0) {
        return;
      }
      delete stacks[axis][datasetIndex];
    }
  }
  var isDirectUpdateMode = (mode) => mode === "reset" || mode === "none";
  var cloneIfNotShared = (cached, shared) => shared ? cached : Object.assign({}, cached);
  var DatasetController = class {
    constructor(chart, datasetIndex) {
      this.chart = chart;
      this._ctx = chart.ctx;
      this.index = datasetIndex;
      this._cachedDataOpts = {};
      this._cachedMeta = this.getMeta();
      this._type = this._cachedMeta.type;
      this.options = void 0;
      this._parsing = false;
      this._data = void 0;
      this._objectData = void 0;
      this._sharedOptions = void 0;
      this._drawStart = void 0;
      this._drawCount = void 0;
      this.enableOptionSharing = false;
      this.$context = void 0;
      this._syncList = [];
      this.initialize();
    }
    initialize() {
      const me2 = this;
      const meta = me2._cachedMeta;
      me2.configure();
      me2.linkScales();
      meta._stacked = isStacked(meta.vScale, meta);
      me2.addElements();
    }
    updateIndex(datasetIndex) {
      if (this.index !== datasetIndex) {
        clearStacks(this._cachedMeta);
      }
      this.index = datasetIndex;
    }
    linkScales() {
      const me2 = this;
      const chart = me2.chart;
      const meta = me2._cachedMeta;
      const dataset = me2.getDataset();
      const chooseId = (axis, x2, y2, r2) => axis === "x" ? x2 : axis === "r" ? r2 : y2;
      const xid = meta.xAxisID = valueOrDefault(dataset.xAxisID, getFirstScaleId(chart, "x"));
      const yid = meta.yAxisID = valueOrDefault(dataset.yAxisID, getFirstScaleId(chart, "y"));
      const rid = meta.rAxisID = valueOrDefault(dataset.rAxisID, getFirstScaleId(chart, "r"));
      const indexAxis = meta.indexAxis;
      const iid = meta.iAxisID = chooseId(indexAxis, xid, yid, rid);
      const vid = meta.vAxisID = chooseId(indexAxis, yid, xid, rid);
      meta.xScale = me2.getScaleForId(xid);
      meta.yScale = me2.getScaleForId(yid);
      meta.rScale = me2.getScaleForId(rid);
      meta.iScale = me2.getScaleForId(iid);
      meta.vScale = me2.getScaleForId(vid);
    }
    getDataset() {
      return this.chart.data.datasets[this.index];
    }
    getMeta() {
      return this.chart.getDatasetMeta(this.index);
    }
    getScaleForId(scaleID) {
      return this.chart.scales[scaleID];
    }
    _getOtherScale(scale) {
      const meta = this._cachedMeta;
      return scale === meta.iScale ? meta.vScale : meta.iScale;
    }
    reset() {
      this._update("reset");
    }
    _destroy() {
      const meta = this._cachedMeta;
      if (this._data) {
        unlistenArrayEvents(this._data, this);
      }
      if (meta._stacked) {
        clearStacks(meta);
      }
    }
    _dataCheck() {
      const me2 = this;
      const dataset = me2.getDataset();
      const data = dataset.data || (dataset.data = []);
      const _data = me2._data;
      if (isObject(data)) {
        me2._data = convertObjectDataToArray(data);
      } else if (_data !== data) {
        if (_data) {
          unlistenArrayEvents(_data, me2);
          const meta = me2._cachedMeta;
          clearStacks(meta);
          meta._parsed = [];
        }
        if (data && Object.isExtensible(data)) {
          listenArrayEvents(data, me2);
        }
        me2._syncList = [];
        me2._data = data;
      }
    }
    addElements() {
      const me2 = this;
      const meta = me2._cachedMeta;
      me2._dataCheck();
      if (me2.datasetElementType) {
        meta.dataset = new me2.datasetElementType();
      }
    }
    buildOrUpdateElements(resetNewElements) {
      const me2 = this;
      const meta = me2._cachedMeta;
      const dataset = me2.getDataset();
      let stackChanged = false;
      me2._dataCheck();
      const oldStacked = meta._stacked;
      meta._stacked = isStacked(meta.vScale, meta);
      if (meta.stack !== dataset.stack) {
        stackChanged = true;
        clearStacks(meta);
        meta.stack = dataset.stack;
      }
      me2._resyncElements(resetNewElements);
      if (stackChanged || oldStacked !== meta._stacked) {
        updateStacks(me2, meta._parsed);
      }
    }
    configure() {
      const me2 = this;
      const config = me2.chart.config;
      const scopeKeys = config.datasetScopeKeys(me2._type);
      const scopes = config.getOptionScopes(me2.getDataset(), scopeKeys, true);
      me2.options = config.createResolver(scopes, me2.getContext());
      me2._parsing = me2.options.parsing;
    }
    parse(start4, count) {
      const me2 = this;
      const { _cachedMeta: meta, _data: data } = me2;
      const { iScale, _stacked } = meta;
      const iAxis = iScale.axis;
      let sorted = start4 === 0 && count === data.length ? true : meta._sorted;
      let prev = start4 > 0 && meta._parsed[start4 - 1];
      let i2, cur, parsed;
      if (me2._parsing === false) {
        meta._parsed = data;
        meta._sorted = true;
        parsed = data;
      } else {
        if (isArray(data[start4])) {
          parsed = me2.parseArrayData(meta, data, start4, count);
        } else if (isObject(data[start4])) {
          parsed = me2.parseObjectData(meta, data, start4, count);
        } else {
          parsed = me2.parsePrimitiveData(meta, data, start4, count);
        }
        const isNotInOrderComparedToPrev = () => cur[iAxis] === null || prev && cur[iAxis] < prev[iAxis];
        for (i2 = 0; i2 < count; ++i2) {
          meta._parsed[i2 + start4] = cur = parsed[i2];
          if (sorted) {
            if (isNotInOrderComparedToPrev()) {
              sorted = false;
            }
            prev = cur;
          }
        }
        meta._sorted = sorted;
      }
      if (_stacked) {
        updateStacks(me2, parsed);
      }
    }
    parsePrimitiveData(meta, data, start4, count) {
      const { iScale, vScale } = meta;
      const iAxis = iScale.axis;
      const vAxis = vScale.axis;
      const labels = iScale.getLabels();
      const singleScale = iScale === vScale;
      const parsed = new Array(count);
      let i2, ilen, index;
      for (i2 = 0, ilen = count; i2 < ilen; ++i2) {
        index = i2 + start4;
        parsed[i2] = {
          [iAxis]: singleScale || iScale.parse(labels[index], index),
          [vAxis]: vScale.parse(data[index], index)
        };
      }
      return parsed;
    }
    parseArrayData(meta, data, start4, count) {
      const { xScale, yScale } = meta;
      const parsed = new Array(count);
      let i2, ilen, index, item;
      for (i2 = 0, ilen = count; i2 < ilen; ++i2) {
        index = i2 + start4;
        item = data[index];
        parsed[i2] = {
          x: xScale.parse(item[0], index),
          y: yScale.parse(item[1], index)
        };
      }
      return parsed;
    }
    parseObjectData(meta, data, start4, count) {
      const { xScale, yScale } = meta;
      const { xAxisKey = "x", yAxisKey = "y" } = this._parsing;
      const parsed = new Array(count);
      let i2, ilen, index, item;
      for (i2 = 0, ilen = count; i2 < ilen; ++i2) {
        index = i2 + start4;
        item = data[index];
        parsed[i2] = {
          x: xScale.parse(resolveObjectKey(item, xAxisKey), index),
          y: yScale.parse(resolveObjectKey(item, yAxisKey), index)
        };
      }
      return parsed;
    }
    getParsed(index) {
      return this._cachedMeta._parsed[index];
    }
    getDataElement(index) {
      return this._cachedMeta.data[index];
    }
    applyStack(scale, parsed, mode) {
      const chart = this.chart;
      const meta = this._cachedMeta;
      const value = parsed[scale.axis];
      const stack = {
        keys: getSortedDatasetIndices(chart, true),
        values: parsed._stacks[scale.axis]
      };
      return applyStack(stack, value, meta.index, { mode });
    }
    updateRangeFromParsed(range, scale, parsed, stack) {
      const parsedValue = parsed[scale.axis];
      let value = parsedValue === null ? NaN : parsedValue;
      const values = stack && parsed._stacks[scale.axis];
      if (stack && values) {
        stack.values = values;
        range.min = Math.min(range.min, value);
        range.max = Math.max(range.max, value);
        value = applyStack(stack, parsedValue, this._cachedMeta.index, { all: true });
      }
      range.min = Math.min(range.min, value);
      range.max = Math.max(range.max, value);
    }
    getMinMax(scale, canStack) {
      const me2 = this;
      const meta = me2._cachedMeta;
      const _parsed = meta._parsed;
      const sorted = meta._sorted && scale === meta.iScale;
      const ilen = _parsed.length;
      const otherScale = me2._getOtherScale(scale);
      const stack = canStack && meta._stacked && { keys: getSortedDatasetIndices(me2.chart, true), values: null };
      const range = { min: Number.POSITIVE_INFINITY, max: Number.NEGATIVE_INFINITY };
      const { min: otherMin, max: otherMax } = getUserBounds(otherScale);
      let i2, value, parsed, otherValue;
      function _skip() {
        parsed = _parsed[i2];
        value = parsed[scale.axis];
        otherValue = parsed[otherScale.axis];
        return !isNumberFinite(value) || otherMin > otherValue || otherMax < otherValue;
      }
      for (i2 = 0; i2 < ilen; ++i2) {
        if (_skip()) {
          continue;
        }
        me2.updateRangeFromParsed(range, scale, parsed, stack);
        if (sorted) {
          break;
        }
      }
      if (sorted) {
        for (i2 = ilen - 1; i2 >= 0; --i2) {
          if (_skip()) {
            continue;
          }
          me2.updateRangeFromParsed(range, scale, parsed, stack);
          break;
        }
      }
      return range;
    }
    getAllParsedValues(scale) {
      const parsed = this._cachedMeta._parsed;
      const values = [];
      let i2, ilen, value;
      for (i2 = 0, ilen = parsed.length; i2 < ilen; ++i2) {
        value = parsed[i2][scale.axis];
        if (isNumberFinite(value)) {
          values.push(value);
        }
      }
      return values;
    }
    getMaxOverflow() {
      return false;
    }
    getLabelAndValue(index) {
      const me2 = this;
      const meta = me2._cachedMeta;
      const iScale = meta.iScale;
      const vScale = meta.vScale;
      const parsed = me2.getParsed(index);
      return {
        label: iScale ? "" + iScale.getLabelForValue(parsed[iScale.axis]) : "",
        value: vScale ? "" + vScale.getLabelForValue(parsed[vScale.axis]) : ""
      };
    }
    _update(mode) {
      const me2 = this;
      const meta = me2._cachedMeta;
      me2.configure();
      me2._cachedDataOpts = {};
      me2.update(mode || "default");
      meta._clip = toClip(valueOrDefault(me2.options.clip, defaultClip(meta.xScale, meta.yScale, me2.getMaxOverflow())));
    }
    update(mode) {
    }
    draw() {
      const me2 = this;
      const ctx = me2._ctx;
      const chart = me2.chart;
      const meta = me2._cachedMeta;
      const elements2 = meta.data || [];
      const area = chart.chartArea;
      const active = [];
      const start4 = me2._drawStart || 0;
      const count = me2._drawCount || elements2.length - start4;
      let i2;
      if (meta.dataset) {
        meta.dataset.draw(ctx, area, start4, count);
      }
      for (i2 = start4; i2 < start4 + count; ++i2) {
        const element = elements2[i2];
        if (element.hidden) {
          continue;
        }
        if (element.active) {
          active.push(element);
        } else {
          element.draw(ctx, area);
        }
      }
      for (i2 = 0; i2 < active.length; ++i2) {
        active[i2].draw(ctx, area);
      }
    }
    getStyle(index, active) {
      const mode = active ? "active" : "default";
      return index === void 0 && this._cachedMeta.dataset ? this.resolveDatasetElementOptions(mode) : this.resolveDataElementOptions(index || 0, mode);
    }
    getContext(index, active, mode) {
      const me2 = this;
      const dataset = me2.getDataset();
      let context;
      if (index >= 0 && index < me2._cachedMeta.data.length) {
        const element = me2._cachedMeta.data[index];
        context = element.$context || (element.$context = createDataContext(me2.getContext(), index, element));
        context.parsed = me2.getParsed(index);
        context.raw = dataset.data[index];
        context.index = context.dataIndex = index;
      } else {
        context = me2.$context || (me2.$context = createDatasetContext(me2.chart.getContext(), me2.index));
        context.dataset = dataset;
        context.index = context.datasetIndex = me2.index;
      }
      context.active = !!active;
      context.mode = mode;
      return context;
    }
    resolveDatasetElementOptions(mode) {
      return this._resolveElementOptions(this.datasetElementType.id, mode);
    }
    resolveDataElementOptions(index, mode) {
      return this._resolveElementOptions(this.dataElementType.id, mode, index);
    }
    _resolveElementOptions(elementType2, mode = "default", index) {
      const me2 = this;
      const active = mode === "active";
      const cache2 = me2._cachedDataOpts;
      const cacheKey = elementType2 + "-" + mode;
      const cached = cache2[cacheKey];
      const sharing = me2.enableOptionSharing && defined(index);
      if (cached) {
        return cloneIfNotShared(cached, sharing);
      }
      const config = me2.chart.config;
      const scopeKeys = config.datasetElementScopeKeys(me2._type, elementType2);
      const prefixes = active ? [`${elementType2}Hover`, "hover", elementType2, ""] : [elementType2, ""];
      const scopes = config.getOptionScopes(me2.getDataset(), scopeKeys);
      const names2 = Object.keys(defaults.elements[elementType2]);
      const context = () => me2.getContext(index, active);
      const values = config.resolveNamedOptions(scopes, names2, context, prefixes);
      if (values.$shared) {
        values.$shared = sharing;
        cache2[cacheKey] = Object.freeze(cloneIfNotShared(values, sharing));
      }
      return values;
    }
    _resolveAnimations(index, transition, active) {
      const me2 = this;
      const chart = me2.chart;
      const cache2 = me2._cachedDataOpts;
      const cacheKey = `animation-${transition}`;
      const cached = cache2[cacheKey];
      if (cached) {
        return cached;
      }
      let options;
      if (chart.options.animation !== false) {
        const config = me2.chart.config;
        const scopeKeys = config.datasetAnimationScopeKeys(me2._type, transition);
        const scopes = config.getOptionScopes(me2.getDataset(), scopeKeys);
        options = config.createResolver(scopes, me2.getContext(index, active, transition));
      }
      const animations = new Animations(chart, options && options.animations);
      if (options && options._cacheable) {
        cache2[cacheKey] = Object.freeze(animations);
      }
      return animations;
    }
    getSharedOptions(options) {
      if (!options.$shared) {
        return;
      }
      return this._sharedOptions || (this._sharedOptions = Object.assign({}, options));
    }
    includeOptions(mode, sharedOptions) {
      return !sharedOptions || isDirectUpdateMode(mode) || this.chart._animationsDisabled;
    }
    updateElement(element, index, properties, mode) {
      if (isDirectUpdateMode(mode)) {
        Object.assign(element, properties);
      } else {
        this._resolveAnimations(index, mode).update(element, properties);
      }
    }
    updateSharedOptions(sharedOptions, mode, newOptions) {
      if (sharedOptions && !isDirectUpdateMode(mode)) {
        this._resolveAnimations(void 0, mode).update(sharedOptions, newOptions);
      }
    }
    _setStyle(element, index, mode, active) {
      element.active = active;
      const options = this.getStyle(index, active);
      this._resolveAnimations(index, mode, active).update(element, {
        options: !active && this.getSharedOptions(options) || options
      });
    }
    removeHoverStyle(element, datasetIndex, index) {
      this._setStyle(element, index, "active", false);
    }
    setHoverStyle(element, datasetIndex, index) {
      this._setStyle(element, index, "active", true);
    }
    _removeDatasetHoverStyle() {
      const element = this._cachedMeta.dataset;
      if (element) {
        this._setStyle(element, void 0, "active", false);
      }
    }
    _setDatasetHoverStyle() {
      const element = this._cachedMeta.dataset;
      if (element) {
        this._setStyle(element, void 0, "active", true);
      }
    }
    _resyncElements(resetNewElements) {
      const me2 = this;
      const data = me2._data;
      const elements2 = me2._cachedMeta.data;
      for (const [method, arg1, arg2] of me2._syncList) {
        me2[method](arg1, arg2);
      }
      me2._syncList = [];
      const numMeta = elements2.length;
      const numData = data.length;
      const count = Math.min(numData, numMeta);
      if (count) {
        me2.parse(0, count);
      }
      if (numData > numMeta) {
        me2._insertElements(numMeta, numData - numMeta, resetNewElements);
      } else if (numData < numMeta) {
        me2._removeElements(numData, numMeta - numData);
      }
    }
    _insertElements(start4, count, resetNewElements = true) {
      const me2 = this;
      const meta = me2._cachedMeta;
      const data = meta.data;
      const end2 = start4 + count;
      let i2;
      const move = (arr) => {
        arr.length += count;
        for (i2 = arr.length - 1; i2 >= end2; i2--) {
          arr[i2] = arr[i2 - count];
        }
      };
      move(data);
      for (i2 = start4; i2 < end2; ++i2) {
        data[i2] = new me2.dataElementType();
      }
      if (me2._parsing) {
        move(meta._parsed);
      }
      me2.parse(start4, count);
      if (resetNewElements) {
        me2.updateElements(data, start4, count, "reset");
      }
    }
    updateElements(element, start4, count, mode) {
    }
    _removeElements(start4, count) {
      const me2 = this;
      const meta = me2._cachedMeta;
      if (me2._parsing) {
        const removed = meta._parsed.splice(start4, count);
        if (meta._stacked) {
          clearStacks(meta, removed);
        }
      }
      meta.data.splice(start4, count);
    }
    _onDataPush() {
      const count = arguments.length;
      this._syncList.push(["_insertElements", this.getDataset().data.length - count, count]);
    }
    _onDataPop() {
      this._syncList.push(["_removeElements", this._cachedMeta.data.length - 1, 1]);
    }
    _onDataShift() {
      this._syncList.push(["_removeElements", 0, 1]);
    }
    _onDataSplice(start4, count) {
      this._syncList.push(["_removeElements", start4, count]);
      this._syncList.push(["_insertElements", start4, arguments.length - 2]);
    }
    _onDataUnshift() {
      this._syncList.push(["_insertElements", 0, arguments.length]);
    }
  };
  DatasetController.defaults = {};
  DatasetController.prototype.datasetElementType = null;
  DatasetController.prototype.dataElementType = null;
  function getAllScaleValues(scale) {
    if (!scale._cache.$bar) {
      const metas = scale.getMatchingVisibleMetas("bar");
      let values = [];
      for (let i2 = 0, ilen = metas.length; i2 < ilen; i2++) {
        values = values.concat(metas[i2].controller.getAllParsedValues(scale));
      }
      scale._cache.$bar = _arrayUnique(values.sort((a2, b2) => a2 - b2));
    }
    return scale._cache.$bar;
  }
  function computeMinSampleSize(scale) {
    const values = getAllScaleValues(scale);
    let min2 = scale._length;
    let i2, ilen, curr, prev;
    const updateMinAndPrev = () => {
      if (curr === 32767 || curr === -32768) {
        return;
      }
      if (defined(prev)) {
        min2 = Math.min(min2, Math.abs(curr - prev) || min2);
      }
      prev = curr;
    };
    for (i2 = 0, ilen = values.length; i2 < ilen; ++i2) {
      curr = scale.getPixelForValue(values[i2]);
      updateMinAndPrev();
    }
    prev = void 0;
    for (i2 = 0, ilen = scale.ticks.length; i2 < ilen; ++i2) {
      curr = scale.getPixelForTick(i2);
      updateMinAndPrev();
    }
    return min2;
  }
  function computeFitCategoryTraits(index, ruler, options, stackCount) {
    const thickness = options.barThickness;
    let size, ratio;
    if (isNullOrUndef(thickness)) {
      size = ruler.min * options.categoryPercentage;
      ratio = options.barPercentage;
    } else {
      size = thickness * stackCount;
      ratio = 1;
    }
    return {
      chunk: size / stackCount,
      ratio,
      start: ruler.pixels[index] - size / 2
    };
  }
  function computeFlexCategoryTraits(index, ruler, options, stackCount) {
    const pixels = ruler.pixels;
    const curr = pixels[index];
    let prev = index > 0 ? pixels[index - 1] : null;
    let next = index < pixels.length - 1 ? pixels[index + 1] : null;
    const percent = options.categoryPercentage;
    if (prev === null) {
      prev = curr - (next === null ? ruler.end - ruler.start : next - curr);
    }
    if (next === null) {
      next = curr + curr - prev;
    }
    const start4 = curr - (curr - Math.min(prev, next)) / 2 * percent;
    const size = Math.abs(next - prev) / 2 * percent;
    return {
      chunk: size / stackCount,
      ratio: options.barPercentage,
      start: start4
    };
  }
  function parseFloatBar(entry, item, vScale, i2) {
    const startValue = vScale.parse(entry[0], i2);
    const endValue = vScale.parse(entry[1], i2);
    const min2 = Math.min(startValue, endValue);
    const max2 = Math.max(startValue, endValue);
    let barStart = min2;
    let barEnd = max2;
    if (Math.abs(min2) > Math.abs(max2)) {
      barStart = max2;
      barEnd = min2;
    }
    item[vScale.axis] = barEnd;
    item._custom = {
      barStart,
      barEnd,
      start: startValue,
      end: endValue,
      min: min2,
      max: max2
    };
  }
  function parseValue(entry, item, vScale, i2) {
    if (isArray(entry)) {
      parseFloatBar(entry, item, vScale, i2);
    } else {
      item[vScale.axis] = vScale.parse(entry, i2);
    }
    return item;
  }
  function parseArrayOrPrimitive(meta, data, start4, count) {
    const iScale = meta.iScale;
    const vScale = meta.vScale;
    const labels = iScale.getLabels();
    const singleScale = iScale === vScale;
    const parsed = [];
    let i2, ilen, item, entry;
    for (i2 = start4, ilen = start4 + count; i2 < ilen; ++i2) {
      entry = data[i2];
      item = {};
      item[iScale.axis] = singleScale || iScale.parse(labels[i2], i2);
      parsed.push(parseValue(entry, item, vScale, i2));
    }
    return parsed;
  }
  function isFloatBar(custom) {
    return custom && custom.barStart !== void 0 && custom.barEnd !== void 0;
  }
  function barSign(size, vScale, actualBase) {
    if (size !== 0) {
      return sign(size);
    }
    return (vScale.isHorizontal() ? 1 : -1) * (vScale.min >= actualBase ? 1 : -1);
  }
  function borderProps(properties) {
    let reverse, start4, end2, top2, bottom2;
    if (properties.horizontal) {
      reverse = properties.base > properties.x;
      start4 = "left";
      end2 = "right";
    } else {
      reverse = properties.base < properties.y;
      start4 = "bottom";
      end2 = "top";
    }
    if (reverse) {
      top2 = "end";
      bottom2 = "start";
    } else {
      top2 = "start";
      bottom2 = "end";
    }
    return { start: start4, end: end2, reverse, top: top2, bottom: bottom2 };
  }
  function setBorderSkipped(properties, options, stack, index) {
    let edge = options.borderSkipped;
    const res = {};
    if (!edge) {
      properties.borderSkipped = res;
      return;
    }
    const { start: start4, end: end2, reverse, top: top2, bottom: bottom2 } = borderProps(properties);
    if (edge === "middle" && stack) {
      properties.enableBorderRadius = true;
      if ((stack._top || 0) === index) {
        edge = top2;
      } else if ((stack._bottom || 0) === index) {
        edge = bottom2;
      } else {
        res[parseEdge(bottom2, start4, end2, reverse)] = true;
        edge = top2;
      }
    }
    res[parseEdge(edge, start4, end2, reverse)] = true;
    properties.borderSkipped = res;
  }
  function parseEdge(edge, a2, b2, reverse) {
    if (reverse) {
      edge = swap(edge, a2, b2);
      edge = startEnd(edge, b2, a2);
    } else {
      edge = startEnd(edge, a2, b2);
    }
    return edge;
  }
  function swap(orig, v1, v2) {
    return orig === v1 ? v2 : orig === v2 ? v1 : orig;
  }
  function startEnd(v2, start4, end2) {
    return v2 === "start" ? start4 : v2 === "end" ? end2 : v2;
  }
  var BarController = class extends DatasetController {
    parsePrimitiveData(meta, data, start4, count) {
      return parseArrayOrPrimitive(meta, data, start4, count);
    }
    parseArrayData(meta, data, start4, count) {
      return parseArrayOrPrimitive(meta, data, start4, count);
    }
    parseObjectData(meta, data, start4, count) {
      const { iScale, vScale } = meta;
      const { xAxisKey = "x", yAxisKey = "y" } = this._parsing;
      const iAxisKey = iScale.axis === "x" ? xAxisKey : yAxisKey;
      const vAxisKey = vScale.axis === "x" ? xAxisKey : yAxisKey;
      const parsed = [];
      let i2, ilen, item, obj;
      for (i2 = start4, ilen = start4 + count; i2 < ilen; ++i2) {
        obj = data[i2];
        item = {};
        item[iScale.axis] = iScale.parse(resolveObjectKey(obj, iAxisKey), i2);
        parsed.push(parseValue(resolveObjectKey(obj, vAxisKey), item, vScale, i2));
      }
      return parsed;
    }
    updateRangeFromParsed(range, scale, parsed, stack) {
      super.updateRangeFromParsed(range, scale, parsed, stack);
      const custom = parsed._custom;
      if (custom && scale === this._cachedMeta.vScale) {
        range.min = Math.min(range.min, custom.min);
        range.max = Math.max(range.max, custom.max);
      }
    }
    getMaxOverflow() {
      return 0;
    }
    getLabelAndValue(index) {
      const me2 = this;
      const meta = me2._cachedMeta;
      const { iScale, vScale } = meta;
      const parsed = me2.getParsed(index);
      const custom = parsed._custom;
      const value = isFloatBar(custom) ? "[" + custom.start + ", " + custom.end + "]" : "" + vScale.getLabelForValue(parsed[vScale.axis]);
      return {
        label: "" + iScale.getLabelForValue(parsed[iScale.axis]),
        value
      };
    }
    initialize() {
      const me2 = this;
      me2.enableOptionSharing = true;
      super.initialize();
      const meta = me2._cachedMeta;
      meta.stack = me2.getDataset().stack;
    }
    update(mode) {
      const me2 = this;
      const meta = me2._cachedMeta;
      me2.updateElements(meta.data, 0, meta.data.length, mode);
    }
    updateElements(bars, start4, count, mode) {
      const me2 = this;
      const reset = mode === "reset";
      const { index, _cachedMeta: { vScale } } = me2;
      const base = vScale.getBasePixel();
      const horizontal = vScale.isHorizontal();
      const ruler = me2._getRuler();
      const firstOpts = me2.resolveDataElementOptions(start4, mode);
      const sharedOptions = me2.getSharedOptions(firstOpts);
      const includeOptions = me2.includeOptions(mode, sharedOptions);
      me2.updateSharedOptions(sharedOptions, mode, firstOpts);
      for (let i2 = start4; i2 < start4 + count; i2++) {
        const parsed = me2.getParsed(i2);
        const vpixels = reset || isNullOrUndef(parsed[vScale.axis]) ? { base, head: base } : me2._calculateBarValuePixels(i2);
        const ipixels = me2._calculateBarIndexPixels(i2, ruler);
        const stack = (parsed._stacks || {})[vScale.axis];
        const properties = {
          horizontal,
          base: vpixels.base,
          enableBorderRadius: !stack || isFloatBar(parsed._custom) || (index === stack._top || index === stack._bottom),
          x: horizontal ? vpixels.head : ipixels.center,
          y: horizontal ? ipixels.center : vpixels.head,
          height: horizontal ? ipixels.size : Math.abs(vpixels.size),
          width: horizontal ? Math.abs(vpixels.size) : ipixels.size
        };
        if (includeOptions) {
          properties.options = sharedOptions || me2.resolveDataElementOptions(i2, bars[i2].active ? "active" : mode);
        }
        setBorderSkipped(properties, properties.options || bars[i2].options, stack, index);
        me2.updateElement(bars[i2], i2, properties, mode);
      }
    }
    _getStacks(last, dataIndex) {
      const me2 = this;
      const meta = me2._cachedMeta;
      const iScale = meta.iScale;
      const metasets = iScale.getMatchingVisibleMetas(me2._type);
      const stacked = iScale.options.stacked;
      const ilen = metasets.length;
      const stacks = [];
      let i2, item;
      for (i2 = 0; i2 < ilen; ++i2) {
        item = metasets[i2];
        if (!item.controller.options.grouped) {
          continue;
        }
        if (typeof dataIndex !== "undefined") {
          const val = item.controller.getParsed(dataIndex)[item.controller._cachedMeta.vScale.axis];
          if (isNullOrUndef(val) || isNaN(val)) {
            continue;
          }
        }
        if (stacked === false || stacks.indexOf(item.stack) === -1 || stacked === void 0 && item.stack === void 0) {
          stacks.push(item.stack);
        }
        if (item.index === last) {
          break;
        }
      }
      if (!stacks.length) {
        stacks.push(void 0);
      }
      return stacks;
    }
    _getStackCount(index) {
      return this._getStacks(void 0, index).length;
    }
    _getStackIndex(datasetIndex, name, dataIndex) {
      const stacks = this._getStacks(datasetIndex, dataIndex);
      const index = name !== void 0 ? stacks.indexOf(name) : -1;
      return index === -1 ? stacks.length - 1 : index;
    }
    _getRuler() {
      const me2 = this;
      const opts = me2.options;
      const meta = me2._cachedMeta;
      const iScale = meta.iScale;
      const pixels = [];
      let i2, ilen;
      for (i2 = 0, ilen = meta.data.length; i2 < ilen; ++i2) {
        pixels.push(iScale.getPixelForValue(me2.getParsed(i2)[iScale.axis], i2));
      }
      const barThickness = opts.barThickness;
      const min2 = barThickness || computeMinSampleSize(iScale);
      return {
        min: min2,
        pixels,
        start: iScale._startPixel,
        end: iScale._endPixel,
        stackCount: me2._getStackCount(),
        scale: iScale,
        grouped: opts.grouped,
        ratio: barThickness ? 1 : opts.categoryPercentage * opts.barPercentage
      };
    }
    _calculateBarValuePixels(index) {
      const me2 = this;
      const { _cachedMeta: { vScale, _stacked }, options: { base: baseValue, minBarLength } } = me2;
      const actualBase = baseValue || 0;
      const parsed = me2.getParsed(index);
      const custom = parsed._custom;
      const floating = isFloatBar(custom);
      let value = parsed[vScale.axis];
      let start4 = 0;
      let length = _stacked ? me2.applyStack(vScale, parsed, _stacked) : value;
      let head, size;
      if (length !== value) {
        start4 = length - value;
        length = value;
      }
      if (floating) {
        value = custom.barStart;
        length = custom.barEnd - custom.barStart;
        if (value !== 0 && sign(value) !== sign(custom.barEnd)) {
          start4 = 0;
        }
        start4 += value;
      }
      const startValue = !isNullOrUndef(baseValue) && !floating ? baseValue : start4;
      let base = vScale.getPixelForValue(startValue);
      if (me2.chart.getDataVisibility(index)) {
        head = vScale.getPixelForValue(start4 + length);
      } else {
        head = base;
      }
      size = head - base;
      if (Math.abs(size) < minBarLength) {
        size = barSign(size, vScale, actualBase) * minBarLength;
        if (value === actualBase) {
          base -= size / 2;
        }
        head = base + size;
      }
      if (base === vScale.getPixelForValue(actualBase)) {
        const halfGrid = sign(size) * vScale.getLineWidthForValue(actualBase) / 2;
        base += halfGrid;
        size -= halfGrid;
      }
      return {
        size,
        base,
        head,
        center: head + size / 2
      };
    }
    _calculateBarIndexPixels(index, ruler) {
      const me2 = this;
      const scale = ruler.scale;
      const options = me2.options;
      const skipNull = options.skipNull;
      const maxBarThickness = valueOrDefault(options.maxBarThickness, Infinity);
      let center, size;
      if (ruler.grouped) {
        const stackCount = skipNull ? me2._getStackCount(index) : ruler.stackCount;
        const range = options.barThickness === "flex" ? computeFlexCategoryTraits(index, ruler, options, stackCount) : computeFitCategoryTraits(index, ruler, options, stackCount);
        const stackIndex = me2._getStackIndex(me2.index, me2._cachedMeta.stack, skipNull ? index : void 0);
        center = range.start + range.chunk * stackIndex + range.chunk / 2;
        size = Math.min(maxBarThickness, range.chunk * range.ratio);
      } else {
        center = scale.getPixelForValue(me2.getParsed(index)[scale.axis], index);
        size = Math.min(maxBarThickness, ruler.min * ruler.ratio);
      }
      return {
        base: center - size / 2,
        head: center + size / 2,
        center,
        size
      };
    }
    draw() {
      const me2 = this;
      const meta = me2._cachedMeta;
      const vScale = meta.vScale;
      const rects = meta.data;
      const ilen = rects.length;
      let i2 = 0;
      for (; i2 < ilen; ++i2) {
        if (me2.getParsed(i2)[vScale.axis] !== null) {
          rects[i2].draw(me2._ctx);
        }
      }
    }
  };
  BarController.id = "bar";
  BarController.defaults = {
    datasetElementType: false,
    dataElementType: "bar",
    categoryPercentage: 0.8,
    barPercentage: 0.9,
    grouped: true,
    animations: {
      numbers: {
        type: "number",
        properties: ["x", "y", "base", "width", "height"]
      }
    }
  };
  BarController.overrides = {
    interaction: {
      mode: "index"
    },
    scales: {
      _index_: {
        type: "category",
        offset: true,
        grid: {
          offset: true
        }
      },
      _value_: {
        type: "linear",
        beginAtZero: true
      }
    }
  };
  var BubbleController = class extends DatasetController {
    initialize() {
      this.enableOptionSharing = true;
      super.initialize();
    }
    parseObjectData(meta, data, start4, count) {
      const { xScale, yScale } = meta;
      const { xAxisKey = "x", yAxisKey = "y" } = this._parsing;
      const parsed = [];
      let i2, ilen, item;
      for (i2 = start4, ilen = start4 + count; i2 < ilen; ++i2) {
        item = data[i2];
        parsed.push({
          x: xScale.parse(resolveObjectKey(item, xAxisKey), i2),
          y: yScale.parse(resolveObjectKey(item, yAxisKey), i2),
          _custom: item && item.r && +item.r
        });
      }
      return parsed;
    }
    getMaxOverflow() {
      const { data, _parsed } = this._cachedMeta;
      let max2 = 0;
      for (let i2 = data.length - 1; i2 >= 0; --i2) {
        max2 = Math.max(max2, data[i2].size() / 2, _parsed[i2]._custom);
      }
      return max2 > 0 && max2;
    }
    getLabelAndValue(index) {
      const me2 = this;
      const meta = me2._cachedMeta;
      const { xScale, yScale } = meta;
      const parsed = me2.getParsed(index);
      const x2 = xScale.getLabelForValue(parsed.x);
      const y2 = yScale.getLabelForValue(parsed.y);
      const r2 = parsed._custom;
      return {
        label: meta.label,
        value: "(" + x2 + ", " + y2 + (r2 ? ", " + r2 : "") + ")"
      };
    }
    update(mode) {
      const me2 = this;
      const points = me2._cachedMeta.data;
      me2.updateElements(points, 0, points.length, mode);
    }
    updateElements(points, start4, count, mode) {
      const me2 = this;
      const reset = mode === "reset";
      const { iScale, vScale } = me2._cachedMeta;
      const firstOpts = me2.resolveDataElementOptions(start4, mode);
      const sharedOptions = me2.getSharedOptions(firstOpts);
      const includeOptions = me2.includeOptions(mode, sharedOptions);
      const iAxis = iScale.axis;
      const vAxis = vScale.axis;
      for (let i2 = start4; i2 < start4 + count; i2++) {
        const point = points[i2];
        const parsed = !reset && me2.getParsed(i2);
        const properties = {};
        const iPixel = properties[iAxis] = reset ? iScale.getPixelForDecimal(0.5) : iScale.getPixelForValue(parsed[iAxis]);
        const vPixel = properties[vAxis] = reset ? vScale.getBasePixel() : vScale.getPixelForValue(parsed[vAxis]);
        properties.skip = isNaN(iPixel) || isNaN(vPixel);
        if (includeOptions) {
          properties.options = me2.resolveDataElementOptions(i2, point.active ? "active" : mode);
          if (reset) {
            properties.options.radius = 0;
          }
        }
        me2.updateElement(point, i2, properties, mode);
      }
      me2.updateSharedOptions(sharedOptions, mode, firstOpts);
    }
    resolveDataElementOptions(index, mode) {
      const parsed = this.getParsed(index);
      let values = super.resolveDataElementOptions(index, mode);
      if (values.$shared) {
        values = Object.assign({}, values, { $shared: false });
      }
      const radius = values.radius;
      if (mode !== "active") {
        values.radius = 0;
      }
      values.radius += valueOrDefault(parsed && parsed._custom, radius);
      return values;
    }
  };
  BubbleController.id = "bubble";
  BubbleController.defaults = {
    datasetElementType: false,
    dataElementType: "point",
    animations: {
      numbers: {
        type: "number",
        properties: ["x", "y", "borderWidth", "radius"]
      }
    }
  };
  BubbleController.overrides = {
    scales: {
      x: {
        type: "linear"
      },
      y: {
        type: "linear"
      }
    },
    plugins: {
      tooltip: {
        callbacks: {
          title() {
            return "";
          }
        }
      }
    }
  };
  function getRatioAndOffset(rotation, circumference, cutout) {
    let ratioX = 1;
    let ratioY = 1;
    let offsetX = 0;
    let offsetY = 0;
    if (circumference < TAU) {
      const startAngle = rotation;
      const endAngle = startAngle + circumference;
      const startX = Math.cos(startAngle);
      const startY = Math.sin(startAngle);
      const endX = Math.cos(endAngle);
      const endY = Math.sin(endAngle);
      const calcMax = (angle, a2, b2) => _angleBetween(angle, startAngle, endAngle, true) ? 1 : Math.max(a2, a2 * cutout, b2, b2 * cutout);
      const calcMin = (angle, a2, b2) => _angleBetween(angle, startAngle, endAngle, true) ? -1 : Math.min(a2, a2 * cutout, b2, b2 * cutout);
      const maxX = calcMax(0, startX, endX);
      const maxY = calcMax(HALF_PI, startY, endY);
      const minX = calcMin(PI, startX, endX);
      const minY = calcMin(PI + HALF_PI, startY, endY);
      ratioX = (maxX - minX) / 2;
      ratioY = (maxY - minY) / 2;
      offsetX = -(maxX + minX) / 2;
      offsetY = -(maxY + minY) / 2;
    }
    return { ratioX, ratioY, offsetX, offsetY };
  }
  var DoughnutController = class extends DatasetController {
    constructor(chart, datasetIndex) {
      super(chart, datasetIndex);
      this.enableOptionSharing = true;
      this.innerRadius = void 0;
      this.outerRadius = void 0;
      this.offsetX = void 0;
      this.offsetY = void 0;
    }
    linkScales() {
    }
    parse(start4, count) {
      const data = this.getDataset().data;
      const meta = this._cachedMeta;
      let i2, ilen;
      for (i2 = start4, ilen = start4 + count; i2 < ilen; ++i2) {
        meta._parsed[i2] = +data[i2];
      }
    }
    _getRotation() {
      return toRadians(this.options.rotation - 90);
    }
    _getCircumference() {
      return toRadians(this.options.circumference);
    }
    _getRotationExtents() {
      let min2 = TAU;
      let max2 = -TAU;
      const me2 = this;
      for (let i2 = 0; i2 < me2.chart.data.datasets.length; ++i2) {
        if (me2.chart.isDatasetVisible(i2)) {
          const controller = me2.chart.getDatasetMeta(i2).controller;
          const rotation = controller._getRotation();
          const circumference = controller._getCircumference();
          min2 = Math.min(min2, rotation);
          max2 = Math.max(max2, rotation + circumference);
        }
      }
      return {
        rotation: min2,
        circumference: max2 - min2
      };
    }
    update(mode) {
      const me2 = this;
      const chart = me2.chart;
      const { chartArea } = chart;
      const meta = me2._cachedMeta;
      const arcs = meta.data;
      const spacing = me2.getMaxBorderWidth() + me2.getMaxOffset(arcs) + me2.options.spacing;
      const maxSize = Math.max((Math.min(chartArea.width, chartArea.height) - spacing) / 2, 0);
      const cutout = Math.min(toPercentage(me2.options.cutout, maxSize), 1);
      const chartWeight = me2._getRingWeight(me2.index);
      const { circumference, rotation } = me2._getRotationExtents();
      const { ratioX, ratioY, offsetX, offsetY } = getRatioAndOffset(rotation, circumference, cutout);
      const maxWidth = (chartArea.width - spacing) / ratioX;
      const maxHeight = (chartArea.height - spacing) / ratioY;
      const maxRadius = Math.max(Math.min(maxWidth, maxHeight) / 2, 0);
      const outerRadius = toDimension(me2.options.radius, maxRadius);
      const innerRadius = Math.max(outerRadius * cutout, 0);
      const radiusLength = (outerRadius - innerRadius) / me2._getVisibleDatasetWeightTotal();
      me2.offsetX = offsetX * outerRadius;
      me2.offsetY = offsetY * outerRadius;
      meta.total = me2.calculateTotal();
      me2.outerRadius = outerRadius - radiusLength * me2._getRingWeightOffset(me2.index);
      me2.innerRadius = Math.max(me2.outerRadius - radiusLength * chartWeight, 0);
      me2.updateElements(arcs, 0, arcs.length, mode);
    }
    _circumference(i2, reset) {
      const me2 = this;
      const opts = me2.options;
      const meta = me2._cachedMeta;
      const circumference = me2._getCircumference();
      if (reset && opts.animation.animateRotate || !this.chart.getDataVisibility(i2) || meta._parsed[i2] === null || meta.data[i2].hidden) {
        return 0;
      }
      return me2.calculateCircumference(meta._parsed[i2] * circumference / TAU);
    }
    updateElements(arcs, start4, count, mode) {
      const me2 = this;
      const reset = mode === "reset";
      const chart = me2.chart;
      const chartArea = chart.chartArea;
      const opts = chart.options;
      const animationOpts = opts.animation;
      const centerX = (chartArea.left + chartArea.right) / 2;
      const centerY = (chartArea.top + chartArea.bottom) / 2;
      const animateScale = reset && animationOpts.animateScale;
      const innerRadius = animateScale ? 0 : me2.innerRadius;
      const outerRadius = animateScale ? 0 : me2.outerRadius;
      const firstOpts = me2.resolveDataElementOptions(start4, mode);
      const sharedOptions = me2.getSharedOptions(firstOpts);
      const includeOptions = me2.includeOptions(mode, sharedOptions);
      let startAngle = me2._getRotation();
      let i2;
      for (i2 = 0; i2 < start4; ++i2) {
        startAngle += me2._circumference(i2, reset);
      }
      for (i2 = start4; i2 < start4 + count; ++i2) {
        const circumference = me2._circumference(i2, reset);
        const arc = arcs[i2];
        const properties = {
          x: centerX + me2.offsetX,
          y: centerY + me2.offsetY,
          startAngle,
          endAngle: startAngle + circumference,
          circumference,
          outerRadius,
          innerRadius
        };
        if (includeOptions) {
          properties.options = sharedOptions || me2.resolveDataElementOptions(i2, arc.active ? "active" : mode);
        }
        startAngle += circumference;
        me2.updateElement(arc, i2, properties, mode);
      }
      me2.updateSharedOptions(sharedOptions, mode, firstOpts);
    }
    calculateTotal() {
      const meta = this._cachedMeta;
      const metaData = meta.data;
      let total = 0;
      let i2;
      for (i2 = 0; i2 < metaData.length; i2++) {
        const value = meta._parsed[i2];
        if (value !== null && !isNaN(value) && this.chart.getDataVisibility(i2) && !metaData[i2].hidden) {
          total += Math.abs(value);
        }
      }
      return total;
    }
    calculateCircumference(value) {
      const total = this._cachedMeta.total;
      if (total > 0 && !isNaN(value)) {
        return TAU * (Math.abs(value) / total);
      }
      return 0;
    }
    getLabelAndValue(index) {
      const me2 = this;
      const meta = me2._cachedMeta;
      const chart = me2.chart;
      const labels = chart.data.labels || [];
      const value = formatNumber(meta._parsed[index], chart.options.locale);
      return {
        label: labels[index] || "",
        value
      };
    }
    getMaxBorderWidth(arcs) {
      const me2 = this;
      let max2 = 0;
      const chart = me2.chart;
      let i2, ilen, meta, controller, options;
      if (!arcs) {
        for (i2 = 0, ilen = chart.data.datasets.length; i2 < ilen; ++i2) {
          if (chart.isDatasetVisible(i2)) {
            meta = chart.getDatasetMeta(i2);
            arcs = meta.data;
            controller = meta.controller;
            if (controller !== me2) {
              controller.configure();
            }
            break;
          }
        }
      }
      if (!arcs) {
        return 0;
      }
      for (i2 = 0, ilen = arcs.length; i2 < ilen; ++i2) {
        options = controller.resolveDataElementOptions(i2);
        if (options.borderAlign !== "inner") {
          max2 = Math.max(max2, options.borderWidth || 0, options.hoverBorderWidth || 0);
        }
      }
      return max2;
    }
    getMaxOffset(arcs) {
      let max2 = 0;
      for (let i2 = 0, ilen = arcs.length; i2 < ilen; ++i2) {
        const options = this.resolveDataElementOptions(i2);
        max2 = Math.max(max2, options.offset || 0, options.hoverOffset || 0);
      }
      return max2;
    }
    _getRingWeightOffset(datasetIndex) {
      let ringWeightOffset = 0;
      for (let i2 = 0; i2 < datasetIndex; ++i2) {
        if (this.chart.isDatasetVisible(i2)) {
          ringWeightOffset += this._getRingWeight(i2);
        }
      }
      return ringWeightOffset;
    }
    _getRingWeight(datasetIndex) {
      return Math.max(valueOrDefault(this.chart.data.datasets[datasetIndex].weight, 1), 0);
    }
    _getVisibleDatasetWeightTotal() {
      return this._getRingWeightOffset(this.chart.data.datasets.length) || 1;
    }
  };
  DoughnutController.id = "doughnut";
  DoughnutController.defaults = {
    datasetElementType: false,
    dataElementType: "arc",
    animation: {
      animateRotate: true,
      animateScale: false
    },
    animations: {
      numbers: {
        type: "number",
        properties: ["circumference", "endAngle", "innerRadius", "outerRadius", "startAngle", "x", "y", "offset", "borderWidth", "spacing"]
      }
    },
    cutout: "50%",
    rotation: 0,
    circumference: 360,
    radius: "100%",
    spacing: 0,
    indexAxis: "r"
  };
  DoughnutController.descriptors = {
    _scriptable: (name) => name !== "spacing",
    _indexable: (name) => name !== "spacing"
  };
  DoughnutController.overrides = {
    aspectRatio: 1,
    plugins: {
      legend: {
        labels: {
          generateLabels(chart) {
            const data = chart.data;
            if (data.labels.length && data.datasets.length) {
              const { labels: { pointStyle } } = chart.legend.options;
              return data.labels.map((label, i2) => {
                const meta = chart.getDatasetMeta(0);
                const style = meta.controller.getStyle(i2);
                return {
                  text: label,
                  fillStyle: style.backgroundColor,
                  strokeStyle: style.borderColor,
                  lineWidth: style.borderWidth,
                  pointStyle,
                  hidden: !chart.getDataVisibility(i2),
                  index: i2
                };
              });
            }
            return [];
          }
        },
        onClick(e2, legendItem, legend) {
          legend.chart.toggleDataVisibility(legendItem.index);
          legend.chart.update();
        }
      },
      tooltip: {
        callbacks: {
          title() {
            return "";
          },
          label(tooltipItem) {
            let dataLabel = tooltipItem.label;
            const value = ": " + tooltipItem.formattedValue;
            if (isArray(dataLabel)) {
              dataLabel = dataLabel.slice();
              dataLabel[0] += value;
            } else {
              dataLabel += value;
            }
            return dataLabel;
          }
        }
      }
    }
  };
  var LineController = class extends DatasetController {
    initialize() {
      this.enableOptionSharing = true;
      super.initialize();
    }
    update(mode) {
      const me2 = this;
      const meta = me2._cachedMeta;
      const { dataset: line, data: points = [], _dataset } = meta;
      const animationsDisabled = me2.chart._animationsDisabled;
      let { start: start4, count } = getStartAndCountOfVisiblePoints(meta, points, animationsDisabled);
      me2._drawStart = start4;
      me2._drawCount = count;
      if (scaleRangesChanged(meta)) {
        start4 = 0;
        count = points.length;
      }
      line._datasetIndex = me2.index;
      line._decimated = !!_dataset._decimated;
      line.points = points;
      const options = me2.resolveDatasetElementOptions(mode);
      if (!me2.options.showLine) {
        options.borderWidth = 0;
      }
      options.segment = me2.options.segment;
      me2.updateElement(line, void 0, {
        animated: !animationsDisabled,
        options
      }, mode);
      me2.updateElements(points, start4, count, mode);
    }
    updateElements(points, start4, count, mode) {
      const me2 = this;
      const reset = mode === "reset";
      const { iScale, vScale, _stacked } = me2._cachedMeta;
      const firstOpts = me2.resolveDataElementOptions(start4, mode);
      const sharedOptions = me2.getSharedOptions(firstOpts);
      const includeOptions = me2.includeOptions(mode, sharedOptions);
      const iAxis = iScale.axis;
      const vAxis = vScale.axis;
      const spanGaps = me2.options.spanGaps;
      const maxGapLength = isNumber(spanGaps) ? spanGaps : Number.POSITIVE_INFINITY;
      const directUpdate = me2.chart._animationsDisabled || reset || mode === "none";
      let prevParsed = start4 > 0 && me2.getParsed(start4 - 1);
      for (let i2 = start4; i2 < start4 + count; ++i2) {
        const point = points[i2];
        const parsed = me2.getParsed(i2);
        const properties = directUpdate ? point : {};
        const nullData = isNullOrUndef(parsed[vAxis]);
        const iPixel = properties[iAxis] = iScale.getPixelForValue(parsed[iAxis], i2);
        const vPixel = properties[vAxis] = reset || nullData ? vScale.getBasePixel() : vScale.getPixelForValue(_stacked ? me2.applyStack(vScale, parsed, _stacked) : parsed[vAxis], i2);
        properties.skip = isNaN(iPixel) || isNaN(vPixel) || nullData;
        properties.stop = i2 > 0 && parsed[iAxis] - prevParsed[iAxis] > maxGapLength;
        properties.parsed = parsed;
        if (includeOptions) {
          properties.options = sharedOptions || me2.resolveDataElementOptions(i2, point.active ? "active" : mode);
        }
        if (!directUpdate) {
          me2.updateElement(point, i2, properties, mode);
        }
        prevParsed = parsed;
      }
      me2.updateSharedOptions(sharedOptions, mode, firstOpts);
    }
    getMaxOverflow() {
      const me2 = this;
      const meta = me2._cachedMeta;
      const dataset = meta.dataset;
      const border = dataset.options && dataset.options.borderWidth || 0;
      const data = meta.data || [];
      if (!data.length) {
        return border;
      }
      const firstPoint = data[0].size(me2.resolveDataElementOptions(0));
      const lastPoint = data[data.length - 1].size(me2.resolveDataElementOptions(data.length - 1));
      return Math.max(border, firstPoint, lastPoint) / 2;
    }
    draw() {
      const meta = this._cachedMeta;
      meta.dataset.updateControlPoints(this.chart.chartArea, meta.iScale.axis);
      super.draw();
    }
  };
  LineController.id = "line";
  LineController.defaults = {
    datasetElementType: "line",
    dataElementType: "point",
    showLine: true,
    spanGaps: false
  };
  LineController.overrides = {
    scales: {
      _index_: {
        type: "category"
      },
      _value_: {
        type: "linear"
      }
    }
  };
  function getStartAndCountOfVisiblePoints(meta, points, animationsDisabled) {
    const pointCount = points.length;
    let start4 = 0;
    let count = pointCount;
    if (meta._sorted) {
      const { iScale, _parsed } = meta;
      const axis = iScale.axis;
      const { min: min2, max: max2, minDefined, maxDefined } = iScale.getUserBounds();
      if (minDefined) {
        start4 = _limitValue(Math.min(_lookupByKey(_parsed, iScale.axis, min2).lo, animationsDisabled ? pointCount : _lookupByKey(points, axis, iScale.getPixelForValue(min2)).lo), 0, pointCount - 1);
      }
      if (maxDefined) {
        count = _limitValue(Math.max(_lookupByKey(_parsed, iScale.axis, max2).hi + 1, animationsDisabled ? 0 : _lookupByKey(points, axis, iScale.getPixelForValue(max2)).hi + 1), start4, pointCount) - start4;
      } else {
        count = pointCount - start4;
      }
    }
    return { start: start4, count };
  }
  function scaleRangesChanged(meta) {
    const { xScale, yScale, _scaleRanges } = meta;
    const newRanges = {
      xmin: xScale.min,
      xmax: xScale.max,
      ymin: yScale.min,
      ymax: yScale.max
    };
    if (!_scaleRanges) {
      meta._scaleRanges = newRanges;
      return true;
    }
    const changed = _scaleRanges.xmin !== xScale.min || _scaleRanges.xmax !== xScale.max || _scaleRanges.ymin !== yScale.min || _scaleRanges.ymax !== yScale.max;
    Object.assign(_scaleRanges, newRanges);
    return changed;
  }
  var PolarAreaController = class extends DatasetController {
    constructor(chart, datasetIndex) {
      super(chart, datasetIndex);
      this.innerRadius = void 0;
      this.outerRadius = void 0;
    }
    getLabelAndValue(index) {
      const me2 = this;
      const meta = me2._cachedMeta;
      const chart = me2.chart;
      const labels = chart.data.labels || [];
      const value = formatNumber(meta._parsed[index].r, chart.options.locale);
      return {
        label: labels[index] || "",
        value
      };
    }
    update(mode) {
      const arcs = this._cachedMeta.data;
      this._updateRadius();
      this.updateElements(arcs, 0, arcs.length, mode);
    }
    _updateRadius() {
      const me2 = this;
      const chart = me2.chart;
      const chartArea = chart.chartArea;
      const opts = chart.options;
      const minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);
      const outerRadius = Math.max(minSize / 2, 0);
      const innerRadius = Math.max(opts.cutoutPercentage ? outerRadius / 100 * opts.cutoutPercentage : 1, 0);
      const radiusLength = (outerRadius - innerRadius) / chart.getVisibleDatasetCount();
      me2.outerRadius = outerRadius - radiusLength * me2.index;
      me2.innerRadius = me2.outerRadius - radiusLength;
    }
    updateElements(arcs, start4, count, mode) {
      const me2 = this;
      const reset = mode === "reset";
      const chart = me2.chart;
      const dataset = me2.getDataset();
      const opts = chart.options;
      const animationOpts = opts.animation;
      const scale = me2._cachedMeta.rScale;
      const centerX = scale.xCenter;
      const centerY = scale.yCenter;
      const datasetStartAngle = scale.getIndexAngle(0) - 0.5 * PI;
      let angle = datasetStartAngle;
      let i2;
      const defaultAngle = 360 / me2.countVisibleElements();
      for (i2 = 0; i2 < start4; ++i2) {
        angle += me2._computeAngle(i2, mode, defaultAngle);
      }
      for (i2 = start4; i2 < start4 + count; i2++) {
        const arc = arcs[i2];
        let startAngle = angle;
        let endAngle = angle + me2._computeAngle(i2, mode, defaultAngle);
        let outerRadius = chart.getDataVisibility(i2) ? scale.getDistanceFromCenterForValue(dataset.data[i2]) : 0;
        angle = endAngle;
        if (reset) {
          if (animationOpts.animateScale) {
            outerRadius = 0;
          }
          if (animationOpts.animateRotate) {
            startAngle = endAngle = datasetStartAngle;
          }
        }
        const properties = {
          x: centerX,
          y: centerY,
          innerRadius: 0,
          outerRadius,
          startAngle,
          endAngle,
          options: me2.resolveDataElementOptions(i2, arc.active ? "active" : mode)
        };
        me2.updateElement(arc, i2, properties, mode);
      }
    }
    countVisibleElements() {
      const dataset = this.getDataset();
      const meta = this._cachedMeta;
      let count = 0;
      meta.data.forEach((element, index) => {
        if (!isNaN(dataset.data[index]) && this.chart.getDataVisibility(index)) {
          count++;
        }
      });
      return count;
    }
    _computeAngle(index, mode, defaultAngle) {
      return this.chart.getDataVisibility(index) ? toRadians(this.resolveDataElementOptions(index, mode).angle || defaultAngle) : 0;
    }
  };
  PolarAreaController.id = "polarArea";
  PolarAreaController.defaults = {
    dataElementType: "arc",
    animation: {
      animateRotate: true,
      animateScale: true
    },
    animations: {
      numbers: {
        type: "number",
        properties: ["x", "y", "startAngle", "endAngle", "innerRadius", "outerRadius"]
      }
    },
    indexAxis: "r",
    startAngle: 0
  };
  PolarAreaController.overrides = {
    aspectRatio: 1,
    plugins: {
      legend: {
        labels: {
          generateLabels(chart) {
            const data = chart.data;
            if (data.labels.length && data.datasets.length) {
              const { labels: { pointStyle } } = chart.legend.options;
              return data.labels.map((label, i2) => {
                const meta = chart.getDatasetMeta(0);
                const style = meta.controller.getStyle(i2);
                return {
                  text: label,
                  fillStyle: style.backgroundColor,
                  strokeStyle: style.borderColor,
                  lineWidth: style.borderWidth,
                  pointStyle,
                  hidden: !chart.getDataVisibility(i2),
                  index: i2
                };
              });
            }
            return [];
          }
        },
        onClick(e2, legendItem, legend) {
          legend.chart.toggleDataVisibility(legendItem.index);
          legend.chart.update();
        }
      },
      tooltip: {
        callbacks: {
          title() {
            return "";
          },
          label(context) {
            return context.chart.data.labels[context.dataIndex] + ": " + context.formattedValue;
          }
        }
      }
    },
    scales: {
      r: {
        type: "radialLinear",
        angleLines: {
          display: false
        },
        beginAtZero: true,
        grid: {
          circular: true
        },
        pointLabels: {
          display: false
        },
        startAngle: 0
      }
    }
  };
  var PieController = class extends DoughnutController {
  };
  PieController.id = "pie";
  PieController.defaults = {
    cutout: 0,
    rotation: 0,
    circumference: 360,
    radius: "100%"
  };
  var RadarController = class extends DatasetController {
    getLabelAndValue(index) {
      const me2 = this;
      const vScale = me2._cachedMeta.vScale;
      const parsed = me2.getParsed(index);
      return {
        label: vScale.getLabels()[index],
        value: "" + vScale.getLabelForValue(parsed[vScale.axis])
      };
    }
    update(mode) {
      const me2 = this;
      const meta = me2._cachedMeta;
      const line = meta.dataset;
      const points = meta.data || [];
      const labels = meta.iScale.getLabels();
      line.points = points;
      if (mode !== "resize") {
        const options = me2.resolveDatasetElementOptions(mode);
        if (!me2.options.showLine) {
          options.borderWidth = 0;
        }
        const properties = {
          _loop: true,
          _fullLoop: labels.length === points.length,
          options
        };
        me2.updateElement(line, void 0, properties, mode);
      }
      me2.updateElements(points, 0, points.length, mode);
    }
    updateElements(points, start4, count, mode) {
      const me2 = this;
      const dataset = me2.getDataset();
      const scale = me2._cachedMeta.rScale;
      const reset = mode === "reset";
      for (let i2 = start4; i2 < start4 + count; i2++) {
        const point = points[i2];
        const options = me2.resolveDataElementOptions(i2, point.active ? "active" : mode);
        const pointPosition = scale.getPointPositionForValue(i2, dataset.data[i2]);
        const x2 = reset ? scale.xCenter : pointPosition.x;
        const y2 = reset ? scale.yCenter : pointPosition.y;
        const properties = {
          x: x2,
          y: y2,
          angle: pointPosition.angle,
          skip: isNaN(x2) || isNaN(y2),
          options
        };
        me2.updateElement(point, i2, properties, mode);
      }
    }
  };
  RadarController.id = "radar";
  RadarController.defaults = {
    datasetElementType: "line",
    dataElementType: "point",
    indexAxis: "r",
    showLine: true,
    elements: {
      line: {
        fill: "start"
      }
    }
  };
  RadarController.overrides = {
    aspectRatio: 1,
    scales: {
      r: {
        type: "radialLinear"
      }
    }
  };
  var ScatterController = class extends LineController {
  };
  ScatterController.id = "scatter";
  ScatterController.defaults = {
    showLine: false,
    fill: false
  };
  ScatterController.overrides = {
    interaction: {
      mode: "point"
    },
    plugins: {
      tooltip: {
        callbacks: {
          title() {
            return "";
          },
          label(item) {
            return "(" + item.label + ", " + item.formattedValue + ")";
          }
        }
      }
    },
    scales: {
      x: {
        type: "linear"
      },
      y: {
        type: "linear"
      }
    }
  };
  var controllers = /* @__PURE__ */ Object.freeze({
    __proto__: null,
    BarController,
    BubbleController,
    DoughnutController,
    LineController,
    PolarAreaController,
    PieController,
    RadarController,
    ScatterController
  });
  function abstract() {
    throw new Error("This method is not implemented: Check that a complete date adapter is provided.");
  }
  var DateAdapter = class {
    constructor(options) {
      this.options = options || {};
    }
    formats() {
      return abstract();
    }
    parse(value, format3) {
      return abstract();
    }
    format(timestamp, format3) {
      return abstract();
    }
    add(timestamp, amount, unit) {
      return abstract();
    }
    diff(a2, b2, unit) {
      return abstract();
    }
    startOf(timestamp, unit, weekday) {
      return abstract();
    }
    endOf(timestamp, unit) {
      return abstract();
    }
  };
  DateAdapter.override = function(members) {
    Object.assign(DateAdapter.prototype, members);
  };
  var adapters = {
    _date: DateAdapter
  };
  function getRelativePosition2(e2, chart) {
    if ("native" in e2) {
      return {
        x: e2.x,
        y: e2.y
      };
    }
    return getRelativePosition(e2, chart);
  }
  function evaluateAllVisibleItems(chart, handler) {
    const metasets = chart.getSortedVisibleDatasetMetas();
    let index, data, element;
    for (let i2 = 0, ilen = metasets.length; i2 < ilen; ++i2) {
      ({ index, data } = metasets[i2]);
      for (let j2 = 0, jlen = data.length; j2 < jlen; ++j2) {
        element = data[j2];
        if (!element.skip) {
          handler(element, index, j2);
        }
      }
    }
  }
  function binarySearch(metaset, axis, value, intersect) {
    const { controller, data, _sorted } = metaset;
    const iScale = controller._cachedMeta.iScale;
    if (iScale && axis === iScale.axis && _sorted && data.length) {
      const lookupMethod = iScale._reversePixels ? _rlookupByKey : _lookupByKey;
      if (!intersect) {
        return lookupMethod(data, axis, value);
      } else if (controller._sharedOptions) {
        const el = data[0];
        const range = typeof el.getRange === "function" && el.getRange(axis);
        if (range) {
          const start4 = lookupMethod(data, axis, value - range);
          const end2 = lookupMethod(data, axis, value + range);
          return { lo: start4.lo, hi: end2.hi };
        }
      }
    }
    return { lo: 0, hi: data.length - 1 };
  }
  function optimizedEvaluateItems(chart, axis, position, handler, intersect) {
    const metasets = chart.getSortedVisibleDatasetMetas();
    const value = position[axis];
    for (let i2 = 0, ilen = metasets.length; i2 < ilen; ++i2) {
      const { index, data } = metasets[i2];
      const { lo, hi: hi2 } = binarySearch(metasets[i2], axis, value, intersect);
      for (let j2 = lo; j2 <= hi2; ++j2) {
        const element = data[j2];
        if (!element.skip) {
          handler(element, index, j2);
        }
      }
    }
  }
  function getDistanceMetricForAxis(axis) {
    const useX = axis.indexOf("x") !== -1;
    const useY = axis.indexOf("y") !== -1;
    return function(pt1, pt2) {
      const deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0;
      const deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0;
      return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));
    };
  }
  function getIntersectItems(chart, position, axis, useFinalPosition) {
    const items = [];
    if (!_isPointInArea(position, chart.chartArea, chart._minPadding)) {
      return items;
    }
    const evaluationFunc = function(element, datasetIndex, index) {
      if (element.inRange(position.x, position.y, useFinalPosition)) {
        items.push({ element, datasetIndex, index });
      }
    };
    optimizedEvaluateItems(chart, axis, position, evaluationFunc, true);
    return items;
  }
  function getNearestItems(chart, position, axis, intersect, useFinalPosition) {
    const distanceMetric = getDistanceMetricForAxis(axis);
    let minDistance = Number.POSITIVE_INFINITY;
    let items = [];
    if (!_isPointInArea(position, chart.chartArea, chart._minPadding)) {
      return items;
    }
    const evaluationFunc = function(element, datasetIndex, index) {
      if (intersect && !element.inRange(position.x, position.y, useFinalPosition)) {
        return;
      }
      const center = element.getCenterPoint(useFinalPosition);
      if (!_isPointInArea(center, chart.chartArea, chart._minPadding) && !element.inRange(position.x, position.y, useFinalPosition)) {
        return;
      }
      const distance = distanceMetric(position, center);
      if (distance < minDistance) {
        items = [{ element, datasetIndex, index }];
        minDistance = distance;
      } else if (distance === minDistance) {
        items.push({ element, datasetIndex, index });
      }
    };
    optimizedEvaluateItems(chart, axis, position, evaluationFunc);
    return items;
  }
  function getAxisItems(chart, e2, options, useFinalPosition) {
    const position = getRelativePosition2(e2, chart);
    const items = [];
    const axis = options.axis;
    const rangeMethod = axis === "x" ? "inXRange" : "inYRange";
    let intersectsItem = false;
    evaluateAllVisibleItems(chart, (element, datasetIndex, index) => {
      if (element[rangeMethod](position[axis], useFinalPosition)) {
        items.push({ element, datasetIndex, index });
      }
      if (element.inRange(position.x, position.y, useFinalPosition)) {
        intersectsItem = true;
      }
    });
    if (options.intersect && !intersectsItem) {
      return [];
    }
    return items;
  }
  var Interaction = {
    modes: {
      index(chart, e2, options, useFinalPosition) {
        const position = getRelativePosition2(e2, chart);
        const axis = options.axis || "x";
        const items = options.intersect ? getIntersectItems(chart, position, axis, useFinalPosition) : getNearestItems(chart, position, axis, false, useFinalPosition);
        const elements2 = [];
        if (!items.length) {
          return [];
        }
        chart.getSortedVisibleDatasetMetas().forEach((meta) => {
          const index = items[0].index;
          const element = meta.data[index];
          if (element && !element.skip) {
            elements2.push({ element, datasetIndex: meta.index, index });
          }
        });
        return elements2;
      },
      dataset(chart, e2, options, useFinalPosition) {
        const position = getRelativePosition2(e2, chart);
        const axis = options.axis || "xy";
        let items = options.intersect ? getIntersectItems(chart, position, axis, useFinalPosition) : getNearestItems(chart, position, axis, false, useFinalPosition);
        if (items.length > 0) {
          const datasetIndex = items[0].datasetIndex;
          const data = chart.getDatasetMeta(datasetIndex).data;
          items = [];
          for (let i2 = 0; i2 < data.length; ++i2) {
            items.push({ element: data[i2], datasetIndex, index: i2 });
          }
        }
        return items;
      },
      point(chart, e2, options, useFinalPosition) {
        const position = getRelativePosition2(e2, chart);
        const axis = options.axis || "xy";
        return getIntersectItems(chart, position, axis, useFinalPosition);
      },
      nearest(chart, e2, options, useFinalPosition) {
        const position = getRelativePosition2(e2, chart);
        const axis = options.axis || "xy";
        return getNearestItems(chart, position, axis, options.intersect, useFinalPosition);
      },
      x(chart, e2, options, useFinalPosition) {
        options.axis = "x";
        return getAxisItems(chart, e2, options, useFinalPosition);
      },
      y(chart, e2, options, useFinalPosition) {
        options.axis = "y";
        return getAxisItems(chart, e2, options, useFinalPosition);
      }
    }
  };
  var STATIC_POSITIONS = ["left", "top", "right", "bottom"];
  function filterByPosition(array, position) {
    return array.filter((v2) => v2.pos === position);
  }
  function filterDynamicPositionByAxis(array, axis) {
    return array.filter((v2) => STATIC_POSITIONS.indexOf(v2.pos) === -1 && v2.box.axis === axis);
  }
  function sortByWeight(array, reverse) {
    return array.sort((a2, b2) => {
      const v0 = reverse ? b2 : a2;
      const v1 = reverse ? a2 : b2;
      return v0.weight === v1.weight ? v0.index - v1.index : v0.weight - v1.weight;
    });
  }
  function wrapBoxes(boxes) {
    const layoutBoxes = [];
    let i2, ilen, box, pos, stack, stackWeight;
    for (i2 = 0, ilen = (boxes || []).length; i2 < ilen; ++i2) {
      box = boxes[i2];
      ({ position: pos, options: { stack, stackWeight = 1 } } = box);
      layoutBoxes.push({
        index: i2,
        box,
        pos,
        horizontal: box.isHorizontal(),
        weight: box.weight,
        stack: stack && pos + stack,
        stackWeight
      });
    }
    return layoutBoxes;
  }
  function buildStacks(layouts2) {
    const stacks = {};
    for (const wrap of layouts2) {
      const { stack, pos, stackWeight } = wrap;
      if (!stack || !STATIC_POSITIONS.includes(pos)) {
        continue;
      }
      const _stack = stacks[stack] || (stacks[stack] = { count: 0, placed: 0, weight: 0, size: 0 });
      _stack.count++;
      _stack.weight += stackWeight;
    }
    return stacks;
  }
  function setLayoutDims(layouts2, params) {
    const stacks = buildStacks(layouts2);
    const { vBoxMaxWidth, hBoxMaxHeight } = params;
    let i2, ilen, layout;
    for (i2 = 0, ilen = layouts2.length; i2 < ilen; ++i2) {
      layout = layouts2[i2];
      const { fullSize } = layout.box;
      const stack = stacks[layout.stack];
      const factor = stack && layout.stackWeight / stack.weight;
      if (layout.horizontal) {
        layout.width = factor ? factor * vBoxMaxWidth : fullSize && params.availableWidth;
        layout.height = hBoxMaxHeight;
      } else {
        layout.width = vBoxMaxWidth;
        layout.height = factor ? factor * hBoxMaxHeight : fullSize && params.availableHeight;
      }
    }
    return stacks;
  }
  function buildLayoutBoxes(boxes) {
    const layoutBoxes = wrapBoxes(boxes);
    const fullSize = sortByWeight(layoutBoxes.filter((wrap) => wrap.box.fullSize), true);
    const left2 = sortByWeight(filterByPosition(layoutBoxes, "left"), true);
    const right2 = sortByWeight(filterByPosition(layoutBoxes, "right"));
    const top2 = sortByWeight(filterByPosition(layoutBoxes, "top"), true);
    const bottom2 = sortByWeight(filterByPosition(layoutBoxes, "bottom"));
    const centerHorizontal = filterDynamicPositionByAxis(layoutBoxes, "x");
    const centerVertical = filterDynamicPositionByAxis(layoutBoxes, "y");
    return {
      fullSize,
      leftAndTop: left2.concat(top2),
      rightAndBottom: right2.concat(centerVertical).concat(bottom2).concat(centerHorizontal),
      chartArea: filterByPosition(layoutBoxes, "chartArea"),
      vertical: left2.concat(right2).concat(centerVertical),
      horizontal: top2.concat(bottom2).concat(centerHorizontal)
    };
  }
  function getCombinedMax(maxPadding, chartArea, a2, b2) {
    return Math.max(maxPadding[a2], chartArea[a2]) + Math.max(maxPadding[b2], chartArea[b2]);
  }
  function updateMaxPadding(maxPadding, boxPadding) {
    maxPadding.top = Math.max(maxPadding.top, boxPadding.top);
    maxPadding.left = Math.max(maxPadding.left, boxPadding.left);
    maxPadding.bottom = Math.max(maxPadding.bottom, boxPadding.bottom);
    maxPadding.right = Math.max(maxPadding.right, boxPadding.right);
  }
  function updateDims(chartArea, params, layout, stacks) {
    const { pos, box } = layout;
    const maxPadding = chartArea.maxPadding;
    if (!isObject(pos)) {
      if (layout.size) {
        chartArea[pos] -= layout.size;
      }
      const stack = stacks[layout.stack] || { size: 0, count: 1 };
      stack.size = Math.max(stack.size, layout.horizontal ? box.height : box.width);
      layout.size = stack.size / stack.count;
      chartArea[pos] += layout.size;
    }
    if (box.getPadding) {
      updateMaxPadding(maxPadding, box.getPadding());
    }
    const newWidth = Math.max(0, params.outerWidth - getCombinedMax(maxPadding, chartArea, "left", "right"));
    const newHeight = Math.max(0, params.outerHeight - getCombinedMax(maxPadding, chartArea, "top", "bottom"));
    const widthChanged = newWidth !== chartArea.w;
    const heightChanged = newHeight !== chartArea.h;
    chartArea.w = newWidth;
    chartArea.h = newHeight;
    return layout.horizontal ? { same: widthChanged, other: heightChanged } : { same: heightChanged, other: widthChanged };
  }
  function handleMaxPadding(chartArea) {
    const maxPadding = chartArea.maxPadding;
    function updatePos(pos) {
      const change = Math.max(maxPadding[pos] - chartArea[pos], 0);
      chartArea[pos] += change;
      return change;
    }
    chartArea.y += updatePos("top");
    chartArea.x += updatePos("left");
    updatePos("right");
    updatePos("bottom");
  }
  function getMargins(horizontal, chartArea) {
    const maxPadding = chartArea.maxPadding;
    function marginForPositions(positions2) {
      const margin = { left: 0, top: 0, right: 0, bottom: 0 };
      positions2.forEach((pos) => {
        margin[pos] = Math.max(chartArea[pos], maxPadding[pos]);
      });
      return margin;
    }
    return horizontal ? marginForPositions(["left", "right"]) : marginForPositions(["top", "bottom"]);
  }
  function fitBoxes(boxes, chartArea, params, stacks) {
    const refitBoxes = [];
    let i2, ilen, layout, box, refit, changed;
    for (i2 = 0, ilen = boxes.length, refit = 0; i2 < ilen; ++i2) {
      layout = boxes[i2];
      box = layout.box;
      box.update(layout.width || chartArea.w, layout.height || chartArea.h, getMargins(layout.horizontal, chartArea));
      const { same, other } = updateDims(chartArea, params, layout, stacks);
      refit |= same && refitBoxes.length;
      changed = changed || other;
      if (!box.fullSize) {
        refitBoxes.push(layout);
      }
    }
    return refit && fitBoxes(refitBoxes, chartArea, params, stacks) || changed;
  }
  function setBoxDims(box, left2, top2, width, height) {
    box.top = top2;
    box.left = left2;
    box.right = left2 + width;
    box.bottom = top2 + height;
    box.width = width;
    box.height = height;
  }
  function placeBoxes(boxes, chartArea, params, stacks) {
    const userPadding = params.padding;
    let { x: x2, y: y2 } = chartArea;
    for (const layout of boxes) {
      const box = layout.box;
      const stack = stacks[layout.stack] || { count: 1, placed: 0, weight: 1 };
      const weight = layout.stackWeight / stack.weight || 1;
      if (layout.horizontal) {
        const width = chartArea.w * weight;
        const height = stack.size || box.height;
        if (defined(stack.start)) {
          y2 = stack.start;
        }
        if (box.fullSize) {
          setBoxDims(box, userPadding.left, y2, params.outerWidth - userPadding.right - userPadding.left, height);
        } else {
          setBoxDims(box, chartArea.left + stack.placed, y2, width, height);
        }
        stack.start = y2;
        stack.placed += width;
        y2 = box.bottom;
      } else {
        const height = chartArea.h * weight;
        const width = stack.size || box.width;
        if (defined(stack.start)) {
          x2 = stack.start;
        }
        if (box.fullSize) {
          setBoxDims(box, x2, userPadding.top, width, params.outerHeight - userPadding.bottom - userPadding.top);
        } else {
          setBoxDims(box, x2, chartArea.top + stack.placed, width, height);
        }
        stack.start = x2;
        stack.placed += height;
        x2 = box.right;
      }
    }
    chartArea.x = x2;
    chartArea.y = y2;
  }
  defaults.set("layout", {
    padding: {
      top: 0,
      right: 0,
      bottom: 0,
      left: 0
    }
  });
  var layouts = {
    addBox(chart, item) {
      if (!chart.boxes) {
        chart.boxes = [];
      }
      item.fullSize = item.fullSize || false;
      item.position = item.position || "top";
      item.weight = item.weight || 0;
      item._layers = item._layers || function() {
        return [{
          z: 0,
          draw(chartArea) {
            item.draw(chartArea);
          }
        }];
      };
      chart.boxes.push(item);
    },
    removeBox(chart, layoutItem) {
      const index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1;
      if (index !== -1) {
        chart.boxes.splice(index, 1);
      }
    },
    configure(chart, item, options) {
      item.fullSize = options.fullSize;
      item.position = options.position;
      item.weight = options.weight;
    },
    update(chart, width, height, minPadding) {
      if (!chart) {
        return;
      }
      const padding = toPadding(chart.options.layout.padding);
      const availableWidth = Math.max(width - padding.width, 0);
      const availableHeight = Math.max(height - padding.height, 0);
      const boxes = buildLayoutBoxes(chart.boxes);
      const verticalBoxes = boxes.vertical;
      const horizontalBoxes = boxes.horizontal;
      each(chart.boxes, (box) => {
        if (typeof box.beforeLayout === "function") {
          box.beforeLayout();
        }
      });
      const visibleVerticalBoxCount = verticalBoxes.reduce((total, wrap) => wrap.box.options && wrap.box.options.display === false ? total : total + 1, 0) || 1;
      const params = Object.freeze({
        outerWidth: width,
        outerHeight: height,
        padding,
        availableWidth,
        availableHeight,
        vBoxMaxWidth: availableWidth / 2 / visibleVerticalBoxCount,
        hBoxMaxHeight: availableHeight / 2
      });
      const maxPadding = Object.assign({}, padding);
      updateMaxPadding(maxPadding, toPadding(minPadding));
      const chartArea = Object.assign({
        maxPadding,
        w: availableWidth,
        h: availableHeight,
        x: padding.left,
        y: padding.top
      }, padding);
      const stacks = setLayoutDims(verticalBoxes.concat(horizontalBoxes), params);
      fitBoxes(boxes.fullSize, chartArea, params, stacks);
      fitBoxes(verticalBoxes, chartArea, params, stacks);
      if (fitBoxes(horizontalBoxes, chartArea, params, stacks)) {
        fitBoxes(verticalBoxes, chartArea, params, stacks);
      }
      handleMaxPadding(chartArea);
      placeBoxes(boxes.leftAndTop, chartArea, params, stacks);
      chartArea.x += chartArea.w;
      chartArea.y += chartArea.h;
      placeBoxes(boxes.rightAndBottom, chartArea, params, stacks);
      chart.chartArea = {
        left: chartArea.left,
        top: chartArea.top,
        right: chartArea.left + chartArea.w,
        bottom: chartArea.top + chartArea.h,
        height: chartArea.h,
        width: chartArea.w
      };
      each(boxes.chartArea, (layout) => {
        const box = layout.box;
        Object.assign(box, chart.chartArea);
        box.update(chartArea.w, chartArea.h);
      });
    }
  };
  var BasePlatform = class {
    acquireContext(canvas, aspectRatio) {
    }
    releaseContext(context) {
      return false;
    }
    addEventListener(chart, type, listener) {
    }
    removeEventListener(chart, type, listener) {
    }
    getDevicePixelRatio() {
      return 1;
    }
    getMaximumSize(element, width, height, aspectRatio) {
      width = Math.max(0, width || element.width);
      height = height || element.height;
      return {
        width,
        height: Math.max(0, aspectRatio ? Math.floor(width / aspectRatio) : height)
      };
    }
    isAttached(canvas) {
      return true;
    }
  };
  var BasicPlatform = class extends BasePlatform {
    acquireContext(item) {
      return item && item.getContext && item.getContext("2d") || null;
    }
  };
  var EXPANDO_KEY = "$chartjs";
  var EVENT_TYPES = {
    touchstart: "mousedown",
    touchmove: "mousemove",
    touchend: "mouseup",
    pointerenter: "mouseenter",
    pointerdown: "mousedown",
    pointermove: "mousemove",
    pointerup: "mouseup",
    pointerleave: "mouseout",
    pointerout: "mouseout"
  };
  var isNullOrEmpty = (value) => value === null || value === "";
  function initCanvas(canvas, aspectRatio) {
    const style = canvas.style;
    const renderHeight = canvas.getAttribute("height");
    const renderWidth = canvas.getAttribute("width");
    canvas[EXPANDO_KEY] = {
      initial: {
        height: renderHeight,
        width: renderWidth,
        style: {
          display: style.display,
          height: style.height,
          width: style.width
        }
      }
    };
    style.display = style.display || "block";
    style.boxSizing = style.boxSizing || "border-box";
    if (isNullOrEmpty(renderWidth)) {
      const displayWidth = readUsedSize(canvas, "width");
      if (displayWidth !== void 0) {
        canvas.width = displayWidth;
      }
    }
    if (isNullOrEmpty(renderHeight)) {
      if (canvas.style.height === "") {
        canvas.height = canvas.width / (aspectRatio || 2);
      } else {
        const displayHeight = readUsedSize(canvas, "height");
        if (displayHeight !== void 0) {
          canvas.height = displayHeight;
        }
      }
    }
    return canvas;
  }
  var eventListenerOptions = supportsEventListenerOptions ? { passive: true } : false;
  function addListener(node, type, listener) {
    node.addEventListener(type, listener, eventListenerOptions);
  }
  function removeListener(chart, type, listener) {
    chart.canvas.removeEventListener(type, listener, eventListenerOptions);
  }
  function fromNativeEvent(event, chart) {
    const type = EVENT_TYPES[event.type] || event.type;
    const { x: x2, y: y2 } = getRelativePosition(event, chart);
    return {
      type,
      chart,
      native: event,
      x: x2 !== void 0 ? x2 : null,
      y: y2 !== void 0 ? y2 : null
    };
  }
  function createAttachObserver(chart, type, listener) {
    const canvas = chart.canvas;
    const container = canvas && _getParentNode(canvas);
    const element = container || canvas;
    const observer = new MutationObserver((entries) => {
      const parent = _getParentNode(element);
      entries.forEach((entry) => {
        for (let i2 = 0; i2 < entry.addedNodes.length; i2++) {
          const added = entry.addedNodes[i2];
          if (added === element || added === parent) {
            listener(entry.target);
          }
        }
      });
    });
    observer.observe(document, { childList: true, subtree: true });
    return observer;
  }
  function createDetachObserver(chart, type, listener) {
    const canvas = chart.canvas;
    const container = canvas && _getParentNode(canvas);
    if (!container) {
      return;
    }
    const observer = new MutationObserver((entries) => {
      entries.forEach((entry) => {
        for (let i2 = 0; i2 < entry.removedNodes.length; i2++) {
          if (entry.removedNodes[i2] === canvas) {
            listener();
            break;
          }
        }
      });
    });
    observer.observe(container, { childList: true });
    return observer;
  }
  var drpListeningCharts = /* @__PURE__ */ new Map();
  var oldDevicePixelRatio = 0;
  function onWindowResize() {
    const dpr = window.devicePixelRatio;
    if (dpr === oldDevicePixelRatio) {
      return;
    }
    oldDevicePixelRatio = dpr;
    drpListeningCharts.forEach((resize, chart) => {
      if (chart.currentDevicePixelRatio !== dpr) {
        resize();
      }
    });
  }
  function listenDevicePixelRatioChanges(chart, resize) {
    if (!drpListeningCharts.size) {
      window.addEventListener("resize", onWindowResize);
    }
    drpListeningCharts.set(chart, resize);
  }
  function unlistenDevicePixelRatioChanges(chart) {
    drpListeningCharts.delete(chart);
    if (!drpListeningCharts.size) {
      window.removeEventListener("resize", onWindowResize);
    }
  }
  function createResizeObserver(chart, type, listener) {
    const canvas = chart.canvas;
    const container = canvas && _getParentNode(canvas);
    if (!container) {
      return;
    }
    const resize = throttled((width, height) => {
      const w2 = container.clientWidth;
      listener(width, height);
      if (w2 < container.clientWidth) {
        listener();
      }
    }, window);
    const observer = new ResizeObserver((entries) => {
      const entry = entries[0];
      const width = entry.contentRect.width;
      const height = entry.contentRect.height;
      if (width === 0 && height === 0) {
        return;
      }
      resize(width, height);
    });
    observer.observe(container);
    listenDevicePixelRatioChanges(chart, resize);
    return observer;
  }
  function releaseObserver(chart, type, observer) {
    if (observer) {
      observer.disconnect();
    }
    if (type === "resize") {
      unlistenDevicePixelRatioChanges(chart);
    }
  }
  function createProxyAndListen(chart, type, listener) {
    const canvas = chart.canvas;
    const proxy = throttled((event) => {
      if (chart.ctx !== null) {
        listener(fromNativeEvent(event, chart));
      }
    }, chart, (args) => {
      const event = args[0];
      return [event, event.offsetX, event.offsetY];
    });
    addListener(canvas, type, proxy);
    return proxy;
  }
  var DomPlatform = class extends BasePlatform {
    acquireContext(canvas, aspectRatio) {
      const context = canvas && canvas.getContext && canvas.getContext("2d");
      if (context && context.canvas === canvas) {
        initCanvas(canvas, aspectRatio);
        return context;
      }
      return null;
    }
    releaseContext(context) {
      const canvas = context.canvas;
      if (!canvas[EXPANDO_KEY]) {
        return false;
      }
      const initial = canvas[EXPANDO_KEY].initial;
      ["height", "width"].forEach((prop) => {
        const value = initial[prop];
        if (isNullOrUndef(value)) {
          canvas.removeAttribute(prop);
        } else {
          canvas.setAttribute(prop, value);
        }
      });
      const style = initial.style || {};
      Object.keys(style).forEach((key) => {
        canvas.style[key] = style[key];
      });
      canvas.width = canvas.width;
      delete canvas[EXPANDO_KEY];
      return true;
    }
    addEventListener(chart, type, listener) {
      this.removeEventListener(chart, type);
      const proxies = chart.$proxies || (chart.$proxies = {});
      const handlers = {
        attach: createAttachObserver,
        detach: createDetachObserver,
        resize: createResizeObserver
      };
      const handler = handlers[type] || createProxyAndListen;
      proxies[type] = handler(chart, type, listener);
    }
    removeEventListener(chart, type) {
      const proxies = chart.$proxies || (chart.$proxies = {});
      const proxy = proxies[type];
      if (!proxy) {
        return;
      }
      const handlers = {
        attach: releaseObserver,
        detach: releaseObserver,
        resize: releaseObserver
      };
      const handler = handlers[type] || removeListener;
      handler(chart, type, proxy);
      proxies[type] = void 0;
    }
    getDevicePixelRatio() {
      return window.devicePixelRatio;
    }
    getMaximumSize(canvas, width, height, aspectRatio) {
      return getMaximumSize(canvas, width, height, aspectRatio);
    }
    isAttached(canvas) {
      const container = _getParentNode(canvas);
      return !!(container && container.isConnected);
    }
  };
  function _detectPlatform(canvas) {
    if (!_isDomSupported() || typeof OffscreenCanvas !== "undefined" && canvas instanceof OffscreenCanvas) {
      return BasicPlatform;
    }
    return DomPlatform;
  }
  var Element2 = class {
    constructor() {
      this.x = void 0;
      this.y = void 0;
      this.active = false;
      this.options = void 0;
      this.$animations = void 0;
    }
    tooltipPosition(useFinalPosition) {
      const { x: x2, y: y2 } = this.getProps(["x", "y"], useFinalPosition);
      return { x: x2, y: y2 };
    }
    hasValue() {
      return isNumber(this.x) && isNumber(this.y);
    }
    getProps(props, final) {
      const me2 = this;
      const anims = this.$animations;
      if (!final || !anims) {
        return me2;
      }
      const ret = {};
      props.forEach((prop) => {
        ret[prop] = anims[prop] && anims[prop].active() ? anims[prop]._to : me2[prop];
      });
      return ret;
    }
  };
  Element2.defaults = {};
  Element2.defaultRoutes = void 0;
  var formatters = {
    values(value) {
      return isArray(value) ? value : "" + value;
    },
    numeric(tickValue, index, ticks) {
      if (tickValue === 0) {
        return "0";
      }
      const locale2 = this.chart.options.locale;
      let notation;
      let delta = tickValue;
      if (ticks.length > 1) {
        const maxTick = Math.max(Math.abs(ticks[0].value), Math.abs(ticks[ticks.length - 1].value));
        if (maxTick < 1e-4 || maxTick > 1e15) {
          notation = "scientific";
        }
        delta = calculateDelta(tickValue, ticks);
      }
      const logDelta = log10(Math.abs(delta));
      const numDecimal = Math.max(Math.min(-1 * Math.floor(logDelta), 20), 0);
      const options = { notation, minimumFractionDigits: numDecimal, maximumFractionDigits: numDecimal };
      Object.assign(options, this.options.ticks.format);
      return formatNumber(tickValue, locale2, options);
    },
    logarithmic(tickValue, index, ticks) {
      if (tickValue === 0) {
        return "0";
      }
      const remain = tickValue / Math.pow(10, Math.floor(log10(tickValue)));
      if (remain === 1 || remain === 2 || remain === 5) {
        return formatters.numeric.call(this, tickValue, index, ticks);
      }
      return "";
    }
  };
  function calculateDelta(tickValue, ticks) {
    let delta = ticks.length > 3 ? ticks[2].value - ticks[1].value : ticks[1].value - ticks[0].value;
    if (Math.abs(delta) >= 1 && tickValue !== Math.floor(tickValue)) {
      delta = tickValue - Math.floor(tickValue);
    }
    return delta;
  }
  var Ticks = { formatters };
  defaults.set("scale", {
    display: true,
    offset: false,
    reverse: false,
    beginAtZero: false,
    bounds: "ticks",
    grace: 0,
    grid: {
      display: true,
      lineWidth: 1,
      drawBorder: true,
      drawOnChartArea: true,
      drawTicks: true,
      tickLength: 8,
      tickWidth: (_ctx, options) => options.lineWidth,
      tickColor: (_ctx, options) => options.color,
      offset: false,
      borderDash: [],
      borderDashOffset: 0,
      borderWidth: 1
    },
    title: {
      display: false,
      text: "",
      padding: {
        top: 4,
        bottom: 4
      }
    },
    ticks: {
      minRotation: 0,
      maxRotation: 50,
      mirror: false,
      textStrokeWidth: 0,
      textStrokeColor: "",
      padding: 3,
      display: true,
      autoSkip: true,
      autoSkipPadding: 3,
      labelOffset: 0,
      callback: Ticks.formatters.values,
      minor: {},
      major: {},
      align: "center",
      crossAlign: "near",
      showLabelBackdrop: false,
      backdropColor: "rgba(255, 255, 255, 0.75)",
      backdropPadding: 2
    }
  });
  defaults.route("scale.ticks", "color", "", "color");
  defaults.route("scale.grid", "color", "", "borderColor");
  defaults.route("scale.grid", "borderColor", "", "borderColor");
  defaults.route("scale.title", "color", "", "color");
  defaults.describe("scale", {
    _fallback: false,
    _scriptable: (name) => !name.startsWith("before") && !name.startsWith("after") && name !== "callback" && name !== "parser",
    _indexable: (name) => name !== "borderDash" && name !== "tickBorderDash"
  });
  defaults.describe("scales", {
    _fallback: "scale"
  });
  defaults.describe("scale.ticks", {
    _scriptable: (name) => name !== "backdropPadding" && name !== "callback",
    _indexable: (name) => name !== "backdropPadding"
  });
  function autoSkip(scale, ticks) {
    const tickOpts = scale.options.ticks;
    const ticksLimit = tickOpts.maxTicksLimit || determineMaxTicks(scale);
    const majorIndices = tickOpts.major.enabled ? getMajorIndices(ticks) : [];
    const numMajorIndices = majorIndices.length;
    const first = majorIndices[0];
    const last = majorIndices[numMajorIndices - 1];
    const newTicks = [];
    if (numMajorIndices > ticksLimit) {
      skipMajors(ticks, newTicks, majorIndices, numMajorIndices / ticksLimit);
      return newTicks;
    }
    const spacing = calculateSpacing(majorIndices, ticks, ticksLimit);
    if (numMajorIndices > 0) {
      let i2, ilen;
      const avgMajorSpacing = numMajorIndices > 1 ? Math.round((last - first) / (numMajorIndices - 1)) : null;
      skip(ticks, newTicks, spacing, isNullOrUndef(avgMajorSpacing) ? 0 : first - avgMajorSpacing, first);
      for (i2 = 0, ilen = numMajorIndices - 1; i2 < ilen; i2++) {
        skip(ticks, newTicks, spacing, majorIndices[i2], majorIndices[i2 + 1]);
      }
      skip(ticks, newTicks, spacing, last, isNullOrUndef(avgMajorSpacing) ? ticks.length : last + avgMajorSpacing);
      return newTicks;
    }
    skip(ticks, newTicks, spacing);
    return newTicks;
  }
  function determineMaxTicks(scale) {
    const offset2 = scale.options.offset;
    const tickLength = scale._tickSize();
    const maxScale = scale._length / tickLength + (offset2 ? 0 : 1);
    const maxChart = scale._maxLength / tickLength;
    return Math.floor(Math.min(maxScale, maxChart));
  }
  function calculateSpacing(majorIndices, ticks, ticksLimit) {
    const evenMajorSpacing = getEvenSpacing(majorIndices);
    const spacing = ticks.length / ticksLimit;
    if (!evenMajorSpacing) {
      return Math.max(spacing, 1);
    }
    const factors = _factorize(evenMajorSpacing);
    for (let i2 = 0, ilen = factors.length - 1; i2 < ilen; i2++) {
      const factor = factors[i2];
      if (factor > spacing) {
        return factor;
      }
    }
    return Math.max(spacing, 1);
  }
  function getMajorIndices(ticks) {
    const result = [];
    let i2, ilen;
    for (i2 = 0, ilen = ticks.length; i2 < ilen; i2++) {
      if (ticks[i2].major) {
        result.push(i2);
      }
    }
    return result;
  }
  function skipMajors(ticks, newTicks, majorIndices, spacing) {
    let count = 0;
    let next = majorIndices[0];
    let i2;
    spacing = Math.ceil(spacing);
    for (i2 = 0; i2 < ticks.length; i2++) {
      if (i2 === next) {
        newTicks.push(ticks[i2]);
        count++;
        next = majorIndices[count * spacing];
      }
    }
  }
  function skip(ticks, newTicks, spacing, majorStart, majorEnd) {
    const start4 = valueOrDefault(majorStart, 0);
    const end2 = Math.min(valueOrDefault(majorEnd, ticks.length), ticks.length);
    let count = 0;
    let length, i2, next;
    spacing = Math.ceil(spacing);
    if (majorEnd) {
      length = majorEnd - majorStart;
      spacing = length / Math.floor(length / spacing);
    }
    next = start4;
    while (next < 0) {
      count++;
      next = Math.round(start4 + count * spacing);
    }
    for (i2 = Math.max(start4, 0); i2 < end2; i2++) {
      if (i2 === next) {
        newTicks.push(ticks[i2]);
        count++;
        next = Math.round(start4 + count * spacing);
      }
    }
  }
  function getEvenSpacing(arr) {
    const len = arr.length;
    let i2, diff;
    if (len < 2) {
      return false;
    }
    for (diff = arr[0], i2 = 1; i2 < len; ++i2) {
      if (arr[i2] - arr[i2 - 1] !== diff) {
        return false;
      }
    }
    return diff;
  }
  var reverseAlign = (align) => align === "left" ? "right" : align === "right" ? "left" : align;
  var offsetFromEdge = (scale, edge, offset2) => edge === "top" || edge === "left" ? scale[edge] + offset2 : scale[edge] - offset2;
  function sample(arr, numItems) {
    const result = [];
    const increment = arr.length / numItems;
    const len = arr.length;
    let i2 = 0;
    for (; i2 < len; i2 += increment) {
      result.push(arr[Math.floor(i2)]);
    }
    return result;
  }
  function getPixelForGridLine(scale, index, offsetGridLines) {
    const length = scale.ticks.length;
    const validIndex2 = Math.min(index, length - 1);
    const start4 = scale._startPixel;
    const end2 = scale._endPixel;
    const epsilon = 1e-6;
    let lineValue = scale.getPixelForTick(validIndex2);
    let offset2;
    if (offsetGridLines) {
      if (length === 1) {
        offset2 = Math.max(lineValue - start4, end2 - lineValue);
      } else if (index === 0) {
        offset2 = (scale.getPixelForTick(1) - lineValue) / 2;
      } else {
        offset2 = (lineValue - scale.getPixelForTick(validIndex2 - 1)) / 2;
      }
      lineValue += validIndex2 < index ? offset2 : -offset2;
      if (lineValue < start4 - epsilon || lineValue > end2 + epsilon) {
        return;
      }
    }
    return lineValue;
  }
  function garbageCollect(caches, length) {
    each(caches, (cache2) => {
      const gc = cache2.gc;
      const gcLen = gc.length / 2;
      let i2;
      if (gcLen > length) {
        for (i2 = 0; i2 < gcLen; ++i2) {
          delete cache2.data[gc[i2]];
        }
        gc.splice(0, gcLen);
      }
    });
  }
  function getTickMarkLength(options) {
    return options.drawTicks ? options.tickLength : 0;
  }
  function getTitleHeight(options, fallback) {
    if (!options.display) {
      return 0;
    }
    const font = toFont(options.font, fallback);
    const padding = toPadding(options.padding);
    const lines = isArray(options.text) ? options.text.length : 1;
    return lines * font.lineHeight + padding.height;
  }
  function createScaleContext(parent, scale) {
    return Object.assign(Object.create(parent), {
      scale,
      type: "scale"
    });
  }
  function createTickContext(parent, index, tick) {
    return Object.assign(Object.create(parent), {
      tick,
      index,
      type: "tick"
    });
  }
  function titleAlign(align, position, reverse) {
    let ret = _toLeftRightCenter(align);
    if (reverse && position !== "right" || !reverse && position === "right") {
      ret = reverseAlign(ret);
    }
    return ret;
  }
  function titleArgs(scale, offset2, position, align) {
    const { top: top2, left: left2, bottom: bottom2, right: right2, chart } = scale;
    const { chartArea, scales: scales2 } = chart;
    let rotation = 0;
    let maxWidth, titleX, titleY;
    const height = bottom2 - top2;
    const width = right2 - left2;
    if (scale.isHorizontal()) {
      titleX = _alignStartEnd(align, left2, right2);
      if (isObject(position)) {
        const positionAxisID = Object.keys(position)[0];
        const value = position[positionAxisID];
        titleY = scales2[positionAxisID].getPixelForValue(value) + height - offset2;
      } else if (position === "center") {
        titleY = (chartArea.bottom + chartArea.top) / 2 + height - offset2;
      } else {
        titleY = offsetFromEdge(scale, position, offset2);
      }
      maxWidth = right2 - left2;
    } else {
      if (isObject(position)) {
        const positionAxisID = Object.keys(position)[0];
        const value = position[positionAxisID];
        titleX = scales2[positionAxisID].getPixelForValue(value) - width + offset2;
      } else if (position === "center") {
        titleX = (chartArea.left + chartArea.right) / 2 - width + offset2;
      } else {
        titleX = offsetFromEdge(scale, position, offset2);
      }
      titleY = _alignStartEnd(align, bottom2, top2);
      rotation = position === "left" ? -HALF_PI : HALF_PI;
    }
    return { titleX, titleY, maxWidth, rotation };
  }
  var Scale = class extends Element2 {
    constructor(cfg) {
      super();
      this.id = cfg.id;
      this.type = cfg.type;
      this.options = void 0;
      this.ctx = cfg.ctx;
      this.chart = cfg.chart;
      this.top = void 0;
      this.bottom = void 0;
      this.left = void 0;
      this.right = void 0;
      this.width = void 0;
      this.height = void 0;
      this._margins = {
        left: 0,
        right: 0,
        top: 0,
        bottom: 0
      };
      this.maxWidth = void 0;
      this.maxHeight = void 0;
      this.paddingTop = void 0;
      this.paddingBottom = void 0;
      this.paddingLeft = void 0;
      this.paddingRight = void 0;
      this.axis = void 0;
      this.labelRotation = void 0;
      this.min = void 0;
      this.max = void 0;
      this._range = void 0;
      this.ticks = [];
      this._gridLineItems = null;
      this._labelItems = null;
      this._labelSizes = null;
      this._length = 0;
      this._maxLength = 0;
      this._longestTextCache = {};
      this._startPixel = void 0;
      this._endPixel = void 0;
      this._reversePixels = false;
      this._userMax = void 0;
      this._userMin = void 0;
      this._suggestedMax = void 0;
      this._suggestedMin = void 0;
      this._ticksLength = 0;
      this._borderValue = 0;
      this._cache = {};
      this._dataLimitsCached = false;
      this.$context = void 0;
    }
    init(options) {
      const me2 = this;
      me2.options = options.setContext(me2.getContext());
      me2.axis = options.axis;
      me2._userMin = me2.parse(options.min);
      me2._userMax = me2.parse(options.max);
      me2._suggestedMin = me2.parse(options.suggestedMin);
      me2._suggestedMax = me2.parse(options.suggestedMax);
    }
    parse(raw, index) {
      return raw;
    }
    getUserBounds() {
      let { _userMin, _userMax, _suggestedMin, _suggestedMax } = this;
      _userMin = finiteOrDefault(_userMin, Number.POSITIVE_INFINITY);
      _userMax = finiteOrDefault(_userMax, Number.NEGATIVE_INFINITY);
      _suggestedMin = finiteOrDefault(_suggestedMin, Number.POSITIVE_INFINITY);
      _suggestedMax = finiteOrDefault(_suggestedMax, Number.NEGATIVE_INFINITY);
      return {
        min: finiteOrDefault(_userMin, _suggestedMin),
        max: finiteOrDefault(_userMax, _suggestedMax),
        minDefined: isNumberFinite(_userMin),
        maxDefined: isNumberFinite(_userMax)
      };
    }
    getMinMax(canStack) {
      const me2 = this;
      let { min: min2, max: max2, minDefined, maxDefined } = me2.getUserBounds();
      let range;
      if (minDefined && maxDefined) {
        return { min: min2, max: max2 };
      }
      const metas = me2.getMatchingVisibleMetas();
      for (let i2 = 0, ilen = metas.length; i2 < ilen; ++i2) {
        range = metas[i2].controller.getMinMax(me2, canStack);
        if (!minDefined) {
          min2 = Math.min(min2, range.min);
        }
        if (!maxDefined) {
          max2 = Math.max(max2, range.max);
        }
      }
      return {
        min: finiteOrDefault(min2, finiteOrDefault(max2, min2)),
        max: finiteOrDefault(max2, finiteOrDefault(min2, max2))
      };
    }
    getPadding() {
      const me2 = this;
      return {
        left: me2.paddingLeft || 0,
        top: me2.paddingTop || 0,
        right: me2.paddingRight || 0,
        bottom: me2.paddingBottom || 0
      };
    }
    getTicks() {
      return this.ticks;
    }
    getLabels() {
      const data = this.chart.data;
      return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels || [];
    }
    beforeLayout() {
      this._cache = {};
      this._dataLimitsCached = false;
    }
    beforeUpdate() {
      callback(this.options.beforeUpdate, [this]);
    }
    update(maxWidth, maxHeight, margins) {
      const me2 = this;
      const tickOpts = me2.options.ticks;
      const sampleSize = tickOpts.sampleSize;
      me2.beforeUpdate();
      me2.maxWidth = maxWidth;
      me2.maxHeight = maxHeight;
      me2._margins = margins = Object.assign({
        left: 0,
        right: 0,
        top: 0,
        bottom: 0
      }, margins);
      me2.ticks = null;
      me2._labelSizes = null;
      me2._gridLineItems = null;
      me2._labelItems = null;
      me2.beforeSetDimensions();
      me2.setDimensions();
      me2.afterSetDimensions();
      me2._maxLength = me2.isHorizontal() ? me2.width + margins.left + margins.right : me2.height + margins.top + margins.bottom;
      if (!me2._dataLimitsCached) {
        me2.beforeDataLimits();
        me2.determineDataLimits();
        me2.afterDataLimits();
        me2._range = _addGrace(me2, me2.options.grace);
        me2._dataLimitsCached = true;
      }
      me2.beforeBuildTicks();
      me2.ticks = me2.buildTicks() || [];
      me2.afterBuildTicks();
      const samplingEnabled = sampleSize < me2.ticks.length;
      me2._convertTicksToLabels(samplingEnabled ? sample(me2.ticks, sampleSize) : me2.ticks);
      me2.configure();
      me2.beforeCalculateLabelRotation();
      me2.calculateLabelRotation();
      me2.afterCalculateLabelRotation();
      if (tickOpts.display && (tickOpts.autoSkip || tickOpts.source === "auto")) {
        me2.ticks = autoSkip(me2, me2.ticks);
        me2._labelSizes = null;
      }
      if (samplingEnabled) {
        me2._convertTicksToLabels(me2.ticks);
      }
      me2.beforeFit();
      me2.fit();
      me2.afterFit();
      me2.afterUpdate();
    }
    configure() {
      const me2 = this;
      let reversePixels = me2.options.reverse;
      let startPixel, endPixel;
      if (me2.isHorizontal()) {
        startPixel = me2.left;
        endPixel = me2.right;
      } else {
        startPixel = me2.top;
        endPixel = me2.bottom;
        reversePixels = !reversePixels;
      }
      me2._startPixel = startPixel;
      me2._endPixel = endPixel;
      me2._reversePixels = reversePixels;
      me2._length = endPixel - startPixel;
      me2._alignToPixels = me2.options.alignToPixels;
    }
    afterUpdate() {
      callback(this.options.afterUpdate, [this]);
    }
    beforeSetDimensions() {
      callback(this.options.beforeSetDimensions, [this]);
    }
    setDimensions() {
      const me2 = this;
      if (me2.isHorizontal()) {
        me2.width = me2.maxWidth;
        me2.left = 0;
        me2.right = me2.width;
      } else {
        me2.height = me2.maxHeight;
        me2.top = 0;
        me2.bottom = me2.height;
      }
      me2.paddingLeft = 0;
      me2.paddingTop = 0;
      me2.paddingRight = 0;
      me2.paddingBottom = 0;
    }
    afterSetDimensions() {
      callback(this.options.afterSetDimensions, [this]);
    }
    _callHooks(name) {
      const me2 = this;
      me2.chart.notifyPlugins(name, me2.getContext());
      callback(me2.options[name], [me2]);
    }
    beforeDataLimits() {
      this._callHooks("beforeDataLimits");
    }
    determineDataLimits() {
    }
    afterDataLimits() {
      this._callHooks("afterDataLimits");
    }
    beforeBuildTicks() {
      this._callHooks("beforeBuildTicks");
    }
    buildTicks() {
      return [];
    }
    afterBuildTicks() {
      this._callHooks("afterBuildTicks");
    }
    beforeTickToLabelConversion() {
      callback(this.options.beforeTickToLabelConversion, [this]);
    }
    generateTickLabels(ticks) {
      const me2 = this;
      const tickOpts = me2.options.ticks;
      let i2, ilen, tick;
      for (i2 = 0, ilen = ticks.length; i2 < ilen; i2++) {
        tick = ticks[i2];
        tick.label = callback(tickOpts.callback, [tick.value, i2, ticks], me2);
      }
    }
    afterTickToLabelConversion() {
      callback(this.options.afterTickToLabelConversion, [this]);
    }
    beforeCalculateLabelRotation() {
      callback(this.options.beforeCalculateLabelRotation, [this]);
    }
    calculateLabelRotation() {
      const me2 = this;
      const options = me2.options;
      const tickOpts = options.ticks;
      const numTicks = me2.ticks.length;
      const minRotation = tickOpts.minRotation || 0;
      const maxRotation = tickOpts.maxRotation;
      let labelRotation = minRotation;
      let tickWidth, maxHeight, maxLabelDiagonal;
      if (!me2._isVisible() || !tickOpts.display || minRotation >= maxRotation || numTicks <= 1 || !me2.isHorizontal()) {
        me2.labelRotation = minRotation;
        return;
      }
      const labelSizes = me2._getLabelSizes();
      const maxLabelWidth = labelSizes.widest.width;
      const maxLabelHeight = labelSizes.highest.height;
      const maxWidth = _limitValue(me2.chart.width - maxLabelWidth, 0, me2.maxWidth);
      tickWidth = options.offset ? me2.maxWidth / numTicks : maxWidth / (numTicks - 1);
      if (maxLabelWidth + 6 > tickWidth) {
        tickWidth = maxWidth / (numTicks - (options.offset ? 0.5 : 1));
        maxHeight = me2.maxHeight - getTickMarkLength(options.grid) - tickOpts.padding - getTitleHeight(options.title, me2.chart.options.font);
        maxLabelDiagonal = Math.sqrt(maxLabelWidth * maxLabelWidth + maxLabelHeight * maxLabelHeight);
        labelRotation = toDegrees(Math.min(Math.asin(_limitValue((labelSizes.highest.height + 6) / tickWidth, -1, 1)), Math.asin(_limitValue(maxHeight / maxLabelDiagonal, -1, 1)) - Math.asin(_limitValue(maxLabelHeight / maxLabelDiagonal, -1, 1))));
        labelRotation = Math.max(minRotation, Math.min(maxRotation, labelRotation));
      }
      me2.labelRotation = labelRotation;
    }
    afterCalculateLabelRotation() {
      callback(this.options.afterCalculateLabelRotation, [this]);
    }
    beforeFit() {
      callback(this.options.beforeFit, [this]);
    }
    fit() {
      const me2 = this;
      const minSize = {
        width: 0,
        height: 0
      };
      const { chart, options: { ticks: tickOpts, title: titleOpts, grid: gridOpts } } = me2;
      const display = me2._isVisible();
      const isHorizontal = me2.isHorizontal();
      if (display) {
        const titleHeight = getTitleHeight(titleOpts, chart.options.font);
        if (isHorizontal) {
          minSize.width = me2.maxWidth;
          minSize.height = getTickMarkLength(gridOpts) + titleHeight;
        } else {
          minSize.height = me2.maxHeight;
          minSize.width = getTickMarkLength(gridOpts) + titleHeight;
        }
        if (tickOpts.display && me2.ticks.length) {
          const { first, last, widest, highest } = me2._getLabelSizes();
          const tickPadding = tickOpts.padding * 2;
          const angleRadians = toRadians(me2.labelRotation);
          const cos = Math.cos(angleRadians);
          const sin = Math.sin(angleRadians);
          if (isHorizontal) {
            const labelHeight = tickOpts.mirror ? 0 : sin * widest.width + cos * highest.height;
            minSize.height = Math.min(me2.maxHeight, minSize.height + labelHeight + tickPadding);
          } else {
            const labelWidth = tickOpts.mirror ? 0 : cos * widest.width + sin * highest.height;
            minSize.width = Math.min(me2.maxWidth, minSize.width + labelWidth + tickPadding);
          }
          me2._calculatePadding(first, last, sin, cos);
        }
      }
      me2._handleMargins();
      if (isHorizontal) {
        me2.width = me2._length = chart.width - me2._margins.left - me2._margins.right;
        me2.height = minSize.height;
      } else {
        me2.width = minSize.width;
        me2.height = me2._length = chart.height - me2._margins.top - me2._margins.bottom;
      }
    }
    _calculatePadding(first, last, sin, cos) {
      const me2 = this;
      const { ticks: { align, padding }, position } = me2.options;
      const isRotated = me2.labelRotation !== 0;
      const labelsBelowTicks = position !== "top" && me2.axis === "x";
      if (me2.isHorizontal()) {
        const offsetLeft = me2.getPixelForTick(0) - me2.left;
        const offsetRight = me2.right - me2.getPixelForTick(me2.ticks.length - 1);
        let paddingLeft = 0;
        let paddingRight = 0;
        if (isRotated) {
          if (labelsBelowTicks) {
            paddingLeft = cos * first.width;
            paddingRight = sin * last.height;
          } else {
            paddingLeft = sin * first.height;
            paddingRight = cos * last.width;
          }
        } else if (align === "start") {
          paddingRight = last.width;
        } else if (align === "end") {
          paddingLeft = first.width;
        } else {
          paddingLeft = first.width / 2;
          paddingRight = last.width / 2;
        }
        me2.paddingLeft = Math.max((paddingLeft - offsetLeft + padding) * me2.width / (me2.width - offsetLeft), 0);
        me2.paddingRight = Math.max((paddingRight - offsetRight + padding) * me2.width / (me2.width - offsetRight), 0);
      } else {
        let paddingTop = last.height / 2;
        let paddingBottom = first.height / 2;
        if (align === "start") {
          paddingTop = 0;
          paddingBottom = first.height;
        } else if (align === "end") {
          paddingTop = last.height;
          paddingBottom = 0;
        }
        me2.paddingTop = paddingTop + padding;
        me2.paddingBottom = paddingBottom + padding;
      }
    }
    _handleMargins() {
      const me2 = this;
      if (me2._margins) {
        me2._margins.left = Math.max(me2.paddingLeft, me2._margins.left);
        me2._margins.top = Math.max(me2.paddingTop, me2._margins.top);
        me2._margins.right = Math.max(me2.paddingRight, me2._margins.right);
        me2._margins.bottom = Math.max(me2.paddingBottom, me2._margins.bottom);
      }
    }
    afterFit() {
      callback(this.options.afterFit, [this]);
    }
    isHorizontal() {
      const { axis, position } = this.options;
      return position === "top" || position === "bottom" || axis === "x";
    }
    isFullSize() {
      return this.options.fullSize;
    }
    _convertTicksToLabels(ticks) {
      const me2 = this;
      me2.beforeTickToLabelConversion();
      me2.generateTickLabels(ticks);
      let i2, ilen;
      for (i2 = 0, ilen = ticks.length; i2 < ilen; i2++) {
        if (isNullOrUndef(ticks[i2].label)) {
          ticks.splice(i2, 1);
          ilen--;
          i2--;
        }
      }
      me2.afterTickToLabelConversion();
    }
    _getLabelSizes() {
      const me2 = this;
      let labelSizes = me2._labelSizes;
      if (!labelSizes) {
        const sampleSize = me2.options.ticks.sampleSize;
        let ticks = me2.ticks;
        if (sampleSize < ticks.length) {
          ticks = sample(ticks, sampleSize);
        }
        me2._labelSizes = labelSizes = me2._computeLabelSizes(ticks, ticks.length);
      }
      return labelSizes;
    }
    _computeLabelSizes(ticks, length) {
      const { ctx, _longestTextCache: caches } = this;
      const widths = [];
      const heights = [];
      let widestLabelSize = 0;
      let highestLabelSize = 0;
      let i2, j2, jlen, label, tickFont, fontString, cache2, lineHeight, width, height, nestedLabel;
      for (i2 = 0; i2 < length; ++i2) {
        label = ticks[i2].label;
        tickFont = this._resolveTickFontOptions(i2);
        ctx.font = fontString = tickFont.string;
        cache2 = caches[fontString] = caches[fontString] || { data: {}, gc: [] };
        lineHeight = tickFont.lineHeight;
        width = height = 0;
        if (!isNullOrUndef(label) && !isArray(label)) {
          width = _measureText(ctx, cache2.data, cache2.gc, width, label);
          height = lineHeight;
        } else if (isArray(label)) {
          for (j2 = 0, jlen = label.length; j2 < jlen; ++j2) {
            nestedLabel = label[j2];
            if (!isNullOrUndef(nestedLabel) && !isArray(nestedLabel)) {
              width = _measureText(ctx, cache2.data, cache2.gc, width, nestedLabel);
              height += lineHeight;
            }
          }
        }
        widths.push(width);
        heights.push(height);
        widestLabelSize = Math.max(width, widestLabelSize);
        highestLabelSize = Math.max(height, highestLabelSize);
      }
      garbageCollect(caches, length);
      const widest = widths.indexOf(widestLabelSize);
      const highest = heights.indexOf(highestLabelSize);
      const valueAt = (idx) => ({ width: widths[idx] || 0, height: heights[idx] || 0 });
      return {
        first: valueAt(0),
        last: valueAt(length - 1),
        widest: valueAt(widest),
        highest: valueAt(highest),
        widths,
        heights
      };
    }
    getLabelForValue(value) {
      return value;
    }
    getPixelForValue(value, index) {
      return NaN;
    }
    getValueForPixel(pixel) {
    }
    getPixelForTick(index) {
      const ticks = this.ticks;
      if (index < 0 || index > ticks.length - 1) {
        return null;
      }
      return this.getPixelForValue(ticks[index].value);
    }
    getPixelForDecimal(decimal) {
      const me2 = this;
      if (me2._reversePixels) {
        decimal = 1 - decimal;
      }
      const pixel = me2._startPixel + decimal * me2._length;
      return _int16Range(me2._alignToPixels ? _alignPixel(me2.chart, pixel, 0) : pixel);
    }
    getDecimalForPixel(pixel) {
      const decimal = (pixel - this._startPixel) / this._length;
      return this._reversePixels ? 1 - decimal : decimal;
    }
    getBasePixel() {
      return this.getPixelForValue(this.getBaseValue());
    }
    getBaseValue() {
      const { min: min2, max: max2 } = this;
      return min2 < 0 && max2 < 0 ? max2 : min2 > 0 && max2 > 0 ? min2 : 0;
    }
    getContext(index) {
      const me2 = this;
      const ticks = me2.ticks || [];
      if (index >= 0 && index < ticks.length) {
        const tick = ticks[index];
        return tick.$context || (tick.$context = createTickContext(me2.getContext(), index, tick));
      }
      return me2.$context || (me2.$context = createScaleContext(me2.chart.getContext(), me2));
    }
    _tickSize() {
      const me2 = this;
      const optionTicks = me2.options.ticks;
      const rot = toRadians(me2.labelRotation);
      const cos = Math.abs(Math.cos(rot));
      const sin = Math.abs(Math.sin(rot));
      const labelSizes = me2._getLabelSizes();
      const padding = optionTicks.autoSkipPadding || 0;
      const w2 = labelSizes ? labelSizes.widest.width + padding : 0;
      const h3 = labelSizes ? labelSizes.highest.height + padding : 0;
      return me2.isHorizontal() ? h3 * cos > w2 * sin ? w2 / cos : h3 / sin : h3 * sin < w2 * cos ? h3 / cos : w2 / sin;
    }
    _isVisible() {
      const display = this.options.display;
      if (display !== "auto") {
        return !!display;
      }
      return this.getMatchingVisibleMetas().length > 0;
    }
    _computeGridLineItems(chartArea) {
      const me2 = this;
      const axis = me2.axis;
      const chart = me2.chart;
      const options = me2.options;
      const { grid, position } = options;
      const offset2 = grid.offset;
      const isHorizontal = me2.isHorizontal();
      const ticks = me2.ticks;
      const ticksLength = ticks.length + (offset2 ? 1 : 0);
      const tl = getTickMarkLength(grid);
      const items = [];
      const borderOpts = grid.setContext(me2.getContext());
      const axisWidth = borderOpts.drawBorder ? borderOpts.borderWidth : 0;
      const axisHalfWidth = axisWidth / 2;
      const alignBorderValue = function(pixel) {
        return _alignPixel(chart, pixel, axisWidth);
      };
      let borderValue, i2, lineValue, alignedLineValue;
      let tx1, ty1, tx2, ty2, x1, y1, x2, y2;
      if (position === "top") {
        borderValue = alignBorderValue(me2.bottom);
        ty1 = me2.bottom - tl;
        ty2 = borderValue - axisHalfWidth;
        y1 = alignBorderValue(chartArea.top) + axisHalfWidth;
        y2 = chartArea.bottom;
      } else if (position === "bottom") {
        borderValue = alignBorderValue(me2.top);
        y1 = chartArea.top;
        y2 = alignBorderValue(chartArea.bottom) - axisHalfWidth;
        ty1 = borderValue + axisHalfWidth;
        ty2 = me2.top + tl;
      } else if (position === "left") {
        borderValue = alignBorderValue(me2.right);
        tx1 = me2.right - tl;
        tx2 = borderValue - axisHalfWidth;
        x1 = alignBorderValue(chartArea.left) + axisHalfWidth;
        x2 = chartArea.right;
      } else if (position === "right") {
        borderValue = alignBorderValue(me2.left);
        x1 = chartArea.left;
        x2 = alignBorderValue(chartArea.right) - axisHalfWidth;
        tx1 = borderValue + axisHalfWidth;
        tx2 = me2.left + tl;
      } else if (axis === "x") {
        if (position === "center") {
          borderValue = alignBorderValue((chartArea.top + chartArea.bottom) / 2 + 0.5);
        } else if (isObject(position)) {
          const positionAxisID = Object.keys(position)[0];
          const value = position[positionAxisID];
          borderValue = alignBorderValue(me2.chart.scales[positionAxisID].getPixelForValue(value));
        }
        y1 = chartArea.top;
        y2 = chartArea.bottom;
        ty1 = borderValue + axisHalfWidth;
        ty2 = ty1 + tl;
      } else if (axis === "y") {
        if (position === "center") {
          borderValue = alignBorderValue((chartArea.left + chartArea.right) / 2);
        } else if (isObject(position)) {
          const positionAxisID = Object.keys(position)[0];
          const value = position[positionAxisID];
          borderValue = alignBorderValue(me2.chart.scales[positionAxisID].getPixelForValue(value));
        }
        tx1 = borderValue - axisHalfWidth;
        tx2 = tx1 - tl;
        x1 = chartArea.left;
        x2 = chartArea.right;
      }
      const limit = valueOrDefault(options.ticks.maxTicksLimit, ticksLength);
      const step = Math.max(1, Math.ceil(ticksLength / limit));
      for (i2 = 0; i2 < ticksLength; i2 += step) {
        const optsAtIndex = grid.setContext(me2.getContext(i2));
        const lineWidth = optsAtIndex.lineWidth;
        const lineColor = optsAtIndex.color;
        const borderDash = grid.borderDash || [];
        const borderDashOffset = optsAtIndex.borderDashOffset;
        const tickWidth = optsAtIndex.tickWidth;
        const tickColor = optsAtIndex.tickColor;
        const tickBorderDash = optsAtIndex.tickBorderDash || [];
        const tickBorderDashOffset = optsAtIndex.tickBorderDashOffset;
        lineValue = getPixelForGridLine(me2, i2, offset2);
        if (lineValue === void 0) {
          continue;
        }
        alignedLineValue = _alignPixel(chart, lineValue, lineWidth);
        if (isHorizontal) {
          tx1 = tx2 = x1 = x2 = alignedLineValue;
        } else {
          ty1 = ty2 = y1 = y2 = alignedLineValue;
        }
        items.push({
          tx1,
          ty1,
          tx2,
          ty2,
          x1,
          y1,
          x2,
          y2,
          width: lineWidth,
          color: lineColor,
          borderDash,
          borderDashOffset,
          tickWidth,
          tickColor,
          tickBorderDash,
          tickBorderDashOffset
        });
      }
      me2._ticksLength = ticksLength;
      me2._borderValue = borderValue;
      return items;
    }
    _computeLabelItems(chartArea) {
      const me2 = this;
      const axis = me2.axis;
      const options = me2.options;
      const { position, ticks: optionTicks } = options;
      const isHorizontal = me2.isHorizontal();
      const ticks = me2.ticks;
      const { align, crossAlign, padding, mirror } = optionTicks;
      const tl = getTickMarkLength(options.grid);
      const tickAndPadding = tl + padding;
      const hTickAndPadding = mirror ? -padding : tickAndPadding;
      const rotation = -toRadians(me2.labelRotation);
      const items = [];
      let i2, ilen, tick, label, x2, y2, textAlign, pixel, font, lineHeight, lineCount, textOffset;
      let textBaseline = "middle";
      if (position === "top") {
        y2 = me2.bottom - hTickAndPadding;
        textAlign = me2._getXAxisLabelAlignment();
      } else if (position === "bottom") {
        y2 = me2.top + hTickAndPadding;
        textAlign = me2._getXAxisLabelAlignment();
      } else if (position === "left") {
        const ret = me2._getYAxisLabelAlignment(tl);
        textAlign = ret.textAlign;
        x2 = ret.x;
      } else if (position === "right") {
        const ret = me2._getYAxisLabelAlignment(tl);
        textAlign = ret.textAlign;
        x2 = ret.x;
      } else if (axis === "x") {
        if (position === "center") {
          y2 = (chartArea.top + chartArea.bottom) / 2 + tickAndPadding;
        } else if (isObject(position)) {
          const positionAxisID = Object.keys(position)[0];
          const value = position[positionAxisID];
          y2 = me2.chart.scales[positionAxisID].getPixelForValue(value) + tickAndPadding;
        }
        textAlign = me2._getXAxisLabelAlignment();
      } else if (axis === "y") {
        if (position === "center") {
          x2 = (chartArea.left + chartArea.right) / 2 - tickAndPadding;
        } else if (isObject(position)) {
          const positionAxisID = Object.keys(position)[0];
          const value = position[positionAxisID];
          x2 = me2.chart.scales[positionAxisID].getPixelForValue(value);
        }
        textAlign = me2._getYAxisLabelAlignment(tl).textAlign;
      }
      if (axis === "y") {
        if (align === "start") {
          textBaseline = "top";
        } else if (align === "end") {
          textBaseline = "bottom";
        }
      }
      const labelSizes = me2._getLabelSizes();
      for (i2 = 0, ilen = ticks.length; i2 < ilen; ++i2) {
        tick = ticks[i2];
        label = tick.label;
        const optsAtIndex = optionTicks.setContext(me2.getContext(i2));
        pixel = me2.getPixelForTick(i2) + optionTicks.labelOffset;
        font = me2._resolveTickFontOptions(i2);
        lineHeight = font.lineHeight;
        lineCount = isArray(label) ? label.length : 1;
        const halfCount = lineCount / 2;
        const color2 = optsAtIndex.color;
        const strokeColor = optsAtIndex.textStrokeColor;
        const strokeWidth = optsAtIndex.textStrokeWidth;
        if (isHorizontal) {
          x2 = pixel;
          if (position === "top") {
            if (crossAlign === "near" || rotation !== 0) {
              textOffset = -lineCount * lineHeight + lineHeight / 2;
            } else if (crossAlign === "center") {
              textOffset = -labelSizes.highest.height / 2 - halfCount * lineHeight + lineHeight;
            } else {
              textOffset = -labelSizes.highest.height + lineHeight / 2;
            }
          } else {
            if (crossAlign === "near" || rotation !== 0) {
              textOffset = lineHeight / 2;
            } else if (crossAlign === "center") {
              textOffset = labelSizes.highest.height / 2 - halfCount * lineHeight;
            } else {
              textOffset = labelSizes.highest.height - lineCount * lineHeight;
            }
          }
          if (mirror) {
            textOffset *= -1;
          }
        } else {
          y2 = pixel;
          textOffset = (1 - lineCount) * lineHeight / 2;
        }
        let backdrop;
        if (optsAtIndex.showLabelBackdrop) {
          const labelPadding = toPadding(optsAtIndex.backdropPadding);
          const height = labelSizes.heights[i2];
          const width = labelSizes.widths[i2];
          let top2 = y2 + textOffset - labelPadding.top;
          let left2 = x2 - labelPadding.left;
          switch (textBaseline) {
            case "middle":
              top2 -= height / 2;
              break;
            case "bottom":
              top2 -= height;
              break;
          }
          switch (textAlign) {
            case "center":
              left2 -= width / 2;
              break;
            case "right":
              left2 -= width;
              break;
          }
          backdrop = {
            left: left2,
            top: top2,
            width: width + labelPadding.width,
            height: height + labelPadding.height,
            color: optsAtIndex.backdropColor
          };
        }
        items.push({
          rotation,
          label,
          font,
          color: color2,
          strokeColor,
          strokeWidth,
          textOffset,
          textAlign,
          textBaseline,
          translation: [x2, y2],
          backdrop
        });
      }
      return items;
    }
    _getXAxisLabelAlignment() {
      const me2 = this;
      const { position, ticks } = me2.options;
      const rotation = -toRadians(me2.labelRotation);
      if (rotation) {
        return position === "top" ? "left" : "right";
      }
      let align = "center";
      if (ticks.align === "start") {
        align = "left";
      } else if (ticks.align === "end") {
        align = "right";
      }
      return align;
    }
    _getYAxisLabelAlignment(tl) {
      const me2 = this;
      const { position, ticks: { crossAlign, mirror, padding } } = me2.options;
      const labelSizes = me2._getLabelSizes();
      const tickAndPadding = tl + padding;
      const widest = labelSizes.widest.width;
      let textAlign;
      let x2;
      if (position === "left") {
        if (mirror) {
          textAlign = "left";
          x2 = me2.right + padding;
        } else {
          x2 = me2.right - tickAndPadding;
          if (crossAlign === "near") {
            textAlign = "right";
          } else if (crossAlign === "center") {
            textAlign = "center";
            x2 -= widest / 2;
          } else {
            textAlign = "left";
            x2 = me2.left;
          }
        }
      } else if (position === "right") {
        if (mirror) {
          textAlign = "right";
          x2 = me2.left + padding;
        } else {
          x2 = me2.left + tickAndPadding;
          if (crossAlign === "near") {
            textAlign = "left";
          } else if (crossAlign === "center") {
            textAlign = "center";
            x2 += widest / 2;
          } else {
            textAlign = "right";
            x2 = me2.right;
          }
        }
      } else {
        textAlign = "right";
      }
      return { textAlign, x: x2 };
    }
    _computeLabelArea() {
      const me2 = this;
      if (me2.options.ticks.mirror) {
        return;
      }
      const chart = me2.chart;
      const position = me2.options.position;
      if (position === "left" || position === "right") {
        return { top: 0, left: me2.left, bottom: chart.height, right: me2.right };
      }
      if (position === "top" || position === "bottom") {
        return { top: me2.top, left: 0, bottom: me2.bottom, right: chart.width };
      }
    }
    drawBackground() {
      const { ctx, options: { backgroundColor }, left: left2, top: top2, width, height } = this;
      if (backgroundColor) {
        ctx.save();
        ctx.fillStyle = backgroundColor;
        ctx.fillRect(left2, top2, width, height);
        ctx.restore();
      }
    }
    getLineWidthForValue(value) {
      const me2 = this;
      const grid = me2.options.grid;
      if (!me2._isVisible() || !grid.display) {
        return 0;
      }
      const ticks = me2.ticks;
      const index = ticks.findIndex((t2) => t2.value === value);
      if (index >= 0) {
        const opts = grid.setContext(me2.getContext(index));
        return opts.lineWidth;
      }
      return 0;
    }
    drawGrid(chartArea) {
      const me2 = this;
      const grid = me2.options.grid;
      const ctx = me2.ctx;
      const items = me2._gridLineItems || (me2._gridLineItems = me2._computeGridLineItems(chartArea));
      let i2, ilen;
      const drawLine = (p1, p2, style) => {
        if (!style.width || !style.color) {
          return;
        }
        ctx.save();
        ctx.lineWidth = style.width;
        ctx.strokeStyle = style.color;
        ctx.setLineDash(style.borderDash || []);
        ctx.lineDashOffset = style.borderDashOffset;
        ctx.beginPath();
        ctx.moveTo(p1.x, p1.y);
        ctx.lineTo(p2.x, p2.y);
        ctx.stroke();
        ctx.restore();
      };
      if (grid.display) {
        for (i2 = 0, ilen = items.length; i2 < ilen; ++i2) {
          const item = items[i2];
          if (grid.drawOnChartArea) {
            drawLine({ x: item.x1, y: item.y1 }, { x: item.x2, y: item.y2 }, item);
          }
          if (grid.drawTicks) {
            drawLine({ x: item.tx1, y: item.ty1 }, { x: item.tx2, y: item.ty2 }, {
              color: item.tickColor,
              width: item.tickWidth,
              borderDash: item.tickBorderDash,
              borderDashOffset: item.tickBorderDashOffset
            });
          }
        }
      }
    }
    drawBorder() {
      const me2 = this;
      const { chart, ctx, options: { grid } } = me2;
      const borderOpts = grid.setContext(me2.getContext());
      const axisWidth = grid.drawBorder ? borderOpts.borderWidth : 0;
      if (!axisWidth) {
        return;
      }
      const lastLineWidth = grid.setContext(me2.getContext(0)).lineWidth;
      const borderValue = me2._borderValue;
      let x1, x2, y1, y2;
      if (me2.isHorizontal()) {
        x1 = _alignPixel(chart, me2.left, axisWidth) - axisWidth / 2;
        x2 = _alignPixel(chart, me2.right, lastLineWidth) + lastLineWidth / 2;
        y1 = y2 = borderValue;
      } else {
        y1 = _alignPixel(chart, me2.top, axisWidth) - axisWidth / 2;
        y2 = _alignPixel(chart, me2.bottom, lastLineWidth) + lastLineWidth / 2;
        x1 = x2 = borderValue;
      }
      ctx.save();
      ctx.lineWidth = borderOpts.borderWidth;
      ctx.strokeStyle = borderOpts.borderColor;
      ctx.beginPath();
      ctx.moveTo(x1, y1);
      ctx.lineTo(x2, y2);
      ctx.stroke();
      ctx.restore();
    }
    drawLabels(chartArea) {
      const me2 = this;
      const optionTicks = me2.options.ticks;
      if (!optionTicks.display) {
        return;
      }
      const ctx = me2.ctx;
      const area = me2._computeLabelArea();
      if (area) {
        clipArea(ctx, area);
      }
      const items = me2._labelItems || (me2._labelItems = me2._computeLabelItems(chartArea));
      let i2, ilen;
      for (i2 = 0, ilen = items.length; i2 < ilen; ++i2) {
        const item = items[i2];
        const tickFont = item.font;
        const label = item.label;
        if (item.backdrop) {
          ctx.fillStyle = item.backdrop.color;
          ctx.fillRect(item.backdrop.left, item.backdrop.top, item.backdrop.width, item.backdrop.height);
        }
        let y2 = item.textOffset;
        renderText(ctx, label, 0, y2, tickFont, item);
      }
      if (area) {
        unclipArea(ctx);
      }
    }
    drawTitle() {
      const { ctx, options: { position, title, reverse } } = this;
      if (!title.display) {
        return;
      }
      const font = toFont(title.font);
      const padding = toPadding(title.padding);
      const align = title.align;
      let offset2 = font.lineHeight / 2;
      if (position === "bottom" || position === "center" || isObject(position)) {
        offset2 += padding.bottom;
        if (isArray(title.text)) {
          offset2 += font.lineHeight * (title.text.length - 1);
        }
      } else {
        offset2 += padding.top;
      }
      const { titleX, titleY, maxWidth, rotation } = titleArgs(this, offset2, position, align);
      renderText(ctx, title.text, 0, 0, font, {
        color: title.color,
        maxWidth,
        rotation,
        textAlign: titleAlign(align, position, reverse),
        textBaseline: "middle",
        translation: [titleX, titleY]
      });
    }
    draw(chartArea) {
      const me2 = this;
      if (!me2._isVisible()) {
        return;
      }
      me2.drawBackground();
      me2.drawGrid(chartArea);
      me2.drawBorder();
      me2.drawTitle();
      me2.drawLabels(chartArea);
    }
    _layers() {
      const me2 = this;
      const opts = me2.options;
      const tz = opts.ticks && opts.ticks.z || 0;
      const gz = valueOrDefault(opts.grid && opts.grid.z, -1);
      if (!me2._isVisible() || me2.draw !== Scale.prototype.draw) {
        return [{
          z: tz,
          draw(chartArea) {
            me2.draw(chartArea);
          }
        }];
      }
      return [{
        z: gz,
        draw(chartArea) {
          me2.drawBackground();
          me2.drawGrid(chartArea);
          me2.drawTitle();
        }
      }, {
        z: gz + 1,
        draw() {
          me2.drawBorder();
        }
      }, {
        z: tz,
        draw(chartArea) {
          me2.drawLabels(chartArea);
        }
      }];
    }
    getMatchingVisibleMetas(type) {
      const me2 = this;
      const metas = me2.chart.getSortedVisibleDatasetMetas();
      const axisID = me2.axis + "AxisID";
      const result = [];
      let i2, ilen;
      for (i2 = 0, ilen = metas.length; i2 < ilen; ++i2) {
        const meta = metas[i2];
        if (meta[axisID] === me2.id && (!type || meta.type === type)) {
          result.push(meta);
        }
      }
      return result;
    }
    _resolveTickFontOptions(index) {
      const opts = this.options.ticks.setContext(this.getContext(index));
      return toFont(opts.font);
    }
    _maxDigits() {
      const me2 = this;
      const fontSize = me2._resolveTickFontOptions(0).lineHeight;
      return (me2.isHorizontal() ? me2.width : me2.height) / fontSize;
    }
  };
  var TypedRegistry = class {
    constructor(type, scope, override) {
      this.type = type;
      this.scope = scope;
      this.override = override;
      this.items = /* @__PURE__ */ Object.create(null);
    }
    isForType(type) {
      return Object.prototype.isPrototypeOf.call(this.type.prototype, type.prototype);
    }
    register(item) {
      const me2 = this;
      const proto = Object.getPrototypeOf(item);
      let parentScope;
      if (isIChartComponent(proto)) {
        parentScope = me2.register(proto);
      }
      const items = me2.items;
      const id2 = item.id;
      const scope = me2.scope + "." + id2;
      if (!id2) {
        throw new Error("class does not have id: " + item);
      }
      if (id2 in items) {
        return scope;
      }
      items[id2] = item;
      registerDefaults(item, scope, parentScope);
      if (me2.override) {
        defaults.override(item.id, item.overrides);
      }
      return scope;
    }
    get(id2) {
      return this.items[id2];
    }
    unregister(item) {
      const items = this.items;
      const id2 = item.id;
      const scope = this.scope;
      if (id2 in items) {
        delete items[id2];
      }
      if (scope && id2 in defaults[scope]) {
        delete defaults[scope][id2];
        if (this.override) {
          delete overrides[id2];
        }
      }
    }
  };
  function registerDefaults(item, scope, parentScope) {
    const itemDefaults = merge(/* @__PURE__ */ Object.create(null), [
      parentScope ? defaults.get(parentScope) : {},
      defaults.get(scope),
      item.defaults
    ]);
    defaults.set(scope, itemDefaults);
    if (item.defaultRoutes) {
      routeDefaults(scope, item.defaultRoutes);
    }
    if (item.descriptors) {
      defaults.describe(scope, item.descriptors);
    }
  }
  function routeDefaults(scope, routes) {
    Object.keys(routes).forEach((property) => {
      const propertyParts = property.split(".");
      const sourceName = propertyParts.pop();
      const sourceScope = [scope].concat(propertyParts).join(".");
      const parts = routes[property].split(".");
      const targetName = parts.pop();
      const targetScope = parts.join(".");
      defaults.route(sourceScope, sourceName, targetScope, targetName);
    });
  }
  function isIChartComponent(proto) {
    return "id" in proto && "defaults" in proto;
  }
  var Registry = class {
    constructor() {
      this.controllers = new TypedRegistry(DatasetController, "datasets", true);
      this.elements = new TypedRegistry(Element2, "elements");
      this.plugins = new TypedRegistry(Object, "plugins");
      this.scales = new TypedRegistry(Scale, "scales");
      this._typedRegistries = [this.controllers, this.scales, this.elements];
    }
    add(...args) {
      this._each("register", args);
    }
    remove(...args) {
      this._each("unregister", args);
    }
    addControllers(...args) {
      this._each("register", args, this.controllers);
    }
    addElements(...args) {
      this._each("register", args, this.elements);
    }
    addPlugins(...args) {
      this._each("register", args, this.plugins);
    }
    addScales(...args) {
      this._each("register", args, this.scales);
    }
    getController(id2) {
      return this._get(id2, this.controllers, "controller");
    }
    getElement(id2) {
      return this._get(id2, this.elements, "element");
    }
    getPlugin(id2) {
      return this._get(id2, this.plugins, "plugin");
    }
    getScale(id2) {
      return this._get(id2, this.scales, "scale");
    }
    removeControllers(...args) {
      this._each("unregister", args, this.controllers);
    }
    removeElements(...args) {
      this._each("unregister", args, this.elements);
    }
    removePlugins(...args) {
      this._each("unregister", args, this.plugins);
    }
    removeScales(...args) {
      this._each("unregister", args, this.scales);
    }
    _each(method, args, typedRegistry) {
      const me2 = this;
      [...args].forEach((arg) => {
        const reg = typedRegistry || me2._getRegistryForType(arg);
        if (typedRegistry || reg.isForType(arg) || reg === me2.plugins && arg.id) {
          me2._exec(method, reg, arg);
        } else {
          each(arg, (item) => {
            const itemReg = typedRegistry || me2._getRegistryForType(item);
            me2._exec(method, itemReg, item);
          });
        }
      });
    }
    _exec(method, registry2, component) {
      const camelMethod = _capitalize(method);
      callback(component["before" + camelMethod], [], component);
      registry2[method](component);
      callback(component["after" + camelMethod], [], component);
    }
    _getRegistryForType(type) {
      for (let i2 = 0; i2 < this._typedRegistries.length; i2++) {
        const reg = this._typedRegistries[i2];
        if (reg.isForType(type)) {
          return reg;
        }
      }
      return this.plugins;
    }
    _get(id2, typedRegistry, type) {
      const item = typedRegistry.get(id2);
      if (item === void 0) {
        throw new Error('"' + id2 + '" is not a registered ' + type + ".");
      }
      return item;
    }
  };
  var registry = new Registry();
  var PluginService = class {
    constructor() {
      this._init = [];
    }
    notify(chart, hook, args, filter) {
      const me2 = this;
      if (hook === "beforeInit") {
        me2._init = me2._createDescriptors(chart, true);
        me2._notify(me2._init, chart, "install");
      }
      const descriptors2 = filter ? me2._descriptors(chart).filter(filter) : me2._descriptors(chart);
      const result = me2._notify(descriptors2, chart, hook, args);
      if (hook === "destroy") {
        me2._notify(descriptors2, chart, "stop");
        me2._notify(me2._init, chart, "uninstall");
      }
      return result;
    }
    _notify(descriptors2, chart, hook, args) {
      args = args || {};
      for (const descriptor of descriptors2) {
        const plugin = descriptor.plugin;
        const method = plugin[hook];
        const params = [chart, args, descriptor.options];
        if (callback(method, params, plugin) === false && args.cancelable) {
          return false;
        }
      }
      return true;
    }
    invalidate() {
      if (!isNullOrUndef(this._cache)) {
        this._oldCache = this._cache;
        this._cache = void 0;
      }
    }
    _descriptors(chart) {
      if (this._cache) {
        return this._cache;
      }
      const descriptors2 = this._cache = this._createDescriptors(chart);
      this._notifyStateChanges(chart);
      return descriptors2;
    }
    _createDescriptors(chart, all) {
      const config = chart && chart.config;
      const options = valueOrDefault(config.options && config.options.plugins, {});
      const plugins2 = allPlugins(config);
      return options === false && !all ? [] : createDescriptors(chart, plugins2, options, all);
    }
    _notifyStateChanges(chart) {
      const previousDescriptors = this._oldCache || [];
      const descriptors2 = this._cache;
      const diff = (a2, b2) => a2.filter((x2) => !b2.some((y2) => x2.plugin.id === y2.plugin.id));
      this._notify(diff(previousDescriptors, descriptors2), chart, "stop");
      this._notify(diff(descriptors2, previousDescriptors), chart, "start");
    }
  };
  function allPlugins(config) {
    const plugins2 = [];
    const keys = Object.keys(registry.plugins.items);
    for (let i2 = 0; i2 < keys.length; i2++) {
      plugins2.push(registry.getPlugin(keys[i2]));
    }
    const local = config.plugins || [];
    for (let i2 = 0; i2 < local.length; i2++) {
      const plugin = local[i2];
      if (plugins2.indexOf(plugin) === -1) {
        plugins2.push(plugin);
      }
    }
    return plugins2;
  }
  function getOpts(options, all) {
    if (!all && options === false) {
      return null;
    }
    if (options === true) {
      return {};
    }
    return options;
  }
  function createDescriptors(chart, plugins2, options, all) {
    const result = [];
    const context = chart.getContext();
    for (let i2 = 0; i2 < plugins2.length; i2++) {
      const plugin = plugins2[i2];
      const id2 = plugin.id;
      const opts = getOpts(options[id2], all);
      if (opts === null) {
        continue;
      }
      result.push({
        plugin,
        options: pluginOpts(chart.config, plugin, opts, context)
      });
    }
    return result;
  }
  function pluginOpts(config, plugin, opts, context) {
    const keys = config.pluginScopeKeys(plugin);
    const scopes = config.getOptionScopes(opts, keys);
    return config.createResolver(scopes, context, [""], { scriptable: false, indexable: false, allKeys: true });
  }
  function getIndexAxis(type, options) {
    const datasetDefaults = defaults.datasets[type] || {};
    const datasetOptions = (options.datasets || {})[type] || {};
    return datasetOptions.indexAxis || options.indexAxis || datasetDefaults.indexAxis || "x";
  }
  function getAxisFromDefaultScaleID(id2, indexAxis) {
    let axis = id2;
    if (id2 === "_index_") {
      axis = indexAxis;
    } else if (id2 === "_value_") {
      axis = indexAxis === "x" ? "y" : "x";
    }
    return axis;
  }
  function getDefaultScaleIDFromAxis(axis, indexAxis) {
    return axis === indexAxis ? "_index_" : "_value_";
  }
  function axisFromPosition(position) {
    if (position === "top" || position === "bottom") {
      return "x";
    }
    if (position === "left" || position === "right") {
      return "y";
    }
  }
  function determineAxis(id2, scaleOptions) {
    if (id2 === "x" || id2 === "y") {
      return id2;
    }
    return scaleOptions.axis || axisFromPosition(scaleOptions.position) || id2.charAt(0).toLowerCase();
  }
  function mergeScaleConfig(config, options) {
    const chartDefaults = overrides[config.type] || { scales: {} };
    const configScales = options.scales || {};
    const chartIndexAxis = getIndexAxis(config.type, options);
    const firstIDs = /* @__PURE__ */ Object.create(null);
    const scales2 = /* @__PURE__ */ Object.create(null);
    Object.keys(configScales).forEach((id2) => {
      const scaleConf = configScales[id2];
      const axis = determineAxis(id2, scaleConf);
      const defaultId = getDefaultScaleIDFromAxis(axis, chartIndexAxis);
      const defaultScaleOptions = chartDefaults.scales || {};
      firstIDs[axis] = firstIDs[axis] || id2;
      scales2[id2] = mergeIf(/* @__PURE__ */ Object.create(null), [{ axis }, scaleConf, defaultScaleOptions[axis], defaultScaleOptions[defaultId]]);
    });
    config.data.datasets.forEach((dataset) => {
      const type = dataset.type || config.type;
      const indexAxis = dataset.indexAxis || getIndexAxis(type, options);
      const datasetDefaults = overrides[type] || {};
      const defaultScaleOptions = datasetDefaults.scales || {};
      Object.keys(defaultScaleOptions).forEach((defaultID) => {
        const axis = getAxisFromDefaultScaleID(defaultID, indexAxis);
        const id2 = dataset[axis + "AxisID"] || firstIDs[axis] || axis;
        scales2[id2] = scales2[id2] || /* @__PURE__ */ Object.create(null);
        mergeIf(scales2[id2], [{ axis }, configScales[id2], defaultScaleOptions[defaultID]]);
      });
    });
    Object.keys(scales2).forEach((key) => {
      const scale = scales2[key];
      mergeIf(scale, [defaults.scales[scale.type], defaults.scale]);
    });
    return scales2;
  }
  function initOptions(config) {
    const options = config.options || (config.options = {});
    options.plugins = valueOrDefault(options.plugins, {});
    options.scales = mergeScaleConfig(config, options);
  }
  function initData(data) {
    data = data || {};
    data.datasets = data.datasets || [];
    data.labels = data.labels || [];
    return data;
  }
  function initConfig(config) {
    config = config || {};
    config.data = initData(config.data);
    initOptions(config);
    return config;
  }
  var keyCache = /* @__PURE__ */ new Map();
  var keysCached = /* @__PURE__ */ new Set();
  function cachedKeys(cacheKey, generate) {
    let keys = keyCache.get(cacheKey);
    if (!keys) {
      keys = generate();
      keyCache.set(cacheKey, keys);
      keysCached.add(keys);
    }
    return keys;
  }
  var addIfFound = (set2, obj, key) => {
    const opts = resolveObjectKey(obj, key);
    if (opts !== void 0) {
      set2.add(opts);
    }
  };
  var Config = class {
    constructor(config) {
      this._config = initConfig(config);
      this._scopeCache = /* @__PURE__ */ new Map();
      this._resolverCache = /* @__PURE__ */ new Map();
    }
    get platform() {
      return this._config.platform;
    }
    get type() {
      return this._config.type;
    }
    set type(type) {
      this._config.type = type;
    }
    get data() {
      return this._config.data;
    }
    set data(data) {
      this._config.data = initData(data);
    }
    get options() {
      return this._config.options;
    }
    set options(options) {
      this._config.options = options;
    }
    get plugins() {
      return this._config.plugins;
    }
    update() {
      const config = this._config;
      this.clearCache();
      initOptions(config);
    }
    clearCache() {
      this._scopeCache.clear();
      this._resolverCache.clear();
    }
    datasetScopeKeys(datasetType) {
      return cachedKeys(datasetType, () => [[
        `datasets.${datasetType}`,
        ""
      ]]);
    }
    datasetAnimationScopeKeys(datasetType, transition) {
      return cachedKeys(`${datasetType}.transition.${transition}`, () => [
        [
          `datasets.${datasetType}.transitions.${transition}`,
          `transitions.${transition}`
        ],
        [
          `datasets.${datasetType}`,
          ""
        ]
      ]);
    }
    datasetElementScopeKeys(datasetType, elementType2) {
      return cachedKeys(`${datasetType}-${elementType2}`, () => [[
        `datasets.${datasetType}.elements.${elementType2}`,
        `datasets.${datasetType}`,
        `elements.${elementType2}`,
        ""
      ]]);
    }
    pluginScopeKeys(plugin) {
      const id2 = plugin.id;
      const type = this.type;
      return cachedKeys(`${type}-plugin-${id2}`, () => [[
        `plugins.${id2}`,
        ...plugin.additionalOptionScopes || []
      ]]);
    }
    _cachedScopes(mainScope, resetCache) {
      const _scopeCache = this._scopeCache;
      let cache2 = _scopeCache.get(mainScope);
      if (!cache2 || resetCache) {
        cache2 = /* @__PURE__ */ new Map();
        _scopeCache.set(mainScope, cache2);
      }
      return cache2;
    }
    getOptionScopes(mainScope, keyLists, resetCache) {
      const { options, type } = this;
      const cache2 = this._cachedScopes(mainScope, resetCache);
      const cached = cache2.get(keyLists);
      if (cached) {
        return cached;
      }
      const scopes = /* @__PURE__ */ new Set();
      keyLists.forEach((keys) => {
        if (mainScope) {
          scopes.add(mainScope);
          keys.forEach((key) => addIfFound(scopes, mainScope, key));
        }
        keys.forEach((key) => addIfFound(scopes, options, key));
        keys.forEach((key) => addIfFound(scopes, overrides[type] || {}, key));
        keys.forEach((key) => addIfFound(scopes, defaults, key));
        keys.forEach((key) => addIfFound(scopes, descriptors, key));
      });
      const array = Array.from(scopes);
      if (array.length === 0) {
        array.push(/* @__PURE__ */ Object.create(null));
      }
      if (keysCached.has(keyLists)) {
        cache2.set(keyLists, array);
      }
      return array;
    }
    chartOptionScopes() {
      const { options, type } = this;
      return [
        options,
        overrides[type] || {},
        defaults.datasets[type] || {},
        { type },
        defaults,
        descriptors
      ];
    }
    resolveNamedOptions(scopes, names2, context, prefixes = [""]) {
      const result = { $shared: true };
      const { resolver, subPrefixes } = getResolver(this._resolverCache, scopes, prefixes);
      let options = resolver;
      if (needContext(resolver, names2)) {
        result.$shared = false;
        context = isFunction(context) ? context() : context;
        const subResolver = this.createResolver(scopes, context, subPrefixes);
        options = _attachContext(resolver, context, subResolver);
      }
      for (const prop of names2) {
        result[prop] = options[prop];
      }
      return result;
    }
    createResolver(scopes, context, prefixes = [""], descriptorDefaults) {
      const { resolver } = getResolver(this._resolverCache, scopes, prefixes);
      return isObject(context) ? _attachContext(resolver, context, void 0, descriptorDefaults) : resolver;
    }
  };
  function getResolver(resolverCache, scopes, prefixes) {
    let cache2 = resolverCache.get(scopes);
    if (!cache2) {
      cache2 = /* @__PURE__ */ new Map();
      resolverCache.set(scopes, cache2);
    }
    const cacheKey = prefixes.join();
    let cached = cache2.get(cacheKey);
    if (!cached) {
      const resolver = _createResolver(scopes, prefixes);
      cached = {
        resolver,
        subPrefixes: prefixes.filter((p2) => !p2.toLowerCase().includes("hover"))
      };
      cache2.set(cacheKey, cached);
    }
    return cached;
  }
  function needContext(proxy, names2) {
    const { isScriptable, isIndexable } = _descriptors(proxy);
    for (const prop of names2) {
      if (isScriptable(prop) && isFunction(proxy[prop]) || isIndexable(prop) && isArray(proxy[prop])) {
        return true;
      }
    }
    return false;
  }
  var version = "3.5.0";
  var KNOWN_POSITIONS = ["top", "bottom", "left", "right", "chartArea"];
  function positionIsHorizontal(position, axis) {
    return position === "top" || position === "bottom" || KNOWN_POSITIONS.indexOf(position) === -1 && axis === "x";
  }
  function compare2Level(l1, l2) {
    return function(a2, b2) {
      return a2[l1] === b2[l1] ? a2[l2] - b2[l2] : a2[l1] - b2[l1];
    };
  }
  function onAnimationsComplete(context) {
    const chart = context.chart;
    const animationOptions2 = chart.options.animation;
    chart.notifyPlugins("afterRender");
    callback(animationOptions2 && animationOptions2.onComplete, [context], chart);
  }
  function onAnimationProgress(context) {
    const chart = context.chart;
    const animationOptions2 = chart.options.animation;
    callback(animationOptions2 && animationOptions2.onProgress, [context], chart);
  }
  function getCanvas(item) {
    if (_isDomSupported() && typeof item === "string") {
      item = document.getElementById(item);
    } else if (item && item.length) {
      item = item[0];
    }
    if (item && item.canvas) {
      item = item.canvas;
    }
    return item;
  }
  var instances = {};
  var getChart = (key) => {
    const canvas = getCanvas(key);
    return Object.values(instances).filter((c2) => c2.canvas === canvas).pop();
  };
  var Chart = class {
    constructor(item, userConfig) {
      const me2 = this;
      const config = this.config = new Config(userConfig);
      const initialCanvas = getCanvas(item);
      const existingChart = getChart(initialCanvas);
      if (existingChart) {
        throw new Error("Canvas is already in use. Chart with ID '" + existingChart.id + "' must be destroyed before the canvas can be reused.");
      }
      const options = config.createResolver(config.chartOptionScopes(), me2.getContext());
      this.platform = new (config.platform || _detectPlatform(initialCanvas))();
      const context = me2.platform.acquireContext(initialCanvas, options.aspectRatio);
      const canvas = context && context.canvas;
      const height = canvas && canvas.height;
      const width = canvas && canvas.width;
      this.id = uid();
      this.ctx = context;
      this.canvas = canvas;
      this.width = width;
      this.height = height;
      this._options = options;
      this._aspectRatio = this.aspectRatio;
      this._layers = [];
      this._metasets = [];
      this._stacks = void 0;
      this.boxes = [];
      this.currentDevicePixelRatio = void 0;
      this.chartArea = void 0;
      this._active = [];
      this._lastEvent = void 0;
      this._listeners = {};
      this._responsiveListeners = void 0;
      this._sortedMetasets = [];
      this.scales = {};
      this.scale = void 0;
      this._plugins = new PluginService();
      this.$proxies = {};
      this._hiddenIndices = {};
      this.attached = false;
      this._animationsDisabled = void 0;
      this.$context = void 0;
      this._doResize = debounce3(() => this.update("resize"), options.resizeDelay || 0);
      instances[me2.id] = me2;
      if (!context || !canvas) {
        console.error("Failed to create chart: can't acquire context from the given item");
        return;
      }
      animator.listen(me2, "complete", onAnimationsComplete);
      animator.listen(me2, "progress", onAnimationProgress);
      me2._initialize();
      if (me2.attached) {
        me2.update();
      }
    }
    get aspectRatio() {
      const { options: { aspectRatio, maintainAspectRatio }, width, height, _aspectRatio } = this;
      if (!isNullOrUndef(aspectRatio)) {
        return aspectRatio;
      }
      if (maintainAspectRatio && _aspectRatio) {
        return _aspectRatio;
      }
      return height ? width / height : null;
    }
    get data() {
      return this.config.data;
    }
    set data(data) {
      this.config.data = data;
    }
    get options() {
      return this._options;
    }
    set options(options) {
      this.config.options = options;
    }
    _initialize() {
      const me2 = this;
      me2.notifyPlugins("beforeInit");
      if (me2.options.responsive) {
        me2.resize();
      } else {
        retinaScale(me2, me2.options.devicePixelRatio);
      }
      me2.bindEvents();
      me2.notifyPlugins("afterInit");
      return me2;
    }
    clear() {
      clearCanvas(this.canvas, this.ctx);
      return this;
    }
    stop() {
      animator.stop(this);
      return this;
    }
    resize(width, height) {
      if (!animator.running(this)) {
        this._resize(width, height);
      } else {
        this._resizeBeforeDraw = { width, height };
      }
    }
    _resize(width, height) {
      const me2 = this;
      const options = me2.options;
      const canvas = me2.canvas;
      const aspectRatio = options.maintainAspectRatio && me2.aspectRatio;
      const newSize = me2.platform.getMaximumSize(canvas, width, height, aspectRatio);
      const newRatio = options.devicePixelRatio || me2.platform.getDevicePixelRatio();
      me2.width = newSize.width;
      me2.height = newSize.height;
      me2._aspectRatio = me2.aspectRatio;
      if (!retinaScale(me2, newRatio, true)) {
        return;
      }
      me2.notifyPlugins("resize", { size: newSize });
      callback(options.onResize, [me2, newSize], me2);
      if (me2.attached) {
        if (me2._doResize()) {
          me2.render();
        }
      }
    }
    ensureScalesHaveIDs() {
      const options = this.options;
      const scalesOptions = options.scales || {};
      each(scalesOptions, (axisOptions, axisID) => {
        axisOptions.id = axisID;
      });
    }
    buildOrUpdateScales() {
      const me2 = this;
      const options = me2.options;
      const scaleOpts = options.scales;
      const scales2 = me2.scales;
      const updated = Object.keys(scales2).reduce((obj, id2) => {
        obj[id2] = false;
        return obj;
      }, {});
      let items = [];
      if (scaleOpts) {
        items = items.concat(Object.keys(scaleOpts).map((id2) => {
          const scaleOptions = scaleOpts[id2];
          const axis = determineAxis(id2, scaleOptions);
          const isRadial = axis === "r";
          const isHorizontal = axis === "x";
          return {
            options: scaleOptions,
            dposition: isRadial ? "chartArea" : isHorizontal ? "bottom" : "left",
            dtype: isRadial ? "radialLinear" : isHorizontal ? "category" : "linear"
          };
        }));
      }
      each(items, (item) => {
        const scaleOptions = item.options;
        const id2 = scaleOptions.id;
        const axis = determineAxis(id2, scaleOptions);
        const scaleType = valueOrDefault(scaleOptions.type, item.dtype);
        if (scaleOptions.position === void 0 || positionIsHorizontal(scaleOptions.position, axis) !== positionIsHorizontal(item.dposition)) {
          scaleOptions.position = item.dposition;
        }
        updated[id2] = true;
        let scale = null;
        if (id2 in scales2 && scales2[id2].type === scaleType) {
          scale = scales2[id2];
        } else {
          const scaleClass = registry.getScale(scaleType);
          scale = new scaleClass({
            id: id2,
            type: scaleType,
            ctx: me2.ctx,
            chart: me2
          });
          scales2[scale.id] = scale;
        }
        scale.init(scaleOptions, options);
      });
      each(updated, (hasUpdated, id2) => {
        if (!hasUpdated) {
          delete scales2[id2];
        }
      });
      each(scales2, (scale) => {
        layouts.configure(me2, scale, scale.options);
        layouts.addBox(me2, scale);
      });
    }
    _updateMetasets() {
      const me2 = this;
      const metasets = me2._metasets;
      const numData = me2.data.datasets.length;
      const numMeta = metasets.length;
      metasets.sort((a2, b2) => a2.index - b2.index);
      if (numMeta > numData) {
        for (let i2 = numData; i2 < numMeta; ++i2) {
          me2._destroyDatasetMeta(i2);
        }
        metasets.splice(numData, numMeta - numData);
      }
      me2._sortedMetasets = metasets.slice(0).sort(compare2Level("order", "index"));
    }
    _removeUnreferencedMetasets() {
      const me2 = this;
      const { _metasets: metasets, data: { datasets } } = me2;
      if (metasets.length > datasets.length) {
        delete me2._stacks;
      }
      metasets.forEach((meta, index) => {
        if (datasets.filter((x2) => x2 === meta._dataset).length === 0) {
          me2._destroyDatasetMeta(index);
        }
      });
    }
    buildOrUpdateControllers() {
      const me2 = this;
      const newControllers = [];
      const datasets = me2.data.datasets;
      let i2, ilen;
      me2._removeUnreferencedMetasets();
      for (i2 = 0, ilen = datasets.length; i2 < ilen; i2++) {
        const dataset = datasets[i2];
        let meta = me2.getDatasetMeta(i2);
        const type = dataset.type || me2.config.type;
        if (meta.type && meta.type !== type) {
          me2._destroyDatasetMeta(i2);
          meta = me2.getDatasetMeta(i2);
        }
        meta.type = type;
        meta.indexAxis = dataset.indexAxis || getIndexAxis(type, me2.options);
        meta.order = dataset.order || 0;
        meta.index = i2;
        meta.label = "" + dataset.label;
        meta.visible = me2.isDatasetVisible(i2);
        if (meta.controller) {
          meta.controller.updateIndex(i2);
          meta.controller.linkScales();
        } else {
          const ControllerClass = registry.getController(type);
          const { datasetElementType, dataElementType } = defaults.datasets[type];
          Object.assign(ControllerClass.prototype, {
            dataElementType: registry.getElement(dataElementType),
            datasetElementType: datasetElementType && registry.getElement(datasetElementType)
          });
          meta.controller = new ControllerClass(me2, i2);
          newControllers.push(meta.controller);
        }
      }
      me2._updateMetasets();
      return newControllers;
    }
    _resetElements() {
      const me2 = this;
      each(me2.data.datasets, (dataset, datasetIndex) => {
        me2.getDatasetMeta(datasetIndex).controller.reset();
      }, me2);
    }
    reset() {
      this._resetElements();
      this.notifyPlugins("reset");
    }
    update(mode) {
      const me2 = this;
      const config = me2.config;
      config.update();
      me2._options = config.createResolver(config.chartOptionScopes(), me2.getContext());
      each(me2.scales, (scale) => {
        layouts.removeBox(me2, scale);
      });
      const animsDisabled = me2._animationsDisabled = !me2.options.animation;
      me2.ensureScalesHaveIDs();
      me2.buildOrUpdateScales();
      const existingEvents = new Set(Object.keys(me2._listeners));
      const newEvents = new Set(me2.options.events);
      if (!setsEqual(existingEvents, newEvents) || !!this._responsiveListeners !== me2.options.responsive) {
        me2.unbindEvents();
        me2.bindEvents();
      }
      me2._plugins.invalidate();
      if (me2.notifyPlugins("beforeUpdate", { mode, cancelable: true }) === false) {
        return;
      }
      const newControllers = me2.buildOrUpdateControllers();
      me2.notifyPlugins("beforeElementsUpdate");
      let minPadding = 0;
      for (let i2 = 0, ilen = me2.data.datasets.length; i2 < ilen; i2++) {
        const { controller } = me2.getDatasetMeta(i2);
        const reset = !animsDisabled && newControllers.indexOf(controller) === -1;
        controller.buildOrUpdateElements(reset);
        minPadding = Math.max(+controller.getMaxOverflow(), minPadding);
      }
      me2._minPadding = minPadding;
      me2._updateLayout(minPadding);
      if (!animsDisabled) {
        each(newControllers, (controller) => {
          controller.reset();
        });
      }
      me2._updateDatasets(mode);
      me2.notifyPlugins("afterUpdate", { mode });
      me2._layers.sort(compare2Level("z", "_idx"));
      if (me2._lastEvent) {
        me2._eventHandler(me2._lastEvent, true);
      }
      me2.render();
    }
    _updateLayout(minPadding) {
      const me2 = this;
      if (me2.notifyPlugins("beforeLayout", { cancelable: true }) === false) {
        return;
      }
      layouts.update(me2, me2.width, me2.height, minPadding);
      const area = me2.chartArea;
      const noArea = area.width <= 0 || area.height <= 0;
      me2._layers = [];
      each(me2.boxes, (box) => {
        if (noArea && box.position === "chartArea") {
          return;
        }
        if (box.configure) {
          box.configure();
        }
        me2._layers.push(...box._layers());
      }, me2);
      me2._layers.forEach((item, index) => {
        item._idx = index;
      });
      me2.notifyPlugins("afterLayout");
    }
    _updateDatasets(mode) {
      const me2 = this;
      const isFunction2 = typeof mode === "function";
      if (me2.notifyPlugins("beforeDatasetsUpdate", { mode, cancelable: true }) === false) {
        return;
      }
      for (let i2 = 0, ilen = me2.data.datasets.length; i2 < ilen; ++i2) {
        me2._updateDataset(i2, isFunction2 ? mode({ datasetIndex: i2 }) : mode);
      }
      me2.notifyPlugins("afterDatasetsUpdate", { mode });
    }
    _updateDataset(index, mode) {
      const me2 = this;
      const meta = me2.getDatasetMeta(index);
      const args = { meta, index, mode, cancelable: true };
      if (me2.notifyPlugins("beforeDatasetUpdate", args) === false) {
        return;
      }
      meta.controller._update(mode);
      args.cancelable = false;
      me2.notifyPlugins("afterDatasetUpdate", args);
    }
    render() {
      const me2 = this;
      if (me2.notifyPlugins("beforeRender", { cancelable: true }) === false) {
        return;
      }
      if (animator.has(me2)) {
        if (me2.attached && !animator.running(me2)) {
          animator.start(me2);
        }
      } else {
        me2.draw();
        onAnimationsComplete({ chart: me2 });
      }
    }
    draw() {
      const me2 = this;
      let i2;
      if (me2._resizeBeforeDraw) {
        const { width, height } = me2._resizeBeforeDraw;
        me2._resize(width, height);
        me2._resizeBeforeDraw = null;
      }
      me2.clear();
      if (me2.width <= 0 || me2.height <= 0) {
        return;
      }
      if (me2.notifyPlugins("beforeDraw", { cancelable: true }) === false) {
        return;
      }
      const layers = me2._layers;
      for (i2 = 0; i2 < layers.length && layers[i2].z <= 0; ++i2) {
        layers[i2].draw(me2.chartArea);
      }
      me2._drawDatasets();
      for (; i2 < layers.length; ++i2) {
        layers[i2].draw(me2.chartArea);
      }
      me2.notifyPlugins("afterDraw");
    }
    _getSortedDatasetMetas(filterVisible) {
      const me2 = this;
      const metasets = me2._sortedMetasets;
      const result = [];
      let i2, ilen;
      for (i2 = 0, ilen = metasets.length; i2 < ilen; ++i2) {
        const meta = metasets[i2];
        if (!filterVisible || meta.visible) {
          result.push(meta);
        }
      }
      return result;
    }
    getSortedVisibleDatasetMetas() {
      return this._getSortedDatasetMetas(true);
    }
    _drawDatasets() {
      const me2 = this;
      if (me2.notifyPlugins("beforeDatasetsDraw", { cancelable: true }) === false) {
        return;
      }
      const metasets = me2.getSortedVisibleDatasetMetas();
      for (let i2 = metasets.length - 1; i2 >= 0; --i2) {
        me2._drawDataset(metasets[i2]);
      }
      me2.notifyPlugins("afterDatasetsDraw");
    }
    _drawDataset(meta) {
      const me2 = this;
      const ctx = me2.ctx;
      const clip = meta._clip;
      const useClip = !clip.disabled;
      const area = me2.chartArea;
      const args = {
        meta,
        index: meta.index,
        cancelable: true
      };
      if (me2.notifyPlugins("beforeDatasetDraw", args) === false) {
        return;
      }
      if (useClip) {
        clipArea(ctx, {
          left: clip.left === false ? 0 : area.left - clip.left,
          right: clip.right === false ? me2.width : area.right + clip.right,
          top: clip.top === false ? 0 : area.top - clip.top,
          bottom: clip.bottom === false ? me2.height : area.bottom + clip.bottom
        });
      }
      meta.controller.draw();
      if (useClip) {
        unclipArea(ctx);
      }
      args.cancelable = false;
      me2.notifyPlugins("afterDatasetDraw", args);
    }
    getElementsAtEventForMode(e2, mode, options, useFinalPosition) {
      const method = Interaction.modes[mode];
      if (typeof method === "function") {
        return method(this, e2, options, useFinalPosition);
      }
      return [];
    }
    getDatasetMeta(datasetIndex) {
      const me2 = this;
      const dataset = me2.data.datasets[datasetIndex];
      const metasets = me2._metasets;
      let meta = metasets.filter((x2) => x2 && x2._dataset === dataset).pop();
      if (!meta) {
        meta = {
          type: null,
          data: [],
          dataset: null,
          controller: null,
          hidden: null,
          xAxisID: null,
          yAxisID: null,
          order: dataset && dataset.order || 0,
          index: datasetIndex,
          _dataset: dataset,
          _parsed: [],
          _sorted: false
        };
        metasets.push(meta);
      }
      return meta;
    }
    getContext() {
      return this.$context || (this.$context = { chart: this, type: "chart" });
    }
    getVisibleDatasetCount() {
      return this.getSortedVisibleDatasetMetas().length;
    }
    isDatasetVisible(datasetIndex) {
      const dataset = this.data.datasets[datasetIndex];
      if (!dataset) {
        return false;
      }
      const meta = this.getDatasetMeta(datasetIndex);
      return typeof meta.hidden === "boolean" ? !meta.hidden : !dataset.hidden;
    }
    setDatasetVisibility(datasetIndex, visible) {
      const meta = this.getDatasetMeta(datasetIndex);
      meta.hidden = !visible;
    }
    toggleDataVisibility(index) {
      this._hiddenIndices[index] = !this._hiddenIndices[index];
    }
    getDataVisibility(index) {
      return !this._hiddenIndices[index];
    }
    _updateVisibility(datasetIndex, dataIndex, visible) {
      const me2 = this;
      const mode = visible ? "show" : "hide";
      const meta = me2.getDatasetMeta(datasetIndex);
      const anims = meta.controller._resolveAnimations(void 0, mode);
      if (defined(dataIndex)) {
        meta.data[dataIndex].hidden = !visible;
        me2.update();
      } else {
        me2.setDatasetVisibility(datasetIndex, visible);
        anims.update(meta, { visible });
        me2.update((ctx) => ctx.datasetIndex === datasetIndex ? mode : void 0);
      }
    }
    hide(datasetIndex, dataIndex) {
      this._updateVisibility(datasetIndex, dataIndex, false);
    }
    show(datasetIndex, dataIndex) {
      this._updateVisibility(datasetIndex, dataIndex, true);
    }
    _destroyDatasetMeta(datasetIndex) {
      const me2 = this;
      const meta = me2._metasets && me2._metasets[datasetIndex];
      if (meta && meta.controller) {
        meta.controller._destroy();
        delete me2._metasets[datasetIndex];
      }
    }
    destroy() {
      const me2 = this;
      const { canvas, ctx } = me2;
      let i2, ilen;
      me2.stop();
      animator.remove(me2);
      for (i2 = 0, ilen = me2.data.datasets.length; i2 < ilen; ++i2) {
        me2._destroyDatasetMeta(i2);
      }
      me2.config.clearCache();
      if (canvas) {
        me2.unbindEvents();
        clearCanvas(canvas, ctx);
        me2.platform.releaseContext(ctx);
        me2.canvas = null;
        me2.ctx = null;
      }
      me2.notifyPlugins("destroy");
      delete instances[me2.id];
    }
    toBase64Image(...args) {
      return this.canvas.toDataURL(...args);
    }
    bindEvents() {
      this.bindUserEvents();
      if (this.options.responsive) {
        this.bindResponsiveEvents();
      } else {
        this.attached = true;
      }
    }
    bindUserEvents() {
      const me2 = this;
      const listeners = me2._listeners;
      const platform = me2.platform;
      const _add = (type, listener2) => {
        platform.addEventListener(me2, type, listener2);
        listeners[type] = listener2;
      };
      const listener = function(e2, x2, y2) {
        e2.offsetX = x2;
        e2.offsetY = y2;
        me2._eventHandler(e2);
      };
      each(me2.options.events, (type) => _add(type, listener));
    }
    bindResponsiveEvents() {
      const me2 = this;
      if (!me2._responsiveListeners) {
        me2._responsiveListeners = {};
      }
      const listeners = me2._responsiveListeners;
      const platform = me2.platform;
      const _add = (type, listener2) => {
        platform.addEventListener(me2, type, listener2);
        listeners[type] = listener2;
      };
      const _remove = (type, listener2) => {
        if (listeners[type]) {
          platform.removeEventListener(me2, type, listener2);
          delete listeners[type];
        }
      };
      const listener = (width, height) => {
        if (me2.canvas) {
          me2.resize(width, height);
        }
      };
      let detached;
      const attached = () => {
        _remove("attach", attached);
        me2.attached = true;
        me2.resize();
        _add("resize", listener);
        _add("detach", detached);
      };
      detached = () => {
        me2.attached = false;
        _remove("resize", listener);
        _add("attach", attached);
      };
      if (platform.isAttached(me2.canvas)) {
        attached();
      } else {
        detached();
      }
    }
    unbindEvents() {
      const me2 = this;
      each(me2._listeners, (listener, type) => {
        me2.platform.removeEventListener(me2, type, listener);
      });
      me2._listeners = {};
      each(me2._responsiveListeners, (listener, type) => {
        me2.platform.removeEventListener(me2, type, listener);
      });
      me2._responsiveListeners = void 0;
    }
    updateHoverStyle(items, mode, enabled) {
      const prefix = enabled ? "set" : "remove";
      let meta, item, i2, ilen;
      if (mode === "dataset") {
        meta = this.getDatasetMeta(items[0].datasetIndex);
        meta.controller["_" + prefix + "DatasetHoverStyle"]();
      }
      for (i2 = 0, ilen = items.length; i2 < ilen; ++i2) {
        item = items[i2];
        const controller = item && this.getDatasetMeta(item.datasetIndex).controller;
        if (controller) {
          controller[prefix + "HoverStyle"](item.element, item.datasetIndex, item.index);
        }
      }
    }
    getActiveElements() {
      return this._active || [];
    }
    setActiveElements(activeElements) {
      const me2 = this;
      const lastActive = me2._active || [];
      const active = activeElements.map(({ datasetIndex, index }) => {
        const meta = me2.getDatasetMeta(datasetIndex);
        if (!meta) {
          throw new Error("No dataset found at index " + datasetIndex);
        }
        return {
          datasetIndex,
          element: meta.data[index],
          index
        };
      });
      const changed = !_elementsEqual(active, lastActive);
      if (changed) {
        me2._active = active;
        me2._updateHoverStyles(active, lastActive);
      }
    }
    notifyPlugins(hook, args, filter) {
      return this._plugins.notify(this, hook, args, filter);
    }
    _updateHoverStyles(active, lastActive, replay) {
      const me2 = this;
      const hoverOptions = me2.options.hover;
      const diff = (a2, b2) => a2.filter((x2) => !b2.some((y2) => x2.datasetIndex === y2.datasetIndex && x2.index === y2.index));
      const deactivated = diff(lastActive, active);
      const activated = replay ? active : diff(active, lastActive);
      if (deactivated.length) {
        me2.updateHoverStyle(deactivated, hoverOptions.mode, false);
      }
      if (activated.length && hoverOptions.mode) {
        me2.updateHoverStyle(activated, hoverOptions.mode, true);
      }
    }
    _eventHandler(e2, replay) {
      const me2 = this;
      const args = { event: e2, replay, cancelable: true };
      const eventFilter = (plugin) => (plugin.options.events || this.options.events).includes(e2.type);
      if (me2.notifyPlugins("beforeEvent", args, eventFilter) === false) {
        return;
      }
      const changed = me2._handleEvent(e2, replay);
      args.cancelable = false;
      me2.notifyPlugins("afterEvent", args, eventFilter);
      if (changed || args.changed) {
        me2.render();
      }
      return me2;
    }
    _handleEvent(e2, replay) {
      const me2 = this;
      const { _active: lastActive = [], options } = me2;
      const hoverOptions = options.hover;
      const useFinalPosition = replay;
      let active = [];
      let changed = false;
      let lastEvent = null;
      if (e2.type !== "mouseout") {
        active = me2.getElementsAtEventForMode(e2, hoverOptions.mode, hoverOptions, useFinalPosition);
        lastEvent = e2.type === "click" ? me2._lastEvent : e2;
      }
      me2._lastEvent = null;
      if (_isPointInArea(e2, me2.chartArea, me2._minPadding)) {
        callback(options.onHover, [e2, active, me2], me2);
        if (e2.type === "mouseup" || e2.type === "click" || e2.type === "contextmenu") {
          callback(options.onClick, [e2, active, me2], me2);
        }
      }
      changed = !_elementsEqual(active, lastActive);
      if (changed || replay) {
        me2._active = active;
        me2._updateHoverStyles(active, lastActive, replay);
      }
      me2._lastEvent = lastEvent;
      return changed;
    }
  };
  var invalidatePlugins = () => each(Chart.instances, (chart) => chart._plugins.invalidate());
  var enumerable = true;
  Object.defineProperties(Chart, {
    defaults: {
      enumerable,
      value: defaults
    },
    instances: {
      enumerable,
      value: instances
    },
    overrides: {
      enumerable,
      value: overrides
    },
    registry: {
      enumerable,
      value: registry
    },
    version: {
      enumerable,
      value: version
    },
    getChart: {
      enumerable,
      value: getChart
    },
    register: {
      enumerable,
      value: (...items) => {
        registry.add(...items);
        invalidatePlugins();
      }
    },
    unregister: {
      enumerable,
      value: (...items) => {
        registry.remove(...items);
        invalidatePlugins();
      }
    }
  });
  function clipArc(ctx, element, endAngle) {
    const { startAngle, pixelMargin, x: x2, y: y2, outerRadius, innerRadius } = element;
    let angleMargin = pixelMargin / outerRadius;
    ctx.beginPath();
    ctx.arc(x2, y2, outerRadius, startAngle - angleMargin, endAngle + angleMargin);
    if (innerRadius > pixelMargin) {
      angleMargin = pixelMargin / innerRadius;
      ctx.arc(x2, y2, innerRadius, endAngle + angleMargin, startAngle - angleMargin, true);
    } else {
      ctx.arc(x2, y2, pixelMargin, endAngle + HALF_PI, startAngle - HALF_PI);
    }
    ctx.closePath();
    ctx.clip();
  }
  function toRadiusCorners(value) {
    return _readValueToProps(value, ["outerStart", "outerEnd", "innerStart", "innerEnd"]);
  }
  function parseBorderRadius$1(arc, innerRadius, outerRadius, angleDelta) {
    const o2 = toRadiusCorners(arc.options.borderRadius);
    const halfThickness = (outerRadius - innerRadius) / 2;
    const innerLimit = Math.min(halfThickness, angleDelta * innerRadius / 2);
    const computeOuterLimit = (val) => {
      const outerArcLimit = (outerRadius - Math.min(halfThickness, val)) * angleDelta / 2;
      return _limitValue(val, 0, Math.min(halfThickness, outerArcLimit));
    };
    return {
      outerStart: computeOuterLimit(o2.outerStart),
      outerEnd: computeOuterLimit(o2.outerEnd),
      innerStart: _limitValue(o2.innerStart, 0, innerLimit),
      innerEnd: _limitValue(o2.innerEnd, 0, innerLimit)
    };
  }
  function rThetaToXY(r2, theta, x2, y2) {
    return {
      x: x2 + r2 * Math.cos(theta),
      y: y2 + r2 * Math.sin(theta)
    };
  }
  function pathArc(ctx, element, offset2, spacing, end2) {
    const { x: x2, y: y2, startAngle: start4, pixelMargin, innerRadius: innerR } = element;
    const outerRadius = Math.max(element.outerRadius + spacing + offset2 - pixelMargin, 0);
    const innerRadius = innerR > 0 ? innerR + spacing + offset2 + pixelMargin : 0;
    let spacingOffset = 0;
    const alpha = end2 - start4;
    if (spacing) {
      const noSpacingInnerRadius = innerR > 0 ? innerR - spacing : 0;
      const noSpacingOuterRadius = outerRadius > 0 ? outerRadius - spacing : 0;
      const avNogSpacingRadius = (noSpacingInnerRadius + noSpacingOuterRadius) / 2;
      const adjustedAngle = avNogSpacingRadius !== 0 ? alpha * avNogSpacingRadius / (avNogSpacingRadius + spacing) : alpha;
      spacingOffset = (alpha - adjustedAngle) / 2;
    }
    const beta = Math.max(1e-3, alpha * outerRadius - offset2 / PI) / outerRadius;
    const angleOffset = (alpha - beta) / 2;
    const startAngle = start4 + angleOffset + spacingOffset;
    const endAngle = end2 - angleOffset - spacingOffset;
    const { outerStart, outerEnd, innerStart, innerEnd } = parseBorderRadius$1(element, innerRadius, outerRadius, endAngle - startAngle);
    const outerStartAdjustedRadius = outerRadius - outerStart;
    const outerEndAdjustedRadius = outerRadius - outerEnd;
    const outerStartAdjustedAngle = startAngle + outerStart / outerStartAdjustedRadius;
    const outerEndAdjustedAngle = endAngle - outerEnd / outerEndAdjustedRadius;
    const innerStartAdjustedRadius = innerRadius + innerStart;
    const innerEndAdjustedRadius = innerRadius + innerEnd;
    const innerStartAdjustedAngle = startAngle + innerStart / innerStartAdjustedRadius;
    const innerEndAdjustedAngle = endAngle - innerEnd / innerEndAdjustedRadius;
    ctx.beginPath();
    ctx.arc(x2, y2, outerRadius, outerStartAdjustedAngle, outerEndAdjustedAngle);
    if (outerEnd > 0) {
      const pCenter = rThetaToXY(outerEndAdjustedRadius, outerEndAdjustedAngle, x2, y2);
      ctx.arc(pCenter.x, pCenter.y, outerEnd, outerEndAdjustedAngle, endAngle + HALF_PI);
    }
    const p4 = rThetaToXY(innerEndAdjustedRadius, endAngle, x2, y2);
    ctx.lineTo(p4.x, p4.y);
    if (innerEnd > 0) {
      const pCenter = rThetaToXY(innerEndAdjustedRadius, innerEndAdjustedAngle, x2, y2);
      ctx.arc(pCenter.x, pCenter.y, innerEnd, endAngle + HALF_PI, innerEndAdjustedAngle + Math.PI);
    }
    ctx.arc(x2, y2, innerRadius, endAngle - innerEnd / innerRadius, startAngle + innerStart / innerRadius, true);
    if (innerStart > 0) {
      const pCenter = rThetaToXY(innerStartAdjustedRadius, innerStartAdjustedAngle, x2, y2);
      ctx.arc(pCenter.x, pCenter.y, innerStart, innerStartAdjustedAngle + Math.PI, startAngle - HALF_PI);
    }
    const p8 = rThetaToXY(outerStartAdjustedRadius, startAngle, x2, y2);
    ctx.lineTo(p8.x, p8.y);
    if (outerStart > 0) {
      const pCenter = rThetaToXY(outerStartAdjustedRadius, outerStartAdjustedAngle, x2, y2);
      ctx.arc(pCenter.x, pCenter.y, outerStart, startAngle - HALF_PI, outerStartAdjustedAngle);
    }
    ctx.closePath();
  }
  function drawArc(ctx, element, offset2, spacing) {
    const { fullCircles, startAngle, circumference } = element;
    let endAngle = element.endAngle;
    if (fullCircles) {
      pathArc(ctx, element, offset2, spacing, startAngle + TAU);
      for (let i2 = 0; i2 < fullCircles; ++i2) {
        ctx.fill();
      }
      if (!isNaN(circumference)) {
        endAngle = startAngle + circumference % TAU;
        if (circumference % TAU === 0) {
          endAngle += TAU;
        }
      }
    }
    pathArc(ctx, element, offset2, spacing, endAngle);
    ctx.fill();
    return endAngle;
  }
  function drawFullCircleBorders(ctx, element, inner) {
    const { x: x2, y: y2, startAngle, pixelMargin, fullCircles } = element;
    const outerRadius = Math.max(element.outerRadius - pixelMargin, 0);
    const innerRadius = element.innerRadius + pixelMargin;
    let i2;
    if (inner) {
      clipArc(ctx, element, startAngle + TAU);
    }
    ctx.beginPath();
    ctx.arc(x2, y2, innerRadius, startAngle + TAU, startAngle, true);
    for (i2 = 0; i2 < fullCircles; ++i2) {
      ctx.stroke();
    }
    ctx.beginPath();
    ctx.arc(x2, y2, outerRadius, startAngle, startAngle + TAU);
    for (i2 = 0; i2 < fullCircles; ++i2) {
      ctx.stroke();
    }
  }
  function drawBorder(ctx, element, offset2, spacing, endAngle) {
    const { options } = element;
    const inner = options.borderAlign === "inner";
    if (!options.borderWidth) {
      return;
    }
    if (inner) {
      ctx.lineWidth = options.borderWidth * 2;
      ctx.lineJoin = "round";
    } else {
      ctx.lineWidth = options.borderWidth;
      ctx.lineJoin = "bevel";
    }
    if (element.fullCircles) {
      drawFullCircleBorders(ctx, element, inner);
    }
    if (inner) {
      clipArc(ctx, element, endAngle);
    }
    pathArc(ctx, element, offset2, spacing, endAngle);
    ctx.stroke();
  }
  var ArcElement = class extends Element2 {
    constructor(cfg) {
      super();
      this.options = void 0;
      this.circumference = void 0;
      this.startAngle = void 0;
      this.endAngle = void 0;
      this.innerRadius = void 0;
      this.outerRadius = void 0;
      this.pixelMargin = 0;
      this.fullCircles = 0;
      if (cfg) {
        Object.assign(this, cfg);
      }
    }
    inRange(chartX, chartY, useFinalPosition) {
      const point = this.getProps(["x", "y"], useFinalPosition);
      const { angle, distance } = getAngleFromPoint(point, { x: chartX, y: chartY });
      const { startAngle, endAngle, innerRadius, outerRadius, circumference } = this.getProps([
        "startAngle",
        "endAngle",
        "innerRadius",
        "outerRadius",
        "circumference"
      ], useFinalPosition);
      const rAdjust = this.options.spacing / 2;
      const betweenAngles = circumference >= TAU || _angleBetween(angle, startAngle, endAngle);
      const withinRadius = distance >= innerRadius + rAdjust && distance <= outerRadius + rAdjust;
      return betweenAngles && withinRadius;
    }
    getCenterPoint(useFinalPosition) {
      const { x: x2, y: y2, startAngle, endAngle, innerRadius, outerRadius } = this.getProps([
        "x",
        "y",
        "startAngle",
        "endAngle",
        "innerRadius",
        "outerRadius",
        "circumference"
      ], useFinalPosition);
      const { offset: offset2, spacing } = this.options;
      const halfAngle = (startAngle + endAngle) / 2;
      const halfRadius = (innerRadius + outerRadius + spacing + offset2) / 2;
      return {
        x: x2 + Math.cos(halfAngle) * halfRadius,
        y: y2 + Math.sin(halfAngle) * halfRadius
      };
    }
    tooltipPosition(useFinalPosition) {
      return this.getCenterPoint(useFinalPosition);
    }
    draw(ctx) {
      const me2 = this;
      const { options, circumference } = me2;
      const offset2 = (options.offset || 0) / 2;
      const spacing = (options.spacing || 0) / 2;
      me2.pixelMargin = options.borderAlign === "inner" ? 0.33 : 0;
      me2.fullCircles = circumference > TAU ? Math.floor(circumference / TAU) : 0;
      if (circumference === 0 || me2.innerRadius < 0 || me2.outerRadius < 0) {
        return;
      }
      ctx.save();
      let radiusOffset = 0;
      if (offset2) {
        radiusOffset = offset2 / 2;
        const halfAngle = (me2.startAngle + me2.endAngle) / 2;
        ctx.translate(Math.cos(halfAngle) * radiusOffset, Math.sin(halfAngle) * radiusOffset);
        if (me2.circumference >= PI) {
          radiusOffset = offset2;
        }
      }
      ctx.fillStyle = options.backgroundColor;
      ctx.strokeStyle = options.borderColor;
      const endAngle = drawArc(ctx, me2, radiusOffset, spacing);
      drawBorder(ctx, me2, radiusOffset, spacing, endAngle);
      ctx.restore();
    }
  };
  ArcElement.id = "arc";
  ArcElement.defaults = {
    borderAlign: "center",
    borderColor: "#fff",
    borderRadius: 0,
    borderWidth: 2,
    offset: 0,
    spacing: 0,
    angle: void 0
  };
  ArcElement.defaultRoutes = {
    backgroundColor: "backgroundColor"
  };
  function setStyle(ctx, options, style = options) {
    ctx.lineCap = valueOrDefault(style.borderCapStyle, options.borderCapStyle);
    ctx.setLineDash(valueOrDefault(style.borderDash, options.borderDash));
    ctx.lineDashOffset = valueOrDefault(style.borderDashOffset, options.borderDashOffset);
    ctx.lineJoin = valueOrDefault(style.borderJoinStyle, options.borderJoinStyle);
    ctx.lineWidth = valueOrDefault(style.borderWidth, options.borderWidth);
    ctx.strokeStyle = valueOrDefault(style.borderColor, options.borderColor);
  }
  function lineTo(ctx, previous, target) {
    ctx.lineTo(target.x, target.y);
  }
  function getLineMethod(options) {
    if (options.stepped) {
      return _steppedLineTo;
    }
    if (options.tension || options.cubicInterpolationMode === "monotone") {
      return _bezierCurveTo;
    }
    return lineTo;
  }
  function pathVars(points, segment, params = {}) {
    const count = points.length;
    const { start: paramsStart = 0, end: paramsEnd = count - 1 } = params;
    const { start: segmentStart, end: segmentEnd } = segment;
    const start4 = Math.max(paramsStart, segmentStart);
    const end2 = Math.min(paramsEnd, segmentEnd);
    const outside = paramsStart < segmentStart && paramsEnd < segmentStart || paramsStart > segmentEnd && paramsEnd > segmentEnd;
    return {
      count,
      start: start4,
      loop: segment.loop,
      ilen: end2 < start4 && !outside ? count + end2 - start4 : end2 - start4
    };
  }
  function pathSegment(ctx, line, segment, params) {
    const { points, options } = line;
    const { count, start: start4, loop, ilen } = pathVars(points, segment, params);
    const lineMethod = getLineMethod(options);
    let { move = true, reverse } = params || {};
    let i2, point, prev;
    for (i2 = 0; i2 <= ilen; ++i2) {
      point = points[(start4 + (reverse ? ilen - i2 : i2)) % count];
      if (point.skip) {
        continue;
      } else if (move) {
        ctx.moveTo(point.x, point.y);
        move = false;
      } else {
        lineMethod(ctx, prev, point, reverse, options.stepped);
      }
      prev = point;
    }
    if (loop) {
      point = points[(start4 + (reverse ? ilen : 0)) % count];
      lineMethod(ctx, prev, point, reverse, options.stepped);
    }
    return !!loop;
  }
  function fastPathSegment(ctx, line, segment, params) {
    const points = line.points;
    const { count, start: start4, ilen } = pathVars(points, segment, params);
    const { move = true, reverse } = params || {};
    let avgX = 0;
    let countX = 0;
    let i2, point, prevX, minY, maxY, lastY;
    const pointIndex = (index) => (start4 + (reverse ? ilen - index : index)) % count;
    const drawX = () => {
      if (minY !== maxY) {
        ctx.lineTo(avgX, maxY);
        ctx.lineTo(avgX, minY);
        ctx.lineTo(avgX, lastY);
      }
    };
    if (move) {
      point = points[pointIndex(0)];
      ctx.moveTo(point.x, point.y);
    }
    for (i2 = 0; i2 <= ilen; ++i2) {
      point = points[pointIndex(i2)];
      if (point.skip) {
        continue;
      }
      const x2 = point.x;
      const y2 = point.y;
      const truncX = x2 | 0;
      if (truncX === prevX) {
        if (y2 < minY) {
          minY = y2;
        } else if (y2 > maxY) {
          maxY = y2;
        }
        avgX = (countX * avgX + x2) / ++countX;
      } else {
        drawX();
        ctx.lineTo(x2, y2);
        prevX = truncX;
        countX = 0;
        minY = maxY = y2;
      }
      lastY = y2;
    }
    drawX();
  }
  function _getSegmentMethod(line) {
    const opts = line.options;
    const borderDash = opts.borderDash && opts.borderDash.length;
    const useFastPath = !line._decimated && !line._loop && !opts.tension && opts.cubicInterpolationMode !== "monotone" && !opts.stepped && !borderDash;
    return useFastPath ? fastPathSegment : pathSegment;
  }
  function _getInterpolationMethod(options) {
    if (options.stepped) {
      return _steppedInterpolation;
    }
    if (options.tension || options.cubicInterpolationMode === "monotone") {
      return _bezierInterpolation;
    }
    return _pointInLine;
  }
  function strokePathWithCache(ctx, line, start4, count) {
    let path = line._path;
    if (!path) {
      path = line._path = new Path2D();
      if (line.path(path, start4, count)) {
        path.closePath();
      }
    }
    setStyle(ctx, line.options);
    ctx.stroke(path);
  }
  function strokePathDirect(ctx, line, start4, count) {
    const { segments, options } = line;
    const segmentMethod = _getSegmentMethod(line);
    for (const segment of segments) {
      setStyle(ctx, options, segment.style);
      ctx.beginPath();
      if (segmentMethod(ctx, line, segment, { start: start4, end: start4 + count - 1 })) {
        ctx.closePath();
      }
      ctx.stroke();
    }
  }
  var usePath2D = typeof Path2D === "function";
  function draw(ctx, line, start4, count) {
    if (usePath2D && line.segments.length === 1) {
      strokePathWithCache(ctx, line, start4, count);
    } else {
      strokePathDirect(ctx, line, start4, count);
    }
  }
  var LineElement = class extends Element2 {
    constructor(cfg) {
      super();
      this.animated = true;
      this.options = void 0;
      this._loop = void 0;
      this._fullLoop = void 0;
      this._path = void 0;
      this._points = void 0;
      this._segments = void 0;
      this._decimated = false;
      this._pointsUpdated = false;
      this._datasetIndex = void 0;
      if (cfg) {
        Object.assign(this, cfg);
      }
    }
    updateControlPoints(chartArea, indexAxis) {
      const me2 = this;
      const options = me2.options;
      if ((options.tension || options.cubicInterpolationMode === "monotone") && !options.stepped && !me2._pointsUpdated) {
        const loop = options.spanGaps ? me2._loop : me2._fullLoop;
        _updateBezierControlPoints(me2._points, options, chartArea, loop, indexAxis);
        me2._pointsUpdated = true;
      }
    }
    set points(points) {
      const me2 = this;
      me2._points = points;
      delete me2._segments;
      delete me2._path;
      me2._pointsUpdated = false;
    }
    get points() {
      return this._points;
    }
    get segments() {
      return this._segments || (this._segments = _computeSegments(this, this.options.segment));
    }
    first() {
      const segments = this.segments;
      const points = this.points;
      return segments.length && points[segments[0].start];
    }
    last() {
      const segments = this.segments;
      const points = this.points;
      const count = segments.length;
      return count && points[segments[count - 1].end];
    }
    interpolate(point, property) {
      const me2 = this;
      const options = me2.options;
      const value = point[property];
      const points = me2.points;
      const segments = _boundSegments(me2, { property, start: value, end: value });
      if (!segments.length) {
        return;
      }
      const result = [];
      const _interpolate = _getInterpolationMethod(options);
      let i2, ilen;
      for (i2 = 0, ilen = segments.length; i2 < ilen; ++i2) {
        const { start: start4, end: end2 } = segments[i2];
        const p1 = points[start4];
        const p2 = points[end2];
        if (p1 === p2) {
          result.push(p1);
          continue;
        }
        const t2 = Math.abs((value - p1[property]) / (p2[property] - p1[property]));
        const interpolated = _interpolate(p1, p2, t2, options.stepped);
        interpolated[property] = point[property];
        result.push(interpolated);
      }
      return result.length === 1 ? result[0] : result;
    }
    pathSegment(ctx, segment, params) {
      const segmentMethod = _getSegmentMethod(this);
      return segmentMethod(ctx, this, segment, params);
    }
    path(ctx, start4, count) {
      const me2 = this;
      const segments = me2.segments;
      const segmentMethod = _getSegmentMethod(me2);
      let loop = me2._loop;
      start4 = start4 || 0;
      count = count || me2.points.length - start4;
      for (const segment of segments) {
        loop &= segmentMethod(ctx, me2, segment, { start: start4, end: start4 + count - 1 });
      }
      return !!loop;
    }
    draw(ctx, chartArea, start4, count) {
      const me2 = this;
      const options = me2.options || {};
      const points = me2.points || [];
      if (!points.length || !options.borderWidth) {
        return;
      }
      ctx.save();
      draw(ctx, me2, start4, count);
      ctx.restore();
      if (me2.animated) {
        me2._pointsUpdated = false;
        me2._path = void 0;
      }
    }
  };
  LineElement.id = "line";
  LineElement.defaults = {
    borderCapStyle: "butt",
    borderDash: [],
    borderDashOffset: 0,
    borderJoinStyle: "miter",
    borderWidth: 3,
    capBezierPoints: true,
    cubicInterpolationMode: "default",
    fill: false,
    spanGaps: false,
    stepped: false,
    tension: 0
  };
  LineElement.defaultRoutes = {
    backgroundColor: "backgroundColor",
    borderColor: "borderColor"
  };
  LineElement.descriptors = {
    _scriptable: true,
    _indexable: (name) => name !== "borderDash" && name !== "fill"
  };
  function inRange$1(el, pos, axis, useFinalPosition) {
    const options = el.options;
    const { [axis]: value } = el.getProps([axis], useFinalPosition);
    return Math.abs(pos - value) < options.radius + options.hitRadius;
  }
  var PointElement = class extends Element2 {
    constructor(cfg) {
      super();
      this.options = void 0;
      this.parsed = void 0;
      this.skip = void 0;
      this.stop = void 0;
      if (cfg) {
        Object.assign(this, cfg);
      }
    }
    inRange(mouseX, mouseY, useFinalPosition) {
      const options = this.options;
      const { x: x2, y: y2 } = this.getProps(["x", "y"], useFinalPosition);
      return Math.pow(mouseX - x2, 2) + Math.pow(mouseY - y2, 2) < Math.pow(options.hitRadius + options.radius, 2);
    }
    inXRange(mouseX, useFinalPosition) {
      return inRange$1(this, mouseX, "x", useFinalPosition);
    }
    inYRange(mouseY, useFinalPosition) {
      return inRange$1(this, mouseY, "y", useFinalPosition);
    }
    getCenterPoint(useFinalPosition) {
      const { x: x2, y: y2 } = this.getProps(["x", "y"], useFinalPosition);
      return { x: x2, y: y2 };
    }
    size(options) {
      options = options || this.options || {};
      let radius = options.radius || 0;
      radius = Math.max(radius, radius && options.hoverRadius || 0);
      const borderWidth = radius && options.borderWidth || 0;
      return (radius + borderWidth) * 2;
    }
    draw(ctx, area) {
      const me2 = this;
      const options = me2.options;
      if (me2.skip || options.radius < 0.1 || !_isPointInArea(me2, area, me2.size(options) / 2)) {
        return;
      }
      ctx.strokeStyle = options.borderColor;
      ctx.lineWidth = options.borderWidth;
      ctx.fillStyle = options.backgroundColor;
      drawPoint(ctx, options, me2.x, me2.y);
    }
    getRange() {
      const options = this.options || {};
      return options.radius + options.hitRadius;
    }
  };
  PointElement.id = "point";
  PointElement.defaults = {
    borderWidth: 1,
    hitRadius: 1,
    hoverBorderWidth: 1,
    hoverRadius: 4,
    pointStyle: "circle",
    radius: 3,
    rotation: 0
  };
  PointElement.defaultRoutes = {
    backgroundColor: "backgroundColor",
    borderColor: "borderColor"
  };
  function getBarBounds(bar, useFinalPosition) {
    const { x: x2, y: y2, base, width, height } = bar.getProps(["x", "y", "base", "width", "height"], useFinalPosition);
    let left2, right2, top2, bottom2, half;
    if (bar.horizontal) {
      half = height / 2;
      left2 = Math.min(x2, base);
      right2 = Math.max(x2, base);
      top2 = y2 - half;
      bottom2 = y2 + half;
    } else {
      half = width / 2;
      left2 = x2 - half;
      right2 = x2 + half;
      top2 = Math.min(y2, base);
      bottom2 = Math.max(y2, base);
    }
    return { left: left2, top: top2, right: right2, bottom: bottom2 };
  }
  function skipOrLimit(skip2, value, min2, max2) {
    return skip2 ? 0 : _limitValue(value, min2, max2);
  }
  function parseBorderWidth(bar, maxW, maxH) {
    const value = bar.options.borderWidth;
    const skip2 = bar.borderSkipped;
    const o2 = toTRBL(value);
    return {
      t: skipOrLimit(skip2.top, o2.top, 0, maxH),
      r: skipOrLimit(skip2.right, o2.right, 0, maxW),
      b: skipOrLimit(skip2.bottom, o2.bottom, 0, maxH),
      l: skipOrLimit(skip2.left, o2.left, 0, maxW)
    };
  }
  function parseBorderRadius(bar, maxW, maxH) {
    const { enableBorderRadius } = bar.getProps(["enableBorderRadius"]);
    const value = bar.options.borderRadius;
    const o2 = toTRBLCorners(value);
    const maxR = Math.min(maxW, maxH);
    const skip2 = bar.borderSkipped;
    const enableBorder = enableBorderRadius || isObject(value);
    return {
      topLeft: skipOrLimit(!enableBorder || skip2.top || skip2.left, o2.topLeft, 0, maxR),
      topRight: skipOrLimit(!enableBorder || skip2.top || skip2.right, o2.topRight, 0, maxR),
      bottomLeft: skipOrLimit(!enableBorder || skip2.bottom || skip2.left, o2.bottomLeft, 0, maxR),
      bottomRight: skipOrLimit(!enableBorder || skip2.bottom || skip2.right, o2.bottomRight, 0, maxR)
    };
  }
  function boundingRects(bar) {
    const bounds = getBarBounds(bar);
    const width = bounds.right - bounds.left;
    const height = bounds.bottom - bounds.top;
    const border = parseBorderWidth(bar, width / 2, height / 2);
    const radius = parseBorderRadius(bar, width / 2, height / 2);
    return {
      outer: {
        x: bounds.left,
        y: bounds.top,
        w: width,
        h: height,
        radius
      },
      inner: {
        x: bounds.left + border.l,
        y: bounds.top + border.t,
        w: width - border.l - border.r,
        h: height - border.t - border.b,
        radius: {
          topLeft: Math.max(0, radius.topLeft - Math.max(border.t, border.l)),
          topRight: Math.max(0, radius.topRight - Math.max(border.t, border.r)),
          bottomLeft: Math.max(0, radius.bottomLeft - Math.max(border.b, border.l)),
          bottomRight: Math.max(0, radius.bottomRight - Math.max(border.b, border.r))
        }
      }
    };
  }
  function inRange(bar, x2, y2, useFinalPosition) {
    const skipX = x2 === null;
    const skipY = y2 === null;
    const skipBoth = skipX && skipY;
    const bounds = bar && !skipBoth && getBarBounds(bar, useFinalPosition);
    return bounds && (skipX || x2 >= bounds.left && x2 <= bounds.right) && (skipY || y2 >= bounds.top && y2 <= bounds.bottom);
  }
  function hasRadius(radius) {
    return radius.topLeft || radius.topRight || radius.bottomLeft || radius.bottomRight;
  }
  function addNormalRectPath(ctx, rect) {
    ctx.rect(rect.x, rect.y, rect.w, rect.h);
  }
  function inflateRect(rect, amount, refRect = {}) {
    const x2 = rect.x !== refRect.x ? -amount : 0;
    const y2 = rect.y !== refRect.y ? -amount : 0;
    const w2 = (rect.x + rect.w !== refRect.x + refRect.w ? amount : 0) - x2;
    const h3 = (rect.y + rect.h !== refRect.y + refRect.h ? amount : 0) - y2;
    return {
      x: rect.x + x2,
      y: rect.y + y2,
      w: rect.w + w2,
      h: rect.h + h3,
      radius: rect.radius
    };
  }
  var BarElement = class extends Element2 {
    constructor(cfg) {
      super();
      this.options = void 0;
      this.horizontal = void 0;
      this.base = void 0;
      this.width = void 0;
      this.height = void 0;
      if (cfg) {
        Object.assign(this, cfg);
      }
    }
    draw(ctx) {
      const options = this.options;
      const { inner, outer } = boundingRects(this);
      const addRectPath = hasRadius(outer.radius) ? addRoundedRectPath : addNormalRectPath;
      const inflateAmount = 0.33;
      ctx.save();
      if (outer.w !== inner.w || outer.h !== inner.h) {
        ctx.beginPath();
        addRectPath(ctx, inflateRect(outer, inflateAmount, inner));
        ctx.clip();
        addRectPath(ctx, inflateRect(inner, -inflateAmount, outer));
        ctx.fillStyle = options.borderColor;
        ctx.fill("evenodd");
      }
      ctx.beginPath();
      addRectPath(ctx, inflateRect(inner, inflateAmount, outer));
      ctx.fillStyle = options.backgroundColor;
      ctx.fill();
      ctx.restore();
    }
    inRange(mouseX, mouseY, useFinalPosition) {
      return inRange(this, mouseX, mouseY, useFinalPosition);
    }
    inXRange(mouseX, useFinalPosition) {
      return inRange(this, mouseX, null, useFinalPosition);
    }
    inYRange(mouseY, useFinalPosition) {
      return inRange(this, null, mouseY, useFinalPosition);
    }
    getCenterPoint(useFinalPosition) {
      const { x: x2, y: y2, base, horizontal } = this.getProps(["x", "y", "base", "horizontal"], useFinalPosition);
      return {
        x: horizontal ? (x2 + base) / 2 : x2,
        y: horizontal ? y2 : (y2 + base) / 2
      };
    }
    getRange(axis) {
      return axis === "x" ? this.width / 2 : this.height / 2;
    }
  };
  BarElement.id = "bar";
  BarElement.defaults = {
    borderSkipped: "start",
    borderWidth: 0,
    borderRadius: 0,
    enableBorderRadius: true,
    pointStyle: void 0
  };
  BarElement.defaultRoutes = {
    backgroundColor: "backgroundColor",
    borderColor: "borderColor"
  };
  var elements = /* @__PURE__ */ Object.freeze({
    __proto__: null,
    ArcElement,
    LineElement,
    PointElement,
    BarElement
  });
  function lttbDecimation(data, start4, count, availableWidth, options) {
    const samples = options.samples || availableWidth;
    if (samples >= count) {
      return data.slice(start4, start4 + count);
    }
    const decimated = [];
    const bucketWidth = (count - 2) / (samples - 2);
    let sampledIndex = 0;
    const endIndex = start4 + count - 1;
    let a2 = start4;
    let i2, maxAreaPoint, maxArea, area, nextA;
    decimated[sampledIndex++] = data[a2];
    for (i2 = 0; i2 < samples - 2; i2++) {
      let avgX = 0;
      let avgY = 0;
      let j2;
      const avgRangeStart = Math.floor((i2 + 1) * bucketWidth) + 1 + start4;
      const avgRangeEnd = Math.min(Math.floor((i2 + 2) * bucketWidth) + 1, count) + start4;
      const avgRangeLength = avgRangeEnd - avgRangeStart;
      for (j2 = avgRangeStart; j2 < avgRangeEnd; j2++) {
        avgX += data[j2].x;
        avgY += data[j2].y;
      }
      avgX /= avgRangeLength;
      avgY /= avgRangeLength;
      const rangeOffs = Math.floor(i2 * bucketWidth) + 1 + start4;
      const rangeTo = Math.min(Math.floor((i2 + 1) * bucketWidth) + 1, count) + start4;
      const { x: pointAx, y: pointAy } = data[a2];
      maxArea = area = -1;
      for (j2 = rangeOffs; j2 < rangeTo; j2++) {
        area = 0.5 * Math.abs((pointAx - avgX) * (data[j2].y - pointAy) - (pointAx - data[j2].x) * (avgY - pointAy));
        if (area > maxArea) {
          maxArea = area;
          maxAreaPoint = data[j2];
          nextA = j2;
        }
      }
      decimated[sampledIndex++] = maxAreaPoint;
      a2 = nextA;
    }
    decimated[sampledIndex++] = data[endIndex];
    return decimated;
  }
  function minMaxDecimation(data, start4, count, availableWidth) {
    let avgX = 0;
    let countX = 0;
    let i2, point, x2, y2, prevX, minIndex, maxIndex, startIndex, minY, maxY;
    const decimated = [];
    const endIndex = start4 + count - 1;
    const xMin = data[start4].x;
    const xMax = data[endIndex].x;
    const dx = xMax - xMin;
    for (i2 = start4; i2 < start4 + count; ++i2) {
      point = data[i2];
      x2 = (point.x - xMin) / dx * availableWidth;
      y2 = point.y;
      const truncX = x2 | 0;
      if (truncX === prevX) {
        if (y2 < minY) {
          minY = y2;
          minIndex = i2;
        } else if (y2 > maxY) {
          maxY = y2;
          maxIndex = i2;
        }
        avgX = (countX * avgX + point.x) / ++countX;
      } else {
        const lastIndex = i2 - 1;
        if (!isNullOrUndef(minIndex) && !isNullOrUndef(maxIndex)) {
          const intermediateIndex1 = Math.min(minIndex, maxIndex);
          const intermediateIndex2 = Math.max(minIndex, maxIndex);
          if (intermediateIndex1 !== startIndex && intermediateIndex1 !== lastIndex) {
            decimated.push({
              ...data[intermediateIndex1],
              x: avgX
            });
          }
          if (intermediateIndex2 !== startIndex && intermediateIndex2 !== lastIndex) {
            decimated.push({
              ...data[intermediateIndex2],
              x: avgX
            });
          }
        }
        if (i2 > 0 && lastIndex !== startIndex) {
          decimated.push(data[lastIndex]);
        }
        decimated.push(point);
        prevX = truncX;
        countX = 0;
        minY = maxY = y2;
        minIndex = maxIndex = startIndex = i2;
      }
    }
    return decimated;
  }
  function cleanDecimatedDataset(dataset) {
    if (dataset._decimated) {
      const data = dataset._data;
      delete dataset._decimated;
      delete dataset._data;
      Object.defineProperty(dataset, "data", { value: data });
    }
  }
  function cleanDecimatedData(chart) {
    chart.data.datasets.forEach((dataset) => {
      cleanDecimatedDataset(dataset);
    });
  }
  function getStartAndCountOfVisiblePointsSimplified(meta, points) {
    const pointCount = points.length;
    let start4 = 0;
    let count;
    const { iScale } = meta;
    const { min: min2, max: max2, minDefined, maxDefined } = iScale.getUserBounds();
    if (minDefined) {
      start4 = _limitValue(_lookupByKey(points, iScale.axis, min2).lo, 0, pointCount - 1);
    }
    if (maxDefined) {
      count = _limitValue(_lookupByKey(points, iScale.axis, max2).hi + 1, start4, pointCount) - start4;
    } else {
      count = pointCount - start4;
    }
    return { start: start4, count };
  }
  var plugin_decimation = {
    id: "decimation",
    defaults: {
      algorithm: "min-max",
      enabled: false
    },
    beforeElementsUpdate: (chart, args, options) => {
      if (!options.enabled) {
        cleanDecimatedData(chart);
        return;
      }
      const availableWidth = chart.width;
      chart.data.datasets.forEach((dataset, datasetIndex) => {
        const { _data, indexAxis } = dataset;
        const meta = chart.getDatasetMeta(datasetIndex);
        const data = _data || dataset.data;
        if (resolve([indexAxis, chart.options.indexAxis]) === "y") {
          return;
        }
        if (meta.type !== "line") {
          return;
        }
        const xAxis = chart.scales[meta.xAxisID];
        if (xAxis.type !== "linear" && xAxis.type !== "time") {
          return;
        }
        if (chart.options.parsing) {
          return;
        }
        let { start: start4, count } = getStartAndCountOfVisiblePointsSimplified(meta, data);
        const threshold = options.threshold || 4 * availableWidth;
        if (count <= threshold) {
          cleanDecimatedDataset(dataset);
          return;
        }
        if (isNullOrUndef(_data)) {
          dataset._data = data;
          delete dataset.data;
          Object.defineProperty(dataset, "data", {
            configurable: true,
            enumerable: true,
            get: function() {
              return this._decimated;
            },
            set: function(d2) {
              this._data = d2;
            }
          });
        }
        let decimated;
        switch (options.algorithm) {
          case "lttb":
            decimated = lttbDecimation(data, start4, count, availableWidth, options);
            break;
          case "min-max":
            decimated = minMaxDecimation(data, start4, count, availableWidth);
            break;
          default:
            throw new Error(`Unsupported decimation algorithm '${options.algorithm}'`);
        }
        dataset._decimated = decimated;
      });
    },
    destroy(chart) {
      cleanDecimatedData(chart);
    }
  };
  function getLineByIndex(chart, index) {
    const meta = chart.getDatasetMeta(index);
    const visible = meta && chart.isDatasetVisible(index);
    return visible ? meta.dataset : null;
  }
  function parseFillOption(line) {
    const options = line.options;
    const fillOption = options.fill;
    let fill = valueOrDefault(fillOption && fillOption.target, fillOption);
    if (fill === void 0) {
      fill = !!options.backgroundColor;
    }
    if (fill === false || fill === null) {
      return false;
    }
    if (fill === true) {
      return "origin";
    }
    return fill;
  }
  function decodeFill(line, index, count) {
    const fill = parseFillOption(line);
    if (isObject(fill)) {
      return isNaN(fill.value) ? false : fill;
    }
    let target = parseFloat(fill);
    if (isNumberFinite(target) && Math.floor(target) === target) {
      if (fill[0] === "-" || fill[0] === "+") {
        target = index + target;
      }
      if (target === index || target < 0 || target >= count) {
        return false;
      }
      return target;
    }
    return ["origin", "start", "end", "stack", "shape"].indexOf(fill) >= 0 && fill;
  }
  function computeLinearBoundary(source) {
    const { scale = {}, fill } = source;
    let target = null;
    let horizontal;
    if (fill === "start") {
      target = scale.bottom;
    } else if (fill === "end") {
      target = scale.top;
    } else if (isObject(fill)) {
      target = scale.getPixelForValue(fill.value);
    } else if (scale.getBasePixel) {
      target = scale.getBasePixel();
    }
    if (isNumberFinite(target)) {
      horizontal = scale.isHorizontal();
      return {
        x: horizontal ? target : null,
        y: horizontal ? null : target
      };
    }
    return null;
  }
  var simpleArc = class {
    constructor(opts) {
      this.x = opts.x;
      this.y = opts.y;
      this.radius = opts.radius;
    }
    pathSegment(ctx, bounds, opts) {
      const { x: x2, y: y2, radius } = this;
      bounds = bounds || { start: 0, end: TAU };
      ctx.arc(x2, y2, radius, bounds.end, bounds.start, true);
      return !opts.bounds;
    }
    interpolate(point) {
      const { x: x2, y: y2, radius } = this;
      const angle = point.angle;
      return {
        x: x2 + Math.cos(angle) * radius,
        y: y2 + Math.sin(angle) * radius,
        angle
      };
    }
  };
  function computeCircularBoundary(source) {
    const { scale, fill } = source;
    const options = scale.options;
    const length = scale.getLabels().length;
    const target = [];
    const start4 = options.reverse ? scale.max : scale.min;
    const end2 = options.reverse ? scale.min : scale.max;
    let i2, center, value;
    if (fill === "start") {
      value = start4;
    } else if (fill === "end") {
      value = end2;
    } else if (isObject(fill)) {
      value = fill.value;
    } else {
      value = scale.getBaseValue();
    }
    if (options.grid.circular) {
      center = scale.getPointPositionForValue(0, start4);
      return new simpleArc({
        x: center.x,
        y: center.y,
        radius: scale.getDistanceFromCenterForValue(value)
      });
    }
    for (i2 = 0; i2 < length; ++i2) {
      target.push(scale.getPointPositionForValue(i2, value));
    }
    return target;
  }
  function computeBoundary(source) {
    const scale = source.scale || {};
    if (scale.getPointPositionForValue) {
      return computeCircularBoundary(source);
    }
    return computeLinearBoundary(source);
  }
  function findSegmentEnd(start4, end2, points) {
    for (; end2 > start4; end2--) {
      const point = points[end2];
      if (!isNaN(point.x) && !isNaN(point.y)) {
        break;
      }
    }
    return end2;
  }
  function pointsFromSegments(boundary, line) {
    const { x: x2 = null, y: y2 = null } = boundary || {};
    const linePoints = line.points;
    const points = [];
    line.segments.forEach(({ start: start4, end: end2 }) => {
      end2 = findSegmentEnd(start4, end2, linePoints);
      const first = linePoints[start4];
      const last = linePoints[end2];
      if (y2 !== null) {
        points.push({ x: first.x, y: y2 });
        points.push({ x: last.x, y: y2 });
      } else if (x2 !== null) {
        points.push({ x: x2, y: first.y });
        points.push({ x: x2, y: last.y });
      }
    });
    return points;
  }
  function buildStackLine(source) {
    const { chart, scale, index, line } = source;
    const points = [];
    const segments = line.segments;
    const sourcePoints = line.points;
    const linesBelow = getLinesBelow(chart, index);
    linesBelow.push(createBoundaryLine({ x: null, y: scale.bottom }, line));
    for (let i2 = 0; i2 < segments.length; i2++) {
      const segment = segments[i2];
      for (let j2 = segment.start; j2 <= segment.end; j2++) {
        addPointsBelow(points, sourcePoints[j2], linesBelow);
      }
    }
    return new LineElement({ points, options: {} });
  }
  var isLineAndNotInHideAnimation = (meta) => meta.type === "line" && !meta.hidden;
  function getLinesBelow(chart, index) {
    const below = [];
    const metas = chart.getSortedVisibleDatasetMetas();
    for (let i2 = 0; i2 < metas.length; i2++) {
      const meta = metas[i2];
      if (meta.index === index) {
        break;
      }
      if (isLineAndNotInHideAnimation(meta)) {
        below.unshift(meta.dataset);
      }
    }
    return below;
  }
  function addPointsBelow(points, sourcePoint, linesBelow) {
    const postponed = [];
    for (let j2 = 0; j2 < linesBelow.length; j2++) {
      const line = linesBelow[j2];
      const { first, last, point } = findPoint(line, sourcePoint, "x");
      if (!point || first && last) {
        continue;
      }
      if (first) {
        postponed.unshift(point);
      } else {
        points.push(point);
        if (!last) {
          break;
        }
      }
    }
    points.push(...postponed);
  }
  function findPoint(line, sourcePoint, property) {
    const point = line.interpolate(sourcePoint, property);
    if (!point) {
      return {};
    }
    const pointValue = point[property];
    const segments = line.segments;
    const linePoints = line.points;
    let first = false;
    let last = false;
    for (let i2 = 0; i2 < segments.length; i2++) {
      const segment = segments[i2];
      const firstValue = linePoints[segment.start][property];
      const lastValue = linePoints[segment.end][property];
      if (pointValue >= firstValue && pointValue <= lastValue) {
        first = pointValue === firstValue;
        last = pointValue === lastValue;
        break;
      }
    }
    return { first, last, point };
  }
  function getTarget(source) {
    const { chart, fill, line } = source;
    if (isNumberFinite(fill)) {
      return getLineByIndex(chart, fill);
    }
    if (fill === "stack") {
      return buildStackLine(source);
    }
    if (fill === "shape") {
      return true;
    }
    const boundary = computeBoundary(source);
    if (boundary instanceof simpleArc) {
      return boundary;
    }
    return createBoundaryLine(boundary, line);
  }
  function createBoundaryLine(boundary, line) {
    let points = [];
    let _loop = false;
    if (isArray(boundary)) {
      _loop = true;
      points = boundary;
    } else {
      points = pointsFromSegments(boundary, line);
    }
    return points.length ? new LineElement({
      points,
      options: { tension: 0 },
      _loop,
      _fullLoop: _loop
    }) : null;
  }
  function resolveTarget(sources, index, propagate) {
    const source = sources[index];
    let fill = source.fill;
    const visited = [index];
    let target;
    if (!propagate) {
      return fill;
    }
    while (fill !== false && visited.indexOf(fill) === -1) {
      if (!isNumberFinite(fill)) {
        return fill;
      }
      target = sources[fill];
      if (!target) {
        return false;
      }
      if (target.visible) {
        return fill;
      }
      visited.push(fill);
      fill = target.fill;
    }
    return false;
  }
  function _clip(ctx, target, clipY) {
    ctx.beginPath();
    target.path(ctx);
    ctx.lineTo(target.last().x, clipY);
    ctx.lineTo(target.first().x, clipY);
    ctx.closePath();
    ctx.clip();
  }
  function getBounds(property, first, last, loop) {
    if (loop) {
      return;
    }
    let start4 = first[property];
    let end2 = last[property];
    if (property === "angle") {
      start4 = _normalizeAngle(start4);
      end2 = _normalizeAngle(end2);
    }
    return { property, start: start4, end: end2 };
  }
  function _getEdge(a2, b2, prop, fn3) {
    if (a2 && b2) {
      return fn3(a2[prop], b2[prop]);
    }
    return a2 ? a2[prop] : b2 ? b2[prop] : 0;
  }
  function _segments(line, target, property) {
    const segments = line.segments;
    const points = line.points;
    const tpoints = target.points;
    const parts = [];
    for (const segment of segments) {
      let { start: start4, end: end2 } = segment;
      end2 = findSegmentEnd(start4, end2, points);
      const bounds = getBounds(property, points[start4], points[end2], segment.loop);
      if (!target.segments) {
        parts.push({
          source: segment,
          target: bounds,
          start: points[start4],
          end: points[end2]
        });
        continue;
      }
      const targetSegments = _boundSegments(target, bounds);
      for (const tgt of targetSegments) {
        const subBounds = getBounds(property, tpoints[tgt.start], tpoints[tgt.end], tgt.loop);
        const fillSources = _boundSegment(segment, points, subBounds);
        for (const fillSource of fillSources) {
          parts.push({
            source: fillSource,
            target: tgt,
            start: {
              [property]: _getEdge(bounds, subBounds, "start", Math.max)
            },
            end: {
              [property]: _getEdge(bounds, subBounds, "end", Math.min)
            }
          });
        }
      }
    }
    return parts;
  }
  function clipBounds(ctx, scale, bounds) {
    const { top: top2, bottom: bottom2 } = scale.chart.chartArea;
    const { property, start: start4, end: end2 } = bounds || {};
    if (property === "x") {
      ctx.beginPath();
      ctx.rect(start4, top2, end2 - start4, bottom2 - top2);
      ctx.clip();
    }
  }
  function interpolatedLineTo(ctx, target, point, property) {
    const interpolatedPoint = target.interpolate(point, property);
    if (interpolatedPoint) {
      ctx.lineTo(interpolatedPoint.x, interpolatedPoint.y);
    }
  }
  function _fill(ctx, cfg) {
    const { line, target, property, color: color2, scale } = cfg;
    const segments = _segments(line, target, property);
    for (const { source: src, target: tgt, start: start4, end: end2 } of segments) {
      const { style: { backgroundColor = color2 } = {} } = src;
      const notShape = target !== true;
      ctx.save();
      ctx.fillStyle = backgroundColor;
      clipBounds(ctx, scale, notShape && getBounds(property, start4, end2));
      ctx.beginPath();
      const lineLoop = !!line.pathSegment(ctx, src);
      let loop;
      if (notShape) {
        if (lineLoop) {
          ctx.closePath();
        } else {
          interpolatedLineTo(ctx, target, end2, property);
        }
        const targetLoop = !!target.pathSegment(ctx, tgt, { move: lineLoop, reverse: true });
        loop = lineLoop && targetLoop;
        if (!loop) {
          interpolatedLineTo(ctx, target, start4, property);
        }
      }
      ctx.closePath();
      ctx.fill(loop ? "evenodd" : "nonzero");
      ctx.restore();
    }
  }
  function doFill(ctx, cfg) {
    const { line, target, above, below, area, scale } = cfg;
    const property = line._loop ? "angle" : cfg.axis;
    ctx.save();
    if (property === "x" && below !== above) {
      _clip(ctx, target, area.top);
      _fill(ctx, { line, target, color: above, scale, property });
      ctx.restore();
      ctx.save();
      _clip(ctx, target, area.bottom);
    }
    _fill(ctx, { line, target, color: below, scale, property });
    ctx.restore();
  }
  function drawfill(ctx, source, area) {
    const target = getTarget(source);
    const { line, scale, axis } = source;
    const lineOpts = line.options;
    const fillOption = lineOpts.fill;
    const color2 = lineOpts.backgroundColor;
    const { above = color2, below = color2 } = fillOption || {};
    if (target && line.points.length) {
      clipArea(ctx, area);
      doFill(ctx, { line, target, above, below, area, scale, axis });
      unclipArea(ctx);
    }
  }
  var plugin_filler = {
    id: "filler",
    afterDatasetsUpdate(chart, _args, options) {
      const count = (chart.data.datasets || []).length;
      const sources = [];
      let meta, i2, line, source;
      for (i2 = 0; i2 < count; ++i2) {
        meta = chart.getDatasetMeta(i2);
        line = meta.dataset;
        source = null;
        if (line && line.options && line instanceof LineElement) {
          source = {
            visible: chart.isDatasetVisible(i2),
            index: i2,
            fill: decodeFill(line, i2, count),
            chart,
            axis: meta.controller.options.indexAxis,
            scale: meta.vScale,
            line
          };
        }
        meta.$filler = source;
        sources.push(source);
      }
      for (i2 = 0; i2 < count; ++i2) {
        source = sources[i2];
        if (!source || source.fill === false) {
          continue;
        }
        source.fill = resolveTarget(sources, i2, options.propagate);
      }
    },
    beforeDraw(chart, _args, options) {
      const draw2 = options.drawTime === "beforeDraw";
      const metasets = chart.getSortedVisibleDatasetMetas();
      const area = chart.chartArea;
      for (let i2 = metasets.length - 1; i2 >= 0; --i2) {
        const source = metasets[i2].$filler;
        if (!source) {
          continue;
        }
        source.line.updateControlPoints(area, source.axis);
        if (draw2) {
          drawfill(chart.ctx, source, area);
        }
      }
    },
    beforeDatasetsDraw(chart, _args, options) {
      if (options.drawTime !== "beforeDatasetsDraw") {
        return;
      }
      const metasets = chart.getSortedVisibleDatasetMetas();
      for (let i2 = metasets.length - 1; i2 >= 0; --i2) {
        const source = metasets[i2].$filler;
        if (source) {
          drawfill(chart.ctx, source, chart.chartArea);
        }
      }
    },
    beforeDatasetDraw(chart, args, options) {
      const source = args.meta.$filler;
      if (!source || source.fill === false || options.drawTime !== "beforeDatasetDraw") {
        return;
      }
      drawfill(chart.ctx, source, chart.chartArea);
    },
    defaults: {
      propagate: true,
      drawTime: "beforeDatasetDraw"
    }
  };
  var getBoxSize = (labelOpts, fontSize) => {
    let { boxHeight = fontSize, boxWidth = fontSize } = labelOpts;
    if (labelOpts.usePointStyle) {
      boxHeight = Math.min(boxHeight, fontSize);
      boxWidth = Math.min(boxWidth, fontSize);
    }
    return {
      boxWidth,
      boxHeight,
      itemHeight: Math.max(fontSize, boxHeight)
    };
  };
  var itemsEqual = (a2, b2) => a2 !== null && b2 !== null && a2.datasetIndex === b2.datasetIndex && a2.index === b2.index;
  var Legend = class extends Element2 {
    constructor(config) {
      super();
      this._added = false;
      this.legendHitBoxes = [];
      this._hoveredItem = null;
      this.doughnutMode = false;
      this.chart = config.chart;
      this.options = config.options;
      this.ctx = config.ctx;
      this.legendItems = void 0;
      this.columnSizes = void 0;
      this.lineWidths = void 0;
      this.maxHeight = void 0;
      this.maxWidth = void 0;
      this.top = void 0;
      this.bottom = void 0;
      this.left = void 0;
      this.right = void 0;
      this.height = void 0;
      this.width = void 0;
      this._margins = void 0;
      this.position = void 0;
      this.weight = void 0;
      this.fullSize = void 0;
    }
    update(maxWidth, maxHeight, margins) {
      const me2 = this;
      me2.maxWidth = maxWidth;
      me2.maxHeight = maxHeight;
      me2._margins = margins;
      me2.setDimensions();
      me2.buildLabels();
      me2.fit();
    }
    setDimensions() {
      const me2 = this;
      if (me2.isHorizontal()) {
        me2.width = me2.maxWidth;
        me2.left = me2._margins.left;
        me2.right = me2.width;
      } else {
        me2.height = me2.maxHeight;
        me2.top = me2._margins.top;
        me2.bottom = me2.height;
      }
    }
    buildLabels() {
      const me2 = this;
      const labelOpts = me2.options.labels || {};
      let legendItems = callback(labelOpts.generateLabels, [me2.chart], me2) || [];
      if (labelOpts.filter) {
        legendItems = legendItems.filter((item) => labelOpts.filter(item, me2.chart.data));
      }
      if (labelOpts.sort) {
        legendItems = legendItems.sort((a2, b2) => labelOpts.sort(a2, b2, me2.chart.data));
      }
      if (me2.options.reverse) {
        legendItems.reverse();
      }
      me2.legendItems = legendItems;
    }
    fit() {
      const me2 = this;
      const { options, ctx } = me2;
      if (!options.display) {
        me2.width = me2.height = 0;
        return;
      }
      const labelOpts = options.labels;
      const labelFont = toFont(labelOpts.font);
      const fontSize = labelFont.size;
      const titleHeight = me2._computeTitleHeight();
      const { boxWidth, itemHeight } = getBoxSize(labelOpts, fontSize);
      let width, height;
      ctx.font = labelFont.string;
      if (me2.isHorizontal()) {
        width = me2.maxWidth;
        height = me2._fitRows(titleHeight, fontSize, boxWidth, itemHeight) + 10;
      } else {
        height = me2.maxHeight;
        width = me2._fitCols(titleHeight, fontSize, boxWidth, itemHeight) + 10;
      }
      me2.width = Math.min(width, options.maxWidth || me2.maxWidth);
      me2.height = Math.min(height, options.maxHeight || me2.maxHeight);
    }
    _fitRows(titleHeight, fontSize, boxWidth, itemHeight) {
      const me2 = this;
      const { ctx, maxWidth, options: { labels: { padding } } } = me2;
      const hitboxes = me2.legendHitBoxes = [];
      const lineWidths = me2.lineWidths = [0];
      const lineHeight = itemHeight + padding;
      let totalHeight = titleHeight;
      ctx.textAlign = "left";
      ctx.textBaseline = "middle";
      let row = -1;
      let top2 = -lineHeight;
      me2.legendItems.forEach((legendItem, i2) => {
        const itemWidth = boxWidth + fontSize / 2 + ctx.measureText(legendItem.text).width;
        if (i2 === 0 || lineWidths[lineWidths.length - 1] + itemWidth + 2 * padding > maxWidth) {
          totalHeight += lineHeight;
          lineWidths[lineWidths.length - (i2 > 0 ? 0 : 1)] = 0;
          top2 += lineHeight;
          row++;
        }
        hitboxes[i2] = { left: 0, top: top2, row, width: itemWidth, height: itemHeight };
        lineWidths[lineWidths.length - 1] += itemWidth + padding;
      });
      return totalHeight;
    }
    _fitCols(titleHeight, fontSize, boxWidth, itemHeight) {
      const me2 = this;
      const { ctx, maxHeight, options: { labels: { padding } } } = me2;
      const hitboxes = me2.legendHitBoxes = [];
      const columnSizes = me2.columnSizes = [];
      const heightLimit = maxHeight - titleHeight;
      let totalWidth = padding;
      let currentColWidth = 0;
      let currentColHeight = 0;
      let left2 = 0;
      let col = 0;
      me2.legendItems.forEach((legendItem, i2) => {
        const itemWidth = boxWidth + fontSize / 2 + ctx.measureText(legendItem.text).width;
        if (i2 > 0 && currentColHeight + itemHeight + 2 * padding > heightLimit) {
          totalWidth += currentColWidth + padding;
          columnSizes.push({ width: currentColWidth, height: currentColHeight });
          left2 += currentColWidth + padding;
          col++;
          currentColWidth = currentColHeight = 0;
        }
        hitboxes[i2] = { left: left2, top: currentColHeight, col, width: itemWidth, height: itemHeight };
        currentColWidth = Math.max(currentColWidth, itemWidth);
        currentColHeight += itemHeight + padding;
      });
      totalWidth += currentColWidth;
      columnSizes.push({ width: currentColWidth, height: currentColHeight });
      return totalWidth;
    }
    adjustHitBoxes() {
      const me2 = this;
      if (!me2.options.display) {
        return;
      }
      const titleHeight = me2._computeTitleHeight();
      const { legendHitBoxes: hitboxes, options: { align, labels: { padding }, rtl } } = me2;
      const rtlHelper = getRtlAdapter(rtl, me2.left, me2.width);
      if (this.isHorizontal()) {
        let row = 0;
        let left2 = _alignStartEnd(align, me2.left + padding, me2.right - me2.lineWidths[row]);
        for (const hitbox of hitboxes) {
          if (row !== hitbox.row) {
            row = hitbox.row;
            left2 = _alignStartEnd(align, me2.left + padding, me2.right - me2.lineWidths[row]);
          }
          hitbox.top += me2.top + titleHeight + padding;
          hitbox.left = rtlHelper.leftForLtr(rtlHelper.x(left2), hitbox.width);
          left2 += hitbox.width + padding;
        }
      } else {
        let col = 0;
        let top2 = _alignStartEnd(align, me2.top + titleHeight + padding, me2.bottom - me2.columnSizes[col].height);
        for (const hitbox of hitboxes) {
          if (hitbox.col !== col) {
            col = hitbox.col;
            top2 = _alignStartEnd(align, me2.top + titleHeight + padding, me2.bottom - me2.columnSizes[col].height);
          }
          hitbox.top = top2;
          hitbox.left += me2.left + padding;
          hitbox.left = rtlHelper.leftForLtr(rtlHelper.x(hitbox.left), hitbox.width);
          top2 += hitbox.height + padding;
        }
      }
    }
    isHorizontal() {
      return this.options.position === "top" || this.options.position === "bottom";
    }
    draw() {
      const me2 = this;
      if (me2.options.display) {
        const ctx = me2.ctx;
        clipArea(ctx, me2);
        me2._draw();
        unclipArea(ctx);
      }
    }
    _draw() {
      const me2 = this;
      const { options: opts, columnSizes, lineWidths, ctx } = me2;
      const { align, labels: labelOpts } = opts;
      const defaultColor = defaults.color;
      const rtlHelper = getRtlAdapter(opts.rtl, me2.left, me2.width);
      const labelFont = toFont(labelOpts.font);
      const { color: fontColor, padding } = labelOpts;
      const fontSize = labelFont.size;
      const halfFontSize = fontSize / 2;
      let cursor;
      me2.drawTitle();
      ctx.textAlign = rtlHelper.textAlign("left");
      ctx.textBaseline = "middle";
      ctx.lineWidth = 0.5;
      ctx.font = labelFont.string;
      const { boxWidth, boxHeight, itemHeight } = getBoxSize(labelOpts, fontSize);
      const drawLegendBox = function(x2, y2, legendItem) {
        if (isNaN(boxWidth) || boxWidth <= 0 || isNaN(boxHeight) || boxHeight < 0) {
          return;
        }
        ctx.save();
        const lineWidth = valueOrDefault(legendItem.lineWidth, 1);
        ctx.fillStyle = valueOrDefault(legendItem.fillStyle, defaultColor);
        ctx.lineCap = valueOrDefault(legendItem.lineCap, "butt");
        ctx.lineDashOffset = valueOrDefault(legendItem.lineDashOffset, 0);
        ctx.lineJoin = valueOrDefault(legendItem.lineJoin, "miter");
        ctx.lineWidth = lineWidth;
        ctx.strokeStyle = valueOrDefault(legendItem.strokeStyle, defaultColor);
        ctx.setLineDash(valueOrDefault(legendItem.lineDash, []));
        if (labelOpts.usePointStyle) {
          const drawOptions = {
            radius: boxWidth * Math.SQRT2 / 2,
            pointStyle: legendItem.pointStyle,
            rotation: legendItem.rotation,
            borderWidth: lineWidth
          };
          const centerX = rtlHelper.xPlus(x2, boxWidth / 2);
          const centerY = y2 + halfFontSize;
          drawPoint(ctx, drawOptions, centerX, centerY);
        } else {
          const yBoxTop = y2 + Math.max((fontSize - boxHeight) / 2, 0);
          const xBoxLeft = rtlHelper.leftForLtr(x2, boxWidth);
          const borderRadius = toTRBLCorners(legendItem.borderRadius);
          ctx.beginPath();
          if (Object.values(borderRadius).some((v2) => v2 !== 0)) {
            addRoundedRectPath(ctx, {
              x: xBoxLeft,
              y: yBoxTop,
              w: boxWidth,
              h: boxHeight,
              radius: borderRadius
            });
          } else {
            ctx.rect(xBoxLeft, yBoxTop, boxWidth, boxHeight);
          }
          ctx.fill();
          if (lineWidth !== 0) {
            ctx.stroke();
          }
        }
        ctx.restore();
      };
      const fillText = function(x2, y2, legendItem) {
        renderText(ctx, legendItem.text, x2, y2 + itemHeight / 2, labelFont, {
          strikethrough: legendItem.hidden,
          textAlign: rtlHelper.textAlign(legendItem.textAlign)
        });
      };
      const isHorizontal = me2.isHorizontal();
      const titleHeight = this._computeTitleHeight();
      if (isHorizontal) {
        cursor = {
          x: _alignStartEnd(align, me2.left + padding, me2.right - lineWidths[0]),
          y: me2.top + padding + titleHeight,
          line: 0
        };
      } else {
        cursor = {
          x: me2.left + padding,
          y: _alignStartEnd(align, me2.top + titleHeight + padding, me2.bottom - columnSizes[0].height),
          line: 0
        };
      }
      overrideTextDirection(me2.ctx, opts.textDirection);
      const lineHeight = itemHeight + padding;
      me2.legendItems.forEach((legendItem, i2) => {
        ctx.strokeStyle = legendItem.fontColor || fontColor;
        ctx.fillStyle = legendItem.fontColor || fontColor;
        const textWidth = ctx.measureText(legendItem.text).width;
        const textAlign = rtlHelper.textAlign(legendItem.textAlign || (legendItem.textAlign = labelOpts.textAlign));
        const width = boxWidth + halfFontSize + textWidth;
        let x2 = cursor.x;
        let y2 = cursor.y;
        rtlHelper.setWidth(me2.width);
        if (isHorizontal) {
          if (i2 > 0 && x2 + width + padding > me2.right) {
            y2 = cursor.y += lineHeight;
            cursor.line++;
            x2 = cursor.x = _alignStartEnd(align, me2.left + padding, me2.right - lineWidths[cursor.line]);
          }
        } else if (i2 > 0 && y2 + lineHeight > me2.bottom) {
          x2 = cursor.x = x2 + columnSizes[cursor.line].width + padding;
          cursor.line++;
          y2 = cursor.y = _alignStartEnd(align, me2.top + titleHeight + padding, me2.bottom - columnSizes[cursor.line].height);
        }
        const realX = rtlHelper.x(x2);
        drawLegendBox(realX, y2, legendItem);
        x2 = _textX(textAlign, x2 + boxWidth + halfFontSize, isHorizontal ? x2 + width : me2.right, opts.rtl);
        fillText(rtlHelper.x(x2), y2, legendItem);
        if (isHorizontal) {
          cursor.x += width + padding;
        } else {
          cursor.y += lineHeight;
        }
      });
      restoreTextDirection(me2.ctx, opts.textDirection);
    }
    drawTitle() {
      const me2 = this;
      const opts = me2.options;
      const titleOpts = opts.title;
      const titleFont = toFont(titleOpts.font);
      const titlePadding = toPadding(titleOpts.padding);
      if (!titleOpts.display) {
        return;
      }
      const rtlHelper = getRtlAdapter(opts.rtl, me2.left, me2.width);
      const ctx = me2.ctx;
      const position = titleOpts.position;
      const halfFontSize = titleFont.size / 2;
      const topPaddingPlusHalfFontSize = titlePadding.top + halfFontSize;
      let y2;
      let left2 = me2.left;
      let maxWidth = me2.width;
      if (this.isHorizontal()) {
        maxWidth = Math.max(...me2.lineWidths);
        y2 = me2.top + topPaddingPlusHalfFontSize;
        left2 = _alignStartEnd(opts.align, left2, me2.right - maxWidth);
      } else {
        const maxHeight = me2.columnSizes.reduce((acc, size) => Math.max(acc, size.height), 0);
        y2 = topPaddingPlusHalfFontSize + _alignStartEnd(opts.align, me2.top, me2.bottom - maxHeight - opts.labels.padding - me2._computeTitleHeight());
      }
      const x2 = _alignStartEnd(position, left2, left2 + maxWidth);
      ctx.textAlign = rtlHelper.textAlign(_toLeftRightCenter(position));
      ctx.textBaseline = "middle";
      ctx.strokeStyle = titleOpts.color;
      ctx.fillStyle = titleOpts.color;
      ctx.font = titleFont.string;
      renderText(ctx, titleOpts.text, x2, y2, titleFont);
    }
    _computeTitleHeight() {
      const titleOpts = this.options.title;
      const titleFont = toFont(titleOpts.font);
      const titlePadding = toPadding(titleOpts.padding);
      return titleOpts.display ? titleFont.lineHeight + titlePadding.height : 0;
    }
    _getLegendItemAt(x2, y2) {
      const me2 = this;
      let i2, hitBox, lh;
      if (x2 >= me2.left && x2 <= me2.right && y2 >= me2.top && y2 <= me2.bottom) {
        lh = me2.legendHitBoxes;
        for (i2 = 0; i2 < lh.length; ++i2) {
          hitBox = lh[i2];
          if (x2 >= hitBox.left && x2 <= hitBox.left + hitBox.width && y2 >= hitBox.top && y2 <= hitBox.top + hitBox.height) {
            return me2.legendItems[i2];
          }
        }
      }
      return null;
    }
    handleEvent(e2) {
      const me2 = this;
      const opts = me2.options;
      if (!isListened(e2.type, opts)) {
        return;
      }
      const hoveredItem = me2._getLegendItemAt(e2.x, e2.y);
      if (e2.type === "mousemove") {
        const previous = me2._hoveredItem;
        const sameItem = itemsEqual(previous, hoveredItem);
        if (previous && !sameItem) {
          callback(opts.onLeave, [e2, previous, me2], me2);
        }
        me2._hoveredItem = hoveredItem;
        if (hoveredItem && !sameItem) {
          callback(opts.onHover, [e2, hoveredItem, me2], me2);
        }
      } else if (hoveredItem) {
        callback(opts.onClick, [e2, hoveredItem, me2], me2);
      }
    }
  };
  function isListened(type, opts) {
    if (type === "mousemove" && (opts.onHover || opts.onLeave)) {
      return true;
    }
    if (opts.onClick && (type === "click" || type === "mouseup")) {
      return true;
    }
    return false;
  }
  var plugin_legend = {
    id: "legend",
    _element: Legend,
    start(chart, _args, options) {
      const legend = chart.legend = new Legend({ ctx: chart.ctx, options, chart });
      layouts.configure(chart, legend, options);
      layouts.addBox(chart, legend);
    },
    stop(chart) {
      layouts.removeBox(chart, chart.legend);
      delete chart.legend;
    },
    beforeUpdate(chart, _args, options) {
      const legend = chart.legend;
      layouts.configure(chart, legend, options);
      legend.options = options;
    },
    afterUpdate(chart) {
      const legend = chart.legend;
      legend.buildLabels();
      legend.adjustHitBoxes();
    },
    afterEvent(chart, args) {
      if (!args.replay) {
        chart.legend.handleEvent(args.event);
      }
    },
    defaults: {
      display: true,
      position: "top",
      align: "center",
      fullSize: true,
      reverse: false,
      weight: 1e3,
      onClick(e2, legendItem, legend) {
        const index = legendItem.datasetIndex;
        const ci2 = legend.chart;
        if (ci2.isDatasetVisible(index)) {
          ci2.hide(index);
          legendItem.hidden = true;
        } else {
          ci2.show(index);
          legendItem.hidden = false;
        }
      },
      onHover: null,
      onLeave: null,
      labels: {
        color: (ctx) => ctx.chart.options.color,
        boxWidth: 40,
        padding: 10,
        generateLabels(chart) {
          const datasets = chart.data.datasets;
          const { labels: { usePointStyle, pointStyle, textAlign, color: color2 } } = chart.legend.options;
          return chart._getSortedDatasetMetas().map((meta) => {
            const style = meta.controller.getStyle(usePointStyle ? 0 : void 0);
            const borderWidth = toPadding(style.borderWidth);
            return {
              text: datasets[meta.index].label,
              fillStyle: style.backgroundColor,
              fontColor: color2,
              hidden: !meta.visible,
              lineCap: style.borderCapStyle,
              lineDash: style.borderDash,
              lineDashOffset: style.borderDashOffset,
              lineJoin: style.borderJoinStyle,
              lineWidth: (borderWidth.width + borderWidth.height) / 4,
              strokeStyle: style.borderColor,
              pointStyle: pointStyle || style.pointStyle,
              rotation: style.rotation,
              textAlign: textAlign || style.textAlign,
              borderRadius: 0,
              datasetIndex: meta.index
            };
          }, this);
        }
      },
      title: {
        color: (ctx) => ctx.chart.options.color,
        display: false,
        position: "center",
        text: ""
      }
    },
    descriptors: {
      _scriptable: (name) => !name.startsWith("on"),
      labels: {
        _scriptable: (name) => !["generateLabels", "filter", "sort"].includes(name)
      }
    }
  };
  var Title = class extends Element2 {
    constructor(config) {
      super();
      this.chart = config.chart;
      this.options = config.options;
      this.ctx = config.ctx;
      this._padding = void 0;
      this.top = void 0;
      this.bottom = void 0;
      this.left = void 0;
      this.right = void 0;
      this.width = void 0;
      this.height = void 0;
      this.position = void 0;
      this.weight = void 0;
      this.fullSize = void 0;
    }
    update(maxWidth, maxHeight) {
      const me2 = this;
      const opts = me2.options;
      me2.left = 0;
      me2.top = 0;
      if (!opts.display) {
        me2.width = me2.height = me2.right = me2.bottom = 0;
        return;
      }
      me2.width = me2.right = maxWidth;
      me2.height = me2.bottom = maxHeight;
      const lineCount = isArray(opts.text) ? opts.text.length : 1;
      me2._padding = toPadding(opts.padding);
      const textSize = lineCount * toFont(opts.font).lineHeight + me2._padding.height;
      if (me2.isHorizontal()) {
        me2.height = textSize;
      } else {
        me2.width = textSize;
      }
    }
    isHorizontal() {
      const pos = this.options.position;
      return pos === "top" || pos === "bottom";
    }
    _drawArgs(offset2) {
      const { top: top2, left: left2, bottom: bottom2, right: right2, options } = this;
      const align = options.align;
      let rotation = 0;
      let maxWidth, titleX, titleY;
      if (this.isHorizontal()) {
        titleX = _alignStartEnd(align, left2, right2);
        titleY = top2 + offset2;
        maxWidth = right2 - left2;
      } else {
        if (options.position === "left") {
          titleX = left2 + offset2;
          titleY = _alignStartEnd(align, bottom2, top2);
          rotation = PI * -0.5;
        } else {
          titleX = right2 - offset2;
          titleY = _alignStartEnd(align, top2, bottom2);
          rotation = PI * 0.5;
        }
        maxWidth = bottom2 - top2;
      }
      return { titleX, titleY, maxWidth, rotation };
    }
    draw() {
      const me2 = this;
      const ctx = me2.ctx;
      const opts = me2.options;
      if (!opts.display) {
        return;
      }
      const fontOpts = toFont(opts.font);
      const lineHeight = fontOpts.lineHeight;
      const offset2 = lineHeight / 2 + me2._padding.top;
      const { titleX, titleY, maxWidth, rotation } = me2._drawArgs(offset2);
      renderText(ctx, opts.text, 0, 0, fontOpts, {
        color: opts.color,
        maxWidth,
        rotation,
        textAlign: _toLeftRightCenter(opts.align),
        textBaseline: "middle",
        translation: [titleX, titleY]
      });
    }
  };
  function createTitle(chart, titleOpts) {
    const title = new Title({
      ctx: chart.ctx,
      options: titleOpts,
      chart
    });
    layouts.configure(chart, title, titleOpts);
    layouts.addBox(chart, title);
    chart.titleBlock = title;
  }
  var plugin_title = {
    id: "title",
    _element: Title,
    start(chart, _args, options) {
      createTitle(chart, options);
    },
    stop(chart) {
      const titleBlock = chart.titleBlock;
      layouts.removeBox(chart, titleBlock);
      delete chart.titleBlock;
    },
    beforeUpdate(chart, _args, options) {
      const title = chart.titleBlock;
      layouts.configure(chart, title, options);
      title.options = options;
    },
    defaults: {
      align: "center",
      display: false,
      font: {
        weight: "bold"
      },
      fullSize: true,
      padding: 10,
      position: "top",
      text: "",
      weight: 2e3
    },
    defaultRoutes: {
      color: "color"
    },
    descriptors: {
      _scriptable: true,
      _indexable: false
    }
  };
  var map2 = /* @__PURE__ */ new WeakMap();
  var plugin_subtitle = {
    id: "subtitle",
    start(chart, _args, options) {
      const title = new Title({
        ctx: chart.ctx,
        options,
        chart
      });
      layouts.configure(chart, title, options);
      layouts.addBox(chart, title);
      map2.set(chart, title);
    },
    stop(chart) {
      layouts.removeBox(chart, map2.get(chart));
      map2.delete(chart);
    },
    beforeUpdate(chart, _args, options) {
      const title = map2.get(chart);
      layouts.configure(chart, title, options);
      title.options = options;
    },
    defaults: {
      align: "center",
      display: false,
      font: {
        weight: "normal"
      },
      fullSize: true,
      padding: 0,
      position: "top",
      text: "",
      weight: 1500
    },
    defaultRoutes: {
      color: "color"
    },
    descriptors: {
      _scriptable: true,
      _indexable: false
    }
  };
  var positioners = {
    average(items) {
      if (!items.length) {
        return false;
      }
      let i2, len;
      let x2 = 0;
      let y2 = 0;
      let count = 0;
      for (i2 = 0, len = items.length; i2 < len; ++i2) {
        const el = items[i2].element;
        if (el && el.hasValue()) {
          const pos = el.tooltipPosition();
          x2 += pos.x;
          y2 += pos.y;
          ++count;
        }
      }
      return {
        x: x2 / count,
        y: y2 / count
      };
    },
    nearest(items, eventPosition) {
      if (!items.length) {
        return false;
      }
      let x2 = eventPosition.x;
      let y2 = eventPosition.y;
      let minDistance = Number.POSITIVE_INFINITY;
      let i2, len, nearestElement;
      for (i2 = 0, len = items.length; i2 < len; ++i2) {
        const el = items[i2].element;
        if (el && el.hasValue()) {
          const center = el.getCenterPoint();
          const d2 = distanceBetweenPoints(eventPosition, center);
          if (d2 < minDistance) {
            minDistance = d2;
            nearestElement = el;
          }
        }
      }
      if (nearestElement) {
        const tp = nearestElement.tooltipPosition();
        x2 = tp.x;
        y2 = tp.y;
      }
      return {
        x: x2,
        y: y2
      };
    }
  };
  function pushOrConcat(base, toPush) {
    if (toPush) {
      if (isArray(toPush)) {
        Array.prototype.push.apply(base, toPush);
      } else {
        base.push(toPush);
      }
    }
    return base;
  }
  function splitNewlines(str) {
    if ((typeof str === "string" || str instanceof String) && str.indexOf("\n") > -1) {
      return str.split("\n");
    }
    return str;
  }
  function createTooltipItem(chart, item) {
    const { element, datasetIndex, index } = item;
    const controller = chart.getDatasetMeta(datasetIndex).controller;
    const { label, value } = controller.getLabelAndValue(index);
    return {
      chart,
      label,
      parsed: controller.getParsed(index),
      raw: chart.data.datasets[datasetIndex].data[index],
      formattedValue: value,
      dataset: controller.getDataset(),
      dataIndex: index,
      datasetIndex,
      element
    };
  }
  function getTooltipSize(tooltip, options) {
    const ctx = tooltip._chart.ctx;
    const { body, footer, title } = tooltip;
    const { boxWidth, boxHeight } = options;
    const bodyFont = toFont(options.bodyFont);
    const titleFont = toFont(options.titleFont);
    const footerFont = toFont(options.footerFont);
    const titleLineCount = title.length;
    const footerLineCount = footer.length;
    const bodyLineItemCount = body.length;
    const padding = toPadding(options.padding);
    let height = padding.height;
    let width = 0;
    let combinedBodyLength = body.reduce((count, bodyItem) => count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length, 0);
    combinedBodyLength += tooltip.beforeBody.length + tooltip.afterBody.length;
    if (titleLineCount) {
      height += titleLineCount * titleFont.lineHeight + (titleLineCount - 1) * options.titleSpacing + options.titleMarginBottom;
    }
    if (combinedBodyLength) {
      const bodyLineHeight = options.displayColors ? Math.max(boxHeight, bodyFont.lineHeight) : bodyFont.lineHeight;
      height += bodyLineItemCount * bodyLineHeight + (combinedBodyLength - bodyLineItemCount) * bodyFont.lineHeight + (combinedBodyLength - 1) * options.bodySpacing;
    }
    if (footerLineCount) {
      height += options.footerMarginTop + footerLineCount * footerFont.lineHeight + (footerLineCount - 1) * options.footerSpacing;
    }
    let widthPadding = 0;
    const maxLineWidth = function(line) {
      width = Math.max(width, ctx.measureText(line).width + widthPadding);
    };
    ctx.save();
    ctx.font = titleFont.string;
    each(tooltip.title, maxLineWidth);
    ctx.font = bodyFont.string;
    each(tooltip.beforeBody.concat(tooltip.afterBody), maxLineWidth);
    widthPadding = options.displayColors ? boxWidth + 2 : 0;
    each(body, (bodyItem) => {
      each(bodyItem.before, maxLineWidth);
      each(bodyItem.lines, maxLineWidth);
      each(bodyItem.after, maxLineWidth);
    });
    widthPadding = 0;
    ctx.font = footerFont.string;
    each(tooltip.footer, maxLineWidth);
    ctx.restore();
    width += padding.width;
    return { width, height };
  }
  function determineYAlign(chart, size) {
    const { y: y2, height } = size;
    if (y2 < height / 2) {
      return "top";
    } else if (y2 > chart.height - height / 2) {
      return "bottom";
    }
    return "center";
  }
  function doesNotFitWithAlign(xAlign, chart, options, size) {
    const { x: x2, width } = size;
    const caret = options.caretSize + options.caretPadding;
    if (xAlign === "left" && x2 + width + caret > chart.width) {
      return true;
    }
    if (xAlign === "right" && x2 - width - caret < 0) {
      return true;
    }
  }
  function determineXAlign(chart, options, size, yAlign) {
    const { x: x2, width } = size;
    const { width: chartWidth, chartArea: { left: left2, right: right2 } } = chart;
    let xAlign = "center";
    if (yAlign === "center") {
      xAlign = x2 <= (left2 + right2) / 2 ? "left" : "right";
    } else if (x2 <= width / 2) {
      xAlign = "left";
    } else if (x2 >= chartWidth - width / 2) {
      xAlign = "right";
    }
    if (doesNotFitWithAlign(xAlign, chart, options, size)) {
      xAlign = "center";
    }
    return xAlign;
  }
  function determineAlignment(chart, options, size) {
    const yAlign = options.yAlign || determineYAlign(chart, size);
    return {
      xAlign: options.xAlign || determineXAlign(chart, options, size, yAlign),
      yAlign
    };
  }
  function alignX(size, xAlign) {
    let { x: x2, width } = size;
    if (xAlign === "right") {
      x2 -= width;
    } else if (xAlign === "center") {
      x2 -= width / 2;
    }
    return x2;
  }
  function alignY(size, yAlign, paddingAndSize) {
    let { y: y2, height } = size;
    if (yAlign === "top") {
      y2 += paddingAndSize;
    } else if (yAlign === "bottom") {
      y2 -= height + paddingAndSize;
    } else {
      y2 -= height / 2;
    }
    return y2;
  }
  function getBackgroundPoint(options, size, alignment, chart) {
    const { caretSize, caretPadding, cornerRadius } = options;
    const { xAlign, yAlign } = alignment;
    const paddingAndSize = caretSize + caretPadding;
    const radiusAndPadding = cornerRadius + caretPadding;
    let x2 = alignX(size, xAlign);
    const y2 = alignY(size, yAlign, paddingAndSize);
    if (yAlign === "center") {
      if (xAlign === "left") {
        x2 += paddingAndSize;
      } else if (xAlign === "right") {
        x2 -= paddingAndSize;
      }
    } else if (xAlign === "left") {
      x2 -= radiusAndPadding;
    } else if (xAlign === "right") {
      x2 += radiusAndPadding;
    }
    return {
      x: _limitValue(x2, 0, chart.width - size.width),
      y: _limitValue(y2, 0, chart.height - size.height)
    };
  }
  function getAlignedX(tooltip, align, options) {
    const padding = toPadding(options.padding);
    return align === "center" ? tooltip.x + tooltip.width / 2 : align === "right" ? tooltip.x + tooltip.width - padding.right : tooltip.x + padding.left;
  }
  function getBeforeAfterBodyLines(callback2) {
    return pushOrConcat([], splitNewlines(callback2));
  }
  function createTooltipContext(parent, tooltip, tooltipItems) {
    return Object.assign(Object.create(parent), {
      tooltip,
      tooltipItems,
      type: "tooltip"
    });
  }
  function overrideCallbacks(callbacks, context) {
    const override = context && context.dataset && context.dataset.tooltip && context.dataset.tooltip.callbacks;
    return override ? callbacks.override(override) : callbacks;
  }
  var Tooltip2 = class extends Element2 {
    constructor(config) {
      super();
      this.opacity = 0;
      this._active = [];
      this._chart = config._chart;
      this._eventPosition = void 0;
      this._size = void 0;
      this._cachedAnimations = void 0;
      this._tooltipItems = [];
      this.$animations = void 0;
      this.$context = void 0;
      this.options = config.options;
      this.dataPoints = void 0;
      this.title = void 0;
      this.beforeBody = void 0;
      this.body = void 0;
      this.afterBody = void 0;
      this.footer = void 0;
      this.xAlign = void 0;
      this.yAlign = void 0;
      this.x = void 0;
      this.y = void 0;
      this.height = void 0;
      this.width = void 0;
      this.caretX = void 0;
      this.caretY = void 0;
      this.labelColors = void 0;
      this.labelPointStyles = void 0;
      this.labelTextColors = void 0;
    }
    initialize(options) {
      this.options = options;
      this._cachedAnimations = void 0;
      this.$context = void 0;
    }
    _resolveAnimations() {
      const me2 = this;
      const cached = me2._cachedAnimations;
      if (cached) {
        return cached;
      }
      const chart = me2._chart;
      const options = me2.options.setContext(me2.getContext());
      const opts = options.enabled && chart.options.animation && options.animations;
      const animations = new Animations(me2._chart, opts);
      if (opts._cacheable) {
        me2._cachedAnimations = Object.freeze(animations);
      }
      return animations;
    }
    getContext() {
      const me2 = this;
      return me2.$context || (me2.$context = createTooltipContext(me2._chart.getContext(), me2, me2._tooltipItems));
    }
    getTitle(context, options) {
      const me2 = this;
      const { callbacks } = options;
      const beforeTitle = callbacks.beforeTitle.apply(me2, [context]);
      const title = callbacks.title.apply(me2, [context]);
      const afterTitle = callbacks.afterTitle.apply(me2, [context]);
      let lines = [];
      lines = pushOrConcat(lines, splitNewlines(beforeTitle));
      lines = pushOrConcat(lines, splitNewlines(title));
      lines = pushOrConcat(lines, splitNewlines(afterTitle));
      return lines;
    }
    getBeforeBody(tooltipItems, options) {
      return getBeforeAfterBodyLines(options.callbacks.beforeBody.apply(this, [tooltipItems]));
    }
    getBody(tooltipItems, options) {
      const me2 = this;
      const { callbacks } = options;
      const bodyItems = [];
      each(tooltipItems, (context) => {
        const bodyItem = {
          before: [],
          lines: [],
          after: []
        };
        const scoped = overrideCallbacks(callbacks, context);
        pushOrConcat(bodyItem.before, splitNewlines(scoped.beforeLabel.call(me2, context)));
        pushOrConcat(bodyItem.lines, scoped.label.call(me2, context));
        pushOrConcat(bodyItem.after, splitNewlines(scoped.afterLabel.call(me2, context)));
        bodyItems.push(bodyItem);
      });
      return bodyItems;
    }
    getAfterBody(tooltipItems, options) {
      return getBeforeAfterBodyLines(options.callbacks.afterBody.apply(this, [tooltipItems]));
    }
    getFooter(tooltipItems, options) {
      const me2 = this;
      const { callbacks } = options;
      const beforeFooter = callbacks.beforeFooter.apply(me2, [tooltipItems]);
      const footer = callbacks.footer.apply(me2, [tooltipItems]);
      const afterFooter = callbacks.afterFooter.apply(me2, [tooltipItems]);
      let lines = [];
      lines = pushOrConcat(lines, splitNewlines(beforeFooter));
      lines = pushOrConcat(lines, splitNewlines(footer));
      lines = pushOrConcat(lines, splitNewlines(afterFooter));
      return lines;
    }
    _createItems(options) {
      const me2 = this;
      const active = me2._active;
      const data = me2._chart.data;
      const labelColors = [];
      const labelPointStyles = [];
      const labelTextColors = [];
      let tooltipItems = [];
      let i2, len;
      for (i2 = 0, len = active.length; i2 < len; ++i2) {
        tooltipItems.push(createTooltipItem(me2._chart, active[i2]));
      }
      if (options.filter) {
        tooltipItems = tooltipItems.filter((element, index, array) => options.filter(element, index, array, data));
      }
      if (options.itemSort) {
        tooltipItems = tooltipItems.sort((a2, b2) => options.itemSort(a2, b2, data));
      }
      each(tooltipItems, (context) => {
        const scoped = overrideCallbacks(options.callbacks, context);
        labelColors.push(scoped.labelColor.call(me2, context));
        labelPointStyles.push(scoped.labelPointStyle.call(me2, context));
        labelTextColors.push(scoped.labelTextColor.call(me2, context));
      });
      me2.labelColors = labelColors;
      me2.labelPointStyles = labelPointStyles;
      me2.labelTextColors = labelTextColors;
      me2.dataPoints = tooltipItems;
      return tooltipItems;
    }
    update(changed, replay) {
      const me2 = this;
      const options = me2.options.setContext(me2.getContext());
      const active = me2._active;
      let properties;
      let tooltipItems = [];
      if (!active.length) {
        if (me2.opacity !== 0) {
          properties = {
            opacity: 0
          };
        }
      } else {
        const position = positioners[options.position].call(me2, active, me2._eventPosition);
        tooltipItems = me2._createItems(options);
        me2.title = me2.getTitle(tooltipItems, options);
        me2.beforeBody = me2.getBeforeBody(tooltipItems, options);
        me2.body = me2.getBody(tooltipItems, options);
        me2.afterBody = me2.getAfterBody(tooltipItems, options);
        me2.footer = me2.getFooter(tooltipItems, options);
        const size = me2._size = getTooltipSize(me2, options);
        const positionAndSize = Object.assign({}, position, size);
        const alignment = determineAlignment(me2._chart, options, positionAndSize);
        const backgroundPoint = getBackgroundPoint(options, positionAndSize, alignment, me2._chart);
        me2.xAlign = alignment.xAlign;
        me2.yAlign = alignment.yAlign;
        properties = {
          opacity: 1,
          x: backgroundPoint.x,
          y: backgroundPoint.y,
          width: size.width,
          height: size.height,
          caretX: position.x,
          caretY: position.y
        };
      }
      me2._tooltipItems = tooltipItems;
      me2.$context = void 0;
      if (properties) {
        me2._resolveAnimations().update(me2, properties);
      }
      if (changed && options.external) {
        options.external.call(me2, { chart: me2._chart, tooltip: me2, replay });
      }
    }
    drawCaret(tooltipPoint, ctx, size, options) {
      const caretPosition = this.getCaretPosition(tooltipPoint, size, options);
      ctx.lineTo(caretPosition.x1, caretPosition.y1);
      ctx.lineTo(caretPosition.x2, caretPosition.y2);
      ctx.lineTo(caretPosition.x3, caretPosition.y3);
    }
    getCaretPosition(tooltipPoint, size, options) {
      const { xAlign, yAlign } = this;
      const { cornerRadius, caretSize } = options;
      const { x: ptX, y: ptY } = tooltipPoint;
      const { width, height } = size;
      let x1, x2, x3, y1, y2, y3;
      if (yAlign === "center") {
        y2 = ptY + height / 2;
        if (xAlign === "left") {
          x1 = ptX;
          x2 = x1 - caretSize;
          y1 = y2 + caretSize;
          y3 = y2 - caretSize;
        } else {
          x1 = ptX + width;
          x2 = x1 + caretSize;
          y1 = y2 - caretSize;
          y3 = y2 + caretSize;
        }
        x3 = x1;
      } else {
        if (xAlign === "left") {
          x2 = ptX + cornerRadius + caretSize;
        } else if (xAlign === "right") {
          x2 = ptX + width - cornerRadius - caretSize;
        } else {
          x2 = this.caretX;
        }
        if (yAlign === "top") {
          y1 = ptY;
          y2 = y1 - caretSize;
          x1 = x2 - caretSize;
          x3 = x2 + caretSize;
        } else {
          y1 = ptY + height;
          y2 = y1 + caretSize;
          x1 = x2 + caretSize;
          x3 = x2 - caretSize;
        }
        y3 = y1;
      }
      return { x1, x2, x3, y1, y2, y3 };
    }
    drawTitle(pt2, ctx, options) {
      const me2 = this;
      const title = me2.title;
      const length = title.length;
      let titleFont, titleSpacing, i2;
      if (length) {
        const rtlHelper = getRtlAdapter(options.rtl, me2.x, me2.width);
        pt2.x = getAlignedX(me2, options.titleAlign, options);
        ctx.textAlign = rtlHelper.textAlign(options.titleAlign);
        ctx.textBaseline = "middle";
        titleFont = toFont(options.titleFont);
        titleSpacing = options.titleSpacing;
        ctx.fillStyle = options.titleColor;
        ctx.font = titleFont.string;
        for (i2 = 0; i2 < length; ++i2) {
          ctx.fillText(title[i2], rtlHelper.x(pt2.x), pt2.y + titleFont.lineHeight / 2);
          pt2.y += titleFont.lineHeight + titleSpacing;
          if (i2 + 1 === length) {
            pt2.y += options.titleMarginBottom - titleSpacing;
          }
        }
      }
    }
    _drawColorBox(ctx, pt2, i2, rtlHelper, options) {
      const me2 = this;
      const labelColors = me2.labelColors[i2];
      const labelPointStyle = me2.labelPointStyles[i2];
      const { boxHeight, boxWidth } = options;
      const bodyFont = toFont(options.bodyFont);
      const colorX = getAlignedX(me2, "left", options);
      const rtlColorX = rtlHelper.x(colorX);
      const yOffSet = boxHeight < bodyFont.lineHeight ? (bodyFont.lineHeight - boxHeight) / 2 : 0;
      const colorY = pt2.y + yOffSet;
      if (options.usePointStyle) {
        const drawOptions = {
          radius: Math.min(boxWidth, boxHeight) / 2,
          pointStyle: labelPointStyle.pointStyle,
          rotation: labelPointStyle.rotation,
          borderWidth: 1
        };
        const centerX = rtlHelper.leftForLtr(rtlColorX, boxWidth) + boxWidth / 2;
        const centerY = colorY + boxHeight / 2;
        ctx.strokeStyle = options.multiKeyBackground;
        ctx.fillStyle = options.multiKeyBackground;
        drawPoint(ctx, drawOptions, centerX, centerY);
        ctx.strokeStyle = labelColors.borderColor;
        ctx.fillStyle = labelColors.backgroundColor;
        drawPoint(ctx, drawOptions, centerX, centerY);
      } else {
        ctx.lineWidth = labelColors.borderWidth || 1;
        ctx.strokeStyle = labelColors.borderColor;
        ctx.setLineDash(labelColors.borderDash || []);
        ctx.lineDashOffset = labelColors.borderDashOffset || 0;
        const outerX = rtlHelper.leftForLtr(rtlColorX, boxWidth);
        const innerX = rtlHelper.leftForLtr(rtlHelper.xPlus(rtlColorX, 1), boxWidth - 2);
        const borderRadius = toTRBLCorners(labelColors.borderRadius);
        if (Object.values(borderRadius).some((v2) => v2 !== 0)) {
          ctx.beginPath();
          ctx.fillStyle = options.multiKeyBackground;
          addRoundedRectPath(ctx, {
            x: outerX,
            y: colorY,
            w: boxWidth,
            h: boxHeight,
            radius: borderRadius
          });
          ctx.fill();
          ctx.stroke();
          ctx.fillStyle = labelColors.backgroundColor;
          ctx.beginPath();
          addRoundedRectPath(ctx, {
            x: innerX,
            y: colorY + 1,
            w: boxWidth - 2,
            h: boxHeight - 2,
            radius: borderRadius
          });
          ctx.fill();
        } else {
          ctx.fillStyle = options.multiKeyBackground;
          ctx.fillRect(outerX, colorY, boxWidth, boxHeight);
          ctx.strokeRect(outerX, colorY, boxWidth, boxHeight);
          ctx.fillStyle = labelColors.backgroundColor;
          ctx.fillRect(innerX, colorY + 1, boxWidth - 2, boxHeight - 2);
        }
      }
      ctx.fillStyle = me2.labelTextColors[i2];
    }
    drawBody(pt2, ctx, options) {
      const me2 = this;
      const { body } = me2;
      const { bodySpacing, bodyAlign, displayColors, boxHeight, boxWidth } = options;
      const bodyFont = toFont(options.bodyFont);
      let bodyLineHeight = bodyFont.lineHeight;
      let xLinePadding = 0;
      const rtlHelper = getRtlAdapter(options.rtl, me2.x, me2.width);
      const fillLineOfText = function(line) {
        ctx.fillText(line, rtlHelper.x(pt2.x + xLinePadding), pt2.y + bodyLineHeight / 2);
        pt2.y += bodyLineHeight + bodySpacing;
      };
      const bodyAlignForCalculation = rtlHelper.textAlign(bodyAlign);
      let bodyItem, textColor, lines, i2, j2, ilen, jlen;
      ctx.textAlign = bodyAlign;
      ctx.textBaseline = "middle";
      ctx.font = bodyFont.string;
      pt2.x = getAlignedX(me2, bodyAlignForCalculation, options);
      ctx.fillStyle = options.bodyColor;
      each(me2.beforeBody, fillLineOfText);
      xLinePadding = displayColors && bodyAlignForCalculation !== "right" ? bodyAlign === "center" ? boxWidth / 2 + 1 : boxWidth + 2 : 0;
      for (i2 = 0, ilen = body.length; i2 < ilen; ++i2) {
        bodyItem = body[i2];
        textColor = me2.labelTextColors[i2];
        ctx.fillStyle = textColor;
        each(bodyItem.before, fillLineOfText);
        lines = bodyItem.lines;
        if (displayColors && lines.length) {
          me2._drawColorBox(ctx, pt2, i2, rtlHelper, options);
          bodyLineHeight = Math.max(bodyFont.lineHeight, boxHeight);
        }
        for (j2 = 0, jlen = lines.length; j2 < jlen; ++j2) {
          fillLineOfText(lines[j2]);
          bodyLineHeight = bodyFont.lineHeight;
        }
        each(bodyItem.after, fillLineOfText);
      }
      xLinePadding = 0;
      bodyLineHeight = bodyFont.lineHeight;
      each(me2.afterBody, fillLineOfText);
      pt2.y -= bodySpacing;
    }
    drawFooter(pt2, ctx, options) {
      const me2 = this;
      const footer = me2.footer;
      const length = footer.length;
      let footerFont, i2;
      if (length) {
        const rtlHelper = getRtlAdapter(options.rtl, me2.x, me2.width);
        pt2.x = getAlignedX(me2, options.footerAlign, options);
        pt2.y += options.footerMarginTop;
        ctx.textAlign = rtlHelper.textAlign(options.footerAlign);
        ctx.textBaseline = "middle";
        footerFont = toFont(options.footerFont);
        ctx.fillStyle = options.footerColor;
        ctx.font = footerFont.string;
        for (i2 = 0; i2 < length; ++i2) {
          ctx.fillText(footer[i2], rtlHelper.x(pt2.x), pt2.y + footerFont.lineHeight / 2);
          pt2.y += footerFont.lineHeight + options.footerSpacing;
        }
      }
    }
    drawBackground(pt2, ctx, tooltipSize, options) {
      const { xAlign, yAlign } = this;
      const { x: x2, y: y2 } = pt2;
      const { width, height } = tooltipSize;
      const radius = options.cornerRadius;
      ctx.fillStyle = options.backgroundColor;
      ctx.strokeStyle = options.borderColor;
      ctx.lineWidth = options.borderWidth;
      ctx.beginPath();
      ctx.moveTo(x2 + radius, y2);
      if (yAlign === "top") {
        this.drawCaret(pt2, ctx, tooltipSize, options);
      }
      ctx.lineTo(x2 + width - radius, y2);
      ctx.quadraticCurveTo(x2 + width, y2, x2 + width, y2 + radius);
      if (yAlign === "center" && xAlign === "right") {
        this.drawCaret(pt2, ctx, tooltipSize, options);
      }
      ctx.lineTo(x2 + width, y2 + height - radius);
      ctx.quadraticCurveTo(x2 + width, y2 + height, x2 + width - radius, y2 + height);
      if (yAlign === "bottom") {
        this.drawCaret(pt2, ctx, tooltipSize, options);
      }
      ctx.lineTo(x2 + radius, y2 + height);
      ctx.quadraticCurveTo(x2, y2 + height, x2, y2 + height - radius);
      if (yAlign === "center" && xAlign === "left") {
        this.drawCaret(pt2, ctx, tooltipSize, options);
      }
      ctx.lineTo(x2, y2 + radius);
      ctx.quadraticCurveTo(x2, y2, x2 + radius, y2);
      ctx.closePath();
      ctx.fill();
      if (options.borderWidth > 0) {
        ctx.stroke();
      }
    }
    _updateAnimationTarget(options) {
      const me2 = this;
      const chart = me2._chart;
      const anims = me2.$animations;
      const animX = anims && anims.x;
      const animY = anims && anims.y;
      if (animX || animY) {
        const position = positioners[options.position].call(me2, me2._active, me2._eventPosition);
        if (!position) {
          return;
        }
        const size = me2._size = getTooltipSize(me2, options);
        const positionAndSize = Object.assign({}, position, me2._size);
        const alignment = determineAlignment(chart, options, positionAndSize);
        const point = getBackgroundPoint(options, positionAndSize, alignment, chart);
        if (animX._to !== point.x || animY._to !== point.y) {
          me2.xAlign = alignment.xAlign;
          me2.yAlign = alignment.yAlign;
          me2.width = size.width;
          me2.height = size.height;
          me2.caretX = position.x;
          me2.caretY = position.y;
          me2._resolveAnimations().update(me2, point);
        }
      }
    }
    draw(ctx) {
      const me2 = this;
      const options = me2.options.setContext(me2.getContext());
      let opacity = me2.opacity;
      if (!opacity) {
        return;
      }
      me2._updateAnimationTarget(options);
      const tooltipSize = {
        width: me2.width,
        height: me2.height
      };
      const pt2 = {
        x: me2.x,
        y: me2.y
      };
      opacity = Math.abs(opacity) < 1e-3 ? 0 : opacity;
      const padding = toPadding(options.padding);
      const hasTooltipContent = me2.title.length || me2.beforeBody.length || me2.body.length || me2.afterBody.length || me2.footer.length;
      if (options.enabled && hasTooltipContent) {
        ctx.save();
        ctx.globalAlpha = opacity;
        me2.drawBackground(pt2, ctx, tooltipSize, options);
        overrideTextDirection(ctx, options.textDirection);
        pt2.y += padding.top;
        me2.drawTitle(pt2, ctx, options);
        me2.drawBody(pt2, ctx, options);
        me2.drawFooter(pt2, ctx, options);
        restoreTextDirection(ctx, options.textDirection);
        ctx.restore();
      }
    }
    getActiveElements() {
      return this._active || [];
    }
    setActiveElements(activeElements, eventPosition) {
      const me2 = this;
      const lastActive = me2._active;
      const active = activeElements.map(({ datasetIndex, index }) => {
        const meta = me2._chart.getDatasetMeta(datasetIndex);
        if (!meta) {
          throw new Error("Cannot find a dataset at index " + datasetIndex);
        }
        return {
          datasetIndex,
          element: meta.data[index],
          index
        };
      });
      const changed = !_elementsEqual(lastActive, active);
      const positionChanged = me2._positionChanged(active, eventPosition);
      if (changed || positionChanged) {
        me2._active = active;
        me2._eventPosition = eventPosition;
        me2.update(true);
      }
    }
    handleEvent(e2, replay) {
      const me2 = this;
      const options = me2.options;
      const lastActive = me2._active || [];
      let changed = false;
      let active = [];
      if (e2.type !== "mouseout") {
        active = me2._chart.getElementsAtEventForMode(e2, options.mode, options, replay);
        if (options.reverse) {
          active.reverse();
        }
      }
      const positionChanged = me2._positionChanged(active, e2);
      changed = replay || !_elementsEqual(active, lastActive) || positionChanged;
      if (changed) {
        me2._active = active;
        if (options.enabled || options.external) {
          me2._eventPosition = {
            x: e2.x,
            y: e2.y
          };
          me2.update(true, replay);
        }
      }
      return changed;
    }
    _positionChanged(active, e2) {
      const { caretX, caretY, options } = this;
      const position = positioners[options.position].call(this, active, e2);
      return position !== false && (caretX !== position.x || caretY !== position.y);
    }
  };
  Tooltip2.positioners = positioners;
  var plugin_tooltip = {
    id: "tooltip",
    _element: Tooltip2,
    positioners,
    afterInit(chart, _args, options) {
      if (options) {
        chart.tooltip = new Tooltip2({ _chart: chart, options });
      }
    },
    beforeUpdate(chart, _args, options) {
      if (chart.tooltip) {
        chart.tooltip.initialize(options);
      }
    },
    reset(chart, _args, options) {
      if (chart.tooltip) {
        chart.tooltip.initialize(options);
      }
    },
    afterDraw(chart) {
      const tooltip = chart.tooltip;
      const args = {
        tooltip
      };
      if (chart.notifyPlugins("beforeTooltipDraw", args) === false) {
        return;
      }
      if (tooltip) {
        tooltip.draw(chart.ctx);
      }
      chart.notifyPlugins("afterTooltipDraw", args);
    },
    afterEvent(chart, args) {
      if (chart.tooltip) {
        const useFinalPosition = args.replay;
        if (chart.tooltip.handleEvent(args.event, useFinalPosition)) {
          args.changed = true;
        }
      }
    },
    defaults: {
      enabled: true,
      external: null,
      position: "average",
      backgroundColor: "rgba(0,0,0,0.8)",
      titleColor: "#fff",
      titleFont: {
        weight: "bold"
      },
      titleSpacing: 2,
      titleMarginBottom: 6,
      titleAlign: "left",
      bodyColor: "#fff",
      bodySpacing: 2,
      bodyFont: {},
      bodyAlign: "left",
      footerColor: "#fff",
      footerSpacing: 2,
      footerMarginTop: 6,
      footerFont: {
        weight: "bold"
      },
      footerAlign: "left",
      padding: 6,
      caretPadding: 2,
      caretSize: 5,
      cornerRadius: 6,
      boxHeight: (ctx, opts) => opts.bodyFont.size,
      boxWidth: (ctx, opts) => opts.bodyFont.size,
      multiKeyBackground: "#fff",
      displayColors: true,
      borderColor: "rgba(0,0,0,0)",
      borderWidth: 0,
      animation: {
        duration: 400,
        easing: "easeOutQuart"
      },
      animations: {
        numbers: {
          type: "number",
          properties: ["x", "y", "width", "height", "caretX", "caretY"]
        },
        opacity: {
          easing: "linear",
          duration: 200
        }
      },
      callbacks: {
        beforeTitle: noop2,
        title(tooltipItems) {
          if (tooltipItems.length > 0) {
            const item = tooltipItems[0];
            const labels = item.chart.data.labels;
            const labelCount = labels ? labels.length : 0;
            if (this && this.options && this.options.mode === "dataset") {
              return item.dataset.label || "";
            } else if (item.label) {
              return item.label;
            } else if (labelCount > 0 && item.dataIndex < labelCount) {
              return labels[item.dataIndex];
            }
          }
          return "";
        },
        afterTitle: noop2,
        beforeBody: noop2,
        beforeLabel: noop2,
        label(tooltipItem) {
          if (this && this.options && this.options.mode === "dataset") {
            return tooltipItem.label + ": " + tooltipItem.formattedValue || tooltipItem.formattedValue;
          }
          let label = tooltipItem.dataset.label || "";
          if (label) {
            label += ": ";
          }
          const value = tooltipItem.formattedValue;
          if (!isNullOrUndef(value)) {
            label += value;
          }
          return label;
        },
        labelColor(tooltipItem) {
          const meta = tooltipItem.chart.getDatasetMeta(tooltipItem.datasetIndex);
          const options = meta.controller.getStyle(tooltipItem.dataIndex);
          return {
            borderColor: options.borderColor,
            backgroundColor: options.backgroundColor,
            borderWidth: options.borderWidth,
            borderDash: options.borderDash,
            borderDashOffset: options.borderDashOffset,
            borderRadius: 0
          };
        },
        labelTextColor() {
          return this.options.bodyColor;
        },
        labelPointStyle(tooltipItem) {
          const meta = tooltipItem.chart.getDatasetMeta(tooltipItem.datasetIndex);
          const options = meta.controller.getStyle(tooltipItem.dataIndex);
          return {
            pointStyle: options.pointStyle,
            rotation: options.rotation
          };
        },
        afterLabel: noop2,
        afterBody: noop2,
        beforeFooter: noop2,
        footer: noop2,
        afterFooter: noop2
      }
    },
    defaultRoutes: {
      bodyFont: "font",
      footerFont: "font",
      titleFont: "font"
    },
    descriptors: {
      _scriptable: (name) => name !== "filter" && name !== "itemSort" && name !== "external",
      _indexable: false,
      callbacks: {
        _scriptable: false,
        _indexable: false
      },
      animation: {
        _fallback: false
      },
      animations: {
        _fallback: "animation"
      }
    },
    additionalOptionScopes: ["interaction"]
  };
  var plugins = /* @__PURE__ */ Object.freeze({
    __proto__: null,
    Decimation: plugin_decimation,
    Filler: plugin_filler,
    Legend: plugin_legend,
    SubTitle: plugin_subtitle,
    Title: plugin_title,
    Tooltip: plugin_tooltip
  });
  var addIfString = (labels, raw, index) => typeof raw === "string" ? labels.push(raw) - 1 : isNaN(raw) ? null : index;
  function findOrAddLabel(labels, raw, index) {
    const first = labels.indexOf(raw);
    if (first === -1) {
      return addIfString(labels, raw, index);
    }
    const last = labels.lastIndexOf(raw);
    return first !== last ? index : first;
  }
  var validIndex = (index, max2) => index === null ? null : _limitValue(Math.round(index), 0, max2);
  var CategoryScale = class extends Scale {
    constructor(cfg) {
      super(cfg);
      this._startValue = void 0;
      this._valueRange = 0;
    }
    parse(raw, index) {
      if (isNullOrUndef(raw)) {
        return null;
      }
      const labels = this.getLabels();
      index = isFinite(index) && labels[index] === raw ? index : findOrAddLabel(labels, raw, valueOrDefault(index, raw));
      return validIndex(index, labels.length - 1);
    }
    determineDataLimits() {
      const me2 = this;
      const { minDefined, maxDefined } = me2.getUserBounds();
      let { min: min2, max: max2 } = me2.getMinMax(true);
      if (me2.options.bounds === "ticks") {
        if (!minDefined) {
          min2 = 0;
        }
        if (!maxDefined) {
          max2 = me2.getLabels().length - 1;
        }
      }
      me2.min = min2;
      me2.max = max2;
    }
    buildTicks() {
      const me2 = this;
      const min2 = me2.min;
      const max2 = me2.max;
      const offset2 = me2.options.offset;
      const ticks = [];
      let labels = me2.getLabels();
      labels = min2 === 0 && max2 === labels.length - 1 ? labels : labels.slice(min2, max2 + 1);
      me2._valueRange = Math.max(labels.length - (offset2 ? 0 : 1), 1);
      me2._startValue = me2.min - (offset2 ? 0.5 : 0);
      for (let value = min2; value <= max2; value++) {
        ticks.push({ value });
      }
      return ticks;
    }
    getLabelForValue(value) {
      const me2 = this;
      const labels = me2.getLabels();
      if (value >= 0 && value < labels.length) {
        return labels[value];
      }
      return value;
    }
    configure() {
      const me2 = this;
      super.configure();
      if (!me2.isHorizontal()) {
        me2._reversePixels = !me2._reversePixels;
      }
    }
    getPixelForValue(value) {
      const me2 = this;
      if (typeof value !== "number") {
        value = me2.parse(value);
      }
      return value === null ? NaN : me2.getPixelForDecimal((value - me2._startValue) / me2._valueRange);
    }
    getPixelForTick(index) {
      const me2 = this;
      const ticks = me2.ticks;
      if (index < 0 || index > ticks.length - 1) {
        return null;
      }
      return me2.getPixelForValue(ticks[index].value);
    }
    getValueForPixel(pixel) {
      const me2 = this;
      return Math.round(me2._startValue + me2.getDecimalForPixel(pixel) * me2._valueRange);
    }
    getBasePixel() {
      return this.bottom;
    }
  };
  CategoryScale.id = "category";
  CategoryScale.defaults = {
    ticks: {
      callback: CategoryScale.prototype.getLabelForValue
    }
  };
  function generateTicks$1(generationOptions, dataRange) {
    const ticks = [];
    const MIN_SPACING = 1e-14;
    const { bounds, step, min: min2, max: max2, precision, count, maxTicks, maxDigits, includeBounds } = generationOptions;
    const unit = step || 1;
    const maxSpaces = maxTicks - 1;
    const { min: rmin, max: rmax } = dataRange;
    const minDefined = !isNullOrUndef(min2);
    const maxDefined = !isNullOrUndef(max2);
    const countDefined = !isNullOrUndef(count);
    const minSpacing = (rmax - rmin) / (maxDigits + 1);
    let spacing = niceNum((rmax - rmin) / maxSpaces / unit) * unit;
    let factor, niceMin, niceMax, numSpaces;
    if (spacing < MIN_SPACING && !minDefined && !maxDefined) {
      return [{ value: rmin }, { value: rmax }];
    }
    numSpaces = Math.ceil(rmax / spacing) - Math.floor(rmin / spacing);
    if (numSpaces > maxSpaces) {
      spacing = niceNum(numSpaces * spacing / maxSpaces / unit) * unit;
    }
    if (!isNullOrUndef(precision)) {
      factor = Math.pow(10, precision);
      spacing = Math.ceil(spacing * factor) / factor;
    }
    if (bounds === "ticks") {
      niceMin = Math.floor(rmin / spacing) * spacing;
      niceMax = Math.ceil(rmax / spacing) * spacing;
    } else {
      niceMin = rmin;
      niceMax = rmax;
    }
    if (minDefined && maxDefined && step && almostWhole((max2 - min2) / step, spacing / 1e3)) {
      numSpaces = Math.round(Math.min((max2 - min2) / spacing, maxTicks));
      spacing = (max2 - min2) / numSpaces;
      niceMin = min2;
      niceMax = max2;
    } else if (countDefined) {
      niceMin = minDefined ? min2 : niceMin;
      niceMax = maxDefined ? max2 : niceMax;
      numSpaces = count - 1;
      spacing = (niceMax - niceMin) / numSpaces;
    } else {
      numSpaces = (niceMax - niceMin) / spacing;
      if (almostEquals(numSpaces, Math.round(numSpaces), spacing / 1e3)) {
        numSpaces = Math.round(numSpaces);
      } else {
        numSpaces = Math.ceil(numSpaces);
      }
    }
    const decimalPlaces = Math.max(_decimalPlaces(spacing), _decimalPlaces(niceMin));
    factor = Math.pow(10, isNullOrUndef(precision) ? decimalPlaces : precision);
    niceMin = Math.round(niceMin * factor) / factor;
    niceMax = Math.round(niceMax * factor) / factor;
    let j2 = 0;
    if (minDefined) {
      if (includeBounds && niceMin !== min2) {
        ticks.push({ value: min2 });
        if (niceMin < min2) {
          j2++;
        }
        if (almostEquals(Math.round((niceMin + j2 * spacing) * factor) / factor, min2, relativeLabelSize(min2, minSpacing, generationOptions))) {
          j2++;
        }
      } else if (niceMin < min2) {
        j2++;
      }
    }
    for (; j2 < numSpaces; ++j2) {
      ticks.push({ value: Math.round((niceMin + j2 * spacing) * factor) / factor });
    }
    if (maxDefined && includeBounds && niceMax !== max2) {
      if (almostEquals(ticks[ticks.length - 1].value, max2, relativeLabelSize(max2, minSpacing, generationOptions))) {
        ticks[ticks.length - 1].value = max2;
      } else {
        ticks.push({ value: max2 });
      }
    } else if (!maxDefined || niceMax === max2) {
      ticks.push({ value: niceMax });
    }
    return ticks;
  }
  function relativeLabelSize(value, minSpacing, { horizontal, minRotation }) {
    const rad = toRadians(minRotation);
    const ratio = (horizontal ? Math.sin(rad) : Math.cos(rad)) || 1e-3;
    const length = 0.75 * minSpacing * ("" + value).length;
    return Math.min(minSpacing / ratio, length);
  }
  var LinearScaleBase = class extends Scale {
    constructor(cfg) {
      super(cfg);
      this.start = void 0;
      this.end = void 0;
      this._startValue = void 0;
      this._endValue = void 0;
      this._valueRange = 0;
    }
    parse(raw, index) {
      if (isNullOrUndef(raw)) {
        return null;
      }
      if ((typeof raw === "number" || raw instanceof Number) && !isFinite(+raw)) {
        return null;
      }
      return +raw;
    }
    handleTickRangeOptions() {
      const me2 = this;
      const { beginAtZero } = me2.options;
      const { minDefined, maxDefined } = me2.getUserBounds();
      let { min: min2, max: max2 } = me2;
      const setMin = (v2) => min2 = minDefined ? min2 : v2;
      const setMax = (v2) => max2 = maxDefined ? max2 : v2;
      if (beginAtZero) {
        const minSign = sign(min2);
        const maxSign = sign(max2);
        if (minSign < 0 && maxSign < 0) {
          setMax(0);
        } else if (minSign > 0 && maxSign > 0) {
          setMin(0);
        }
      }
      if (min2 === max2) {
        let offset2 = 1;
        if (max2 >= Number.MAX_SAFE_INTEGER || min2 <= Number.MIN_SAFE_INTEGER) {
          offset2 = Math.abs(max2 * 0.05);
        }
        setMax(max2 + offset2);
        if (!beginAtZero) {
          setMin(min2 - offset2);
        }
      }
      me2.min = min2;
      me2.max = max2;
    }
    getTickLimit() {
      const me2 = this;
      const tickOpts = me2.options.ticks;
      let { maxTicksLimit, stepSize } = tickOpts;
      let maxTicks;
      if (stepSize) {
        maxTicks = Math.ceil(me2.max / stepSize) - Math.floor(me2.min / stepSize) + 1;
      } else {
        maxTicks = me2.computeTickLimit();
        maxTicksLimit = maxTicksLimit || 11;
      }
      if (maxTicksLimit) {
        maxTicks = Math.min(maxTicksLimit, maxTicks);
      }
      return maxTicks;
    }
    computeTickLimit() {
      return Number.POSITIVE_INFINITY;
    }
    buildTicks() {
      const me2 = this;
      const opts = me2.options;
      const tickOpts = opts.ticks;
      let maxTicks = me2.getTickLimit();
      maxTicks = Math.max(2, maxTicks);
      const numericGeneratorOptions = {
        maxTicks,
        bounds: opts.bounds,
        min: opts.min,
        max: opts.max,
        precision: tickOpts.precision,
        step: tickOpts.stepSize,
        count: tickOpts.count,
        maxDigits: me2._maxDigits(),
        horizontal: me2.isHorizontal(),
        minRotation: tickOpts.minRotation || 0,
        includeBounds: tickOpts.includeBounds !== false
      };
      const dataRange = me2._range || me2;
      const ticks = generateTicks$1(numericGeneratorOptions, dataRange);
      if (opts.bounds === "ticks") {
        _setMinAndMaxByKey(ticks, me2, "value");
      }
      if (opts.reverse) {
        ticks.reverse();
        me2.start = me2.max;
        me2.end = me2.min;
      } else {
        me2.start = me2.min;
        me2.end = me2.max;
      }
      return ticks;
    }
    configure() {
      const me2 = this;
      const ticks = me2.ticks;
      let start4 = me2.min;
      let end2 = me2.max;
      super.configure();
      if (me2.options.offset && ticks.length) {
        const offset2 = (end2 - start4) / Math.max(ticks.length - 1, 1) / 2;
        start4 -= offset2;
        end2 += offset2;
      }
      me2._startValue = start4;
      me2._endValue = end2;
      me2._valueRange = end2 - start4;
    }
    getLabelForValue(value) {
      return formatNumber(value, this.chart.options.locale);
    }
  };
  var LinearScale = class extends LinearScaleBase {
    determineDataLimits() {
      const me2 = this;
      const { min: min2, max: max2 } = me2.getMinMax(true);
      me2.min = isNumberFinite(min2) ? min2 : 0;
      me2.max = isNumberFinite(max2) ? max2 : 1;
      me2.handleTickRangeOptions();
    }
    computeTickLimit() {
      const me2 = this;
      const horizontal = me2.isHorizontal();
      const length = horizontal ? me2.width : me2.height;
      const minRotation = toRadians(me2.options.ticks.minRotation);
      const ratio = (horizontal ? Math.sin(minRotation) : Math.cos(minRotation)) || 1e-3;
      const tickFont = me2._resolveTickFontOptions(0);
      return Math.ceil(length / Math.min(40, tickFont.lineHeight / ratio));
    }
    getPixelForValue(value) {
      return value === null ? NaN : this.getPixelForDecimal((value - this._startValue) / this._valueRange);
    }
    getValueForPixel(pixel) {
      return this._startValue + this.getDecimalForPixel(pixel) * this._valueRange;
    }
  };
  LinearScale.id = "linear";
  LinearScale.defaults = {
    ticks: {
      callback: Ticks.formatters.numeric
    }
  };
  function isMajor(tickVal) {
    const remain = tickVal / Math.pow(10, Math.floor(log10(tickVal)));
    return remain === 1;
  }
  function generateTicks(generationOptions, dataRange) {
    const endExp = Math.floor(log10(dataRange.max));
    const endSignificand = Math.ceil(dataRange.max / Math.pow(10, endExp));
    const ticks = [];
    let tickVal = finiteOrDefault(generationOptions.min, Math.pow(10, Math.floor(log10(dataRange.min))));
    let exp = Math.floor(log10(tickVal));
    let significand = Math.floor(tickVal / Math.pow(10, exp));
    let precision = exp < 0 ? Math.pow(10, Math.abs(exp)) : 1;
    do {
      ticks.push({ value: tickVal, major: isMajor(tickVal) });
      ++significand;
      if (significand === 10) {
        significand = 1;
        ++exp;
        precision = exp >= 0 ? 1 : precision;
      }
      tickVal = Math.round(significand * Math.pow(10, exp) * precision) / precision;
    } while (exp < endExp || exp === endExp && significand < endSignificand);
    const lastTick = finiteOrDefault(generationOptions.max, tickVal);
    ticks.push({ value: lastTick, major: isMajor(tickVal) });
    return ticks;
  }
  var LogarithmicScale = class extends Scale {
    constructor(cfg) {
      super(cfg);
      this.start = void 0;
      this.end = void 0;
      this._startValue = void 0;
      this._valueRange = 0;
    }
    parse(raw, index) {
      const value = LinearScaleBase.prototype.parse.apply(this, [raw, index]);
      if (value === 0) {
        this._zero = true;
        return void 0;
      }
      return isNumberFinite(value) && value > 0 ? value : null;
    }
    determineDataLimits() {
      const me2 = this;
      const { min: min2, max: max2 } = me2.getMinMax(true);
      me2.min = isNumberFinite(min2) ? Math.max(0, min2) : null;
      me2.max = isNumberFinite(max2) ? Math.max(0, max2) : null;
      if (me2.options.beginAtZero) {
        me2._zero = true;
      }
      me2.handleTickRangeOptions();
    }
    handleTickRangeOptions() {
      const me2 = this;
      const { minDefined, maxDefined } = me2.getUserBounds();
      let min2 = me2.min;
      let max2 = me2.max;
      const setMin = (v2) => min2 = minDefined ? min2 : v2;
      const setMax = (v2) => max2 = maxDefined ? max2 : v2;
      const exp = (v2, m2) => Math.pow(10, Math.floor(log10(v2)) + m2);
      if (min2 === max2) {
        if (min2 <= 0) {
          setMin(1);
          setMax(10);
        } else {
          setMin(exp(min2, -1));
          setMax(exp(max2, 1));
        }
      }
      if (min2 <= 0) {
        setMin(exp(max2, -1));
      }
      if (max2 <= 0) {
        setMax(exp(min2, 1));
      }
      if (me2._zero && me2.min !== me2._suggestedMin && min2 === exp(me2.min, 0)) {
        setMin(exp(min2, -1));
      }
      me2.min = min2;
      me2.max = max2;
    }
    buildTicks() {
      const me2 = this;
      const opts = me2.options;
      const generationOptions = {
        min: me2._userMin,
        max: me2._userMax
      };
      const ticks = generateTicks(generationOptions, me2);
      if (opts.bounds === "ticks") {
        _setMinAndMaxByKey(ticks, me2, "value");
      }
      if (opts.reverse) {
        ticks.reverse();
        me2.start = me2.max;
        me2.end = me2.min;
      } else {
        me2.start = me2.min;
        me2.end = me2.max;
      }
      return ticks;
    }
    getLabelForValue(value) {
      return value === void 0 ? "0" : formatNumber(value, this.chart.options.locale);
    }
    configure() {
      const me2 = this;
      const start4 = me2.min;
      super.configure();
      me2._startValue = log10(start4);
      me2._valueRange = log10(me2.max) - log10(start4);
    }
    getPixelForValue(value) {
      const me2 = this;
      if (value === void 0 || value === 0) {
        value = me2.min;
      }
      if (value === null || isNaN(value)) {
        return NaN;
      }
      return me2.getPixelForDecimal(value === me2.min ? 0 : (log10(value) - me2._startValue) / me2._valueRange);
    }
    getValueForPixel(pixel) {
      const me2 = this;
      const decimal = me2.getDecimalForPixel(pixel);
      return Math.pow(10, me2._startValue + decimal * me2._valueRange);
    }
  };
  LogarithmicScale.id = "logarithmic";
  LogarithmicScale.defaults = {
    ticks: {
      callback: Ticks.formatters.logarithmic,
      major: {
        enabled: true
      }
    }
  };
  function getTickBackdropHeight(opts) {
    const tickOpts = opts.ticks;
    if (tickOpts.display && opts.display) {
      const padding = toPadding(tickOpts.backdropPadding);
      return valueOrDefault(tickOpts.font && tickOpts.font.size, defaults.font.size) + padding.height;
    }
    return 0;
  }
  function measureLabelSize(ctx, font, label) {
    label = isArray(label) ? label : [label];
    return {
      w: _longestText(ctx, font.string, label),
      h: label.length * font.lineHeight
    };
  }
  function determineLimits(angle, pos, size, min2, max2) {
    if (angle === min2 || angle === max2) {
      return {
        start: pos - size / 2,
        end: pos + size / 2
      };
    } else if (angle < min2 || angle > max2) {
      return {
        start: pos - size,
        end: pos
      };
    }
    return {
      start: pos,
      end: pos + size
    };
  }
  function fitWithPointLabels(scale) {
    const furthestLimits = {
      l: 0,
      r: scale.width,
      t: 0,
      b: scale.height - scale.paddingTop
    };
    const furthestAngles = {};
    const labelSizes = [];
    const padding = [];
    const valueCount = scale.getLabels().length;
    for (let i2 = 0; i2 < valueCount; i2++) {
      const opts = scale.options.pointLabels.setContext(scale.getPointLabelContext(i2));
      padding[i2] = opts.padding;
      const pointPosition = scale.getPointPosition(i2, scale.drawingArea + padding[i2]);
      const plFont = toFont(opts.font);
      const textSize = measureLabelSize(scale.ctx, plFont, scale._pointLabels[i2]);
      labelSizes[i2] = textSize;
      const angleRadians = scale.getIndexAngle(i2);
      const angle = toDegrees(angleRadians);
      const hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180);
      const vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270);
      if (hLimits.start < furthestLimits.l) {
        furthestLimits.l = hLimits.start;
        furthestAngles.l = angleRadians;
      }
      if (hLimits.end > furthestLimits.r) {
        furthestLimits.r = hLimits.end;
        furthestAngles.r = angleRadians;
      }
      if (vLimits.start < furthestLimits.t) {
        furthestLimits.t = vLimits.start;
        furthestAngles.t = angleRadians;
      }
      if (vLimits.end > furthestLimits.b) {
        furthestLimits.b = vLimits.end;
        furthestAngles.b = angleRadians;
      }
    }
    scale._setReductions(scale.drawingArea, furthestLimits, furthestAngles);
    scale._pointLabelItems = buildPointLabelItems(scale, labelSizes, padding);
  }
  function buildPointLabelItems(scale, labelSizes, padding) {
    const items = [];
    const valueCount = scale.getLabels().length;
    const opts = scale.options;
    const tickBackdropHeight = getTickBackdropHeight(opts);
    const outerDistance = scale.getDistanceFromCenterForValue(opts.ticks.reverse ? scale.min : scale.max);
    for (let i2 = 0; i2 < valueCount; i2++) {
      const extra = i2 === 0 ? tickBackdropHeight / 2 : 0;
      const pointLabelPosition = scale.getPointPosition(i2, outerDistance + extra + padding[i2]);
      const angle = toDegrees(scale.getIndexAngle(i2));
      const size = labelSizes[i2];
      const y2 = yForAngle(pointLabelPosition.y, size.h, angle);
      const textAlign = getTextAlignForAngle(angle);
      const left2 = leftForTextAlign(pointLabelPosition.x, size.w, textAlign);
      items.push({
        x: pointLabelPosition.x,
        y: y2,
        textAlign,
        left: left2,
        top: y2,
        right: left2 + size.w,
        bottom: y2 + size.h
      });
    }
    return items;
  }
  function getTextAlignForAngle(angle) {
    if (angle === 0 || angle === 180) {
      return "center";
    } else if (angle < 180) {
      return "left";
    }
    return "right";
  }
  function leftForTextAlign(x2, w2, align) {
    if (align === "right") {
      x2 -= w2;
    } else if (align === "center") {
      x2 -= w2 / 2;
    }
    return x2;
  }
  function yForAngle(y2, h3, angle) {
    if (angle === 90 || angle === 270) {
      y2 -= h3 / 2;
    } else if (angle > 270 || angle < 90) {
      y2 -= h3;
    }
    return y2;
  }
  function drawPointLabels(scale, labelCount) {
    const { ctx, options: { pointLabels } } = scale;
    for (let i2 = labelCount - 1; i2 >= 0; i2--) {
      const optsAtIndex = pointLabels.setContext(scale.getPointLabelContext(i2));
      const plFont = toFont(optsAtIndex.font);
      const { x: x2, y: y2, textAlign, left: left2, top: top2, right: right2, bottom: bottom2 } = scale._pointLabelItems[i2];
      const { backdropColor } = optsAtIndex;
      if (!isNullOrUndef(backdropColor)) {
        const padding = toPadding(optsAtIndex.backdropPadding);
        ctx.fillStyle = backdropColor;
        ctx.fillRect(left2 - padding.left, top2 - padding.top, right2 - left2 + padding.width, bottom2 - top2 + padding.height);
      }
      renderText(ctx, scale._pointLabels[i2], x2, y2 + plFont.lineHeight / 2, plFont, {
        color: optsAtIndex.color,
        textAlign,
        textBaseline: "middle"
      });
    }
  }
  function pathRadiusLine(scale, radius, circular, labelCount) {
    const { ctx } = scale;
    if (circular) {
      ctx.arc(scale.xCenter, scale.yCenter, radius, 0, TAU);
    } else {
      let pointPosition = scale.getPointPosition(0, radius);
      ctx.moveTo(pointPosition.x, pointPosition.y);
      for (let i2 = 1; i2 < labelCount; i2++) {
        pointPosition = scale.getPointPosition(i2, radius);
        ctx.lineTo(pointPosition.x, pointPosition.y);
      }
    }
  }
  function drawRadiusLine(scale, gridLineOpts, radius, labelCount) {
    const ctx = scale.ctx;
    const circular = gridLineOpts.circular;
    const { color: color2, lineWidth } = gridLineOpts;
    if (!circular && !labelCount || !color2 || !lineWidth || radius < 0) {
      return;
    }
    ctx.save();
    ctx.strokeStyle = color2;
    ctx.lineWidth = lineWidth;
    ctx.setLineDash(gridLineOpts.borderDash);
    ctx.lineDashOffset = gridLineOpts.borderDashOffset;
    ctx.beginPath();
    pathRadiusLine(scale, radius, circular, labelCount);
    ctx.closePath();
    ctx.stroke();
    ctx.restore();
  }
  function numberOrZero2(param) {
    return isNumber(param) ? param : 0;
  }
  function createPointLabelContext(parent, index, label) {
    return Object.assign(Object.create(parent), {
      label,
      index,
      type: "pointLabel"
    });
  }
  var RadialLinearScale = class extends LinearScaleBase {
    constructor(cfg) {
      super(cfg);
      this.xCenter = void 0;
      this.yCenter = void 0;
      this.drawingArea = void 0;
      this._pointLabels = [];
      this._pointLabelItems = [];
    }
    setDimensions() {
      const me2 = this;
      me2.width = me2.maxWidth;
      me2.height = me2.maxHeight;
      me2.paddingTop = getTickBackdropHeight(me2.options) / 2;
      me2.xCenter = Math.floor(me2.width / 2);
      me2.yCenter = Math.floor((me2.height - me2.paddingTop) / 2);
      me2.drawingArea = Math.min(me2.height - me2.paddingTop, me2.width) / 2;
    }
    determineDataLimits() {
      const me2 = this;
      const { min: min2, max: max2 } = me2.getMinMax(false);
      me2.min = isNumberFinite(min2) && !isNaN(min2) ? min2 : 0;
      me2.max = isNumberFinite(max2) && !isNaN(max2) ? max2 : 0;
      me2.handleTickRangeOptions();
    }
    computeTickLimit() {
      return Math.ceil(this.drawingArea / getTickBackdropHeight(this.options));
    }
    generateTickLabels(ticks) {
      const me2 = this;
      LinearScaleBase.prototype.generateTickLabels.call(me2, ticks);
      me2._pointLabels = me2.getLabels().map((value, index) => {
        const label = callback(me2.options.pointLabels.callback, [value, index], me2);
        return label || label === 0 ? label : "";
      });
    }
    fit() {
      const me2 = this;
      const opts = me2.options;
      if (opts.display && opts.pointLabels.display) {
        fitWithPointLabels(me2);
      } else {
        me2.setCenterPoint(0, 0, 0, 0);
      }
    }
    _setReductions(largestPossibleRadius, furthestLimits, furthestAngles) {
      const me2 = this;
      let radiusReductionLeft = furthestLimits.l / Math.sin(furthestAngles.l);
      let radiusReductionRight = Math.max(furthestLimits.r - me2.width, 0) / Math.sin(furthestAngles.r);
      let radiusReductionTop = -furthestLimits.t / Math.cos(furthestAngles.t);
      let radiusReductionBottom = -Math.max(furthestLimits.b - (me2.height - me2.paddingTop), 0) / Math.cos(furthestAngles.b);
      radiusReductionLeft = numberOrZero2(radiusReductionLeft);
      radiusReductionRight = numberOrZero2(radiusReductionRight);
      radiusReductionTop = numberOrZero2(radiusReductionTop);
      radiusReductionBottom = numberOrZero2(radiusReductionBottom);
      me2.drawingArea = Math.max(largestPossibleRadius / 2, Math.min(Math.floor(largestPossibleRadius - (radiusReductionLeft + radiusReductionRight) / 2), Math.floor(largestPossibleRadius - (radiusReductionTop + radiusReductionBottom) / 2)));
      me2.setCenterPoint(radiusReductionLeft, radiusReductionRight, radiusReductionTop, radiusReductionBottom);
    }
    setCenterPoint(leftMovement, rightMovement, topMovement, bottomMovement) {
      const me2 = this;
      const maxRight = me2.width - rightMovement - me2.drawingArea;
      const maxLeft = leftMovement + me2.drawingArea;
      const maxTop = topMovement + me2.drawingArea;
      const maxBottom = me2.height - me2.paddingTop - bottomMovement - me2.drawingArea;
      me2.xCenter = Math.floor((maxLeft + maxRight) / 2 + me2.left);
      me2.yCenter = Math.floor((maxTop + maxBottom) / 2 + me2.top + me2.paddingTop);
    }
    getIndexAngle(index) {
      const angleMultiplier = TAU / this.getLabels().length;
      const startAngle = this.options.startAngle || 0;
      return _normalizeAngle(index * angleMultiplier + toRadians(startAngle));
    }
    getDistanceFromCenterForValue(value) {
      const me2 = this;
      if (isNullOrUndef(value)) {
        return NaN;
      }
      const scalingFactor = me2.drawingArea / (me2.max - me2.min);
      if (me2.options.reverse) {
        return (me2.max - value) * scalingFactor;
      }
      return (value - me2.min) * scalingFactor;
    }
    getValueForDistanceFromCenter(distance) {
      if (isNullOrUndef(distance)) {
        return NaN;
      }
      const me2 = this;
      const scaledDistance = distance / (me2.drawingArea / (me2.max - me2.min));
      return me2.options.reverse ? me2.max - scaledDistance : me2.min + scaledDistance;
    }
    getPointLabelContext(index) {
      const me2 = this;
      const pointLabels = me2._pointLabels || [];
      if (index >= 0 && index < pointLabels.length) {
        const pointLabel = pointLabels[index];
        return createPointLabelContext(me2.getContext(), index, pointLabel);
      }
    }
    getPointPosition(index, distanceFromCenter) {
      const me2 = this;
      const angle = me2.getIndexAngle(index) - HALF_PI;
      return {
        x: Math.cos(angle) * distanceFromCenter + me2.xCenter,
        y: Math.sin(angle) * distanceFromCenter + me2.yCenter,
        angle
      };
    }
    getPointPositionForValue(index, value) {
      return this.getPointPosition(index, this.getDistanceFromCenterForValue(value));
    }
    getBasePosition(index) {
      return this.getPointPositionForValue(index || 0, this.getBaseValue());
    }
    getPointLabelPosition(index) {
      const { left: left2, top: top2, right: right2, bottom: bottom2 } = this._pointLabelItems[index];
      return {
        left: left2,
        top: top2,
        right: right2,
        bottom: bottom2
      };
    }
    drawBackground() {
      const me2 = this;
      const { backgroundColor, grid: { circular } } = me2.options;
      if (backgroundColor) {
        const ctx = me2.ctx;
        ctx.save();
        ctx.beginPath();
        pathRadiusLine(me2, me2.getDistanceFromCenterForValue(me2._endValue), circular, me2.getLabels().length);
        ctx.closePath();
        ctx.fillStyle = backgroundColor;
        ctx.fill();
        ctx.restore();
      }
    }
    drawGrid() {
      const me2 = this;
      const ctx = me2.ctx;
      const opts = me2.options;
      const { angleLines, grid } = opts;
      const labelCount = me2.getLabels().length;
      let i2, offset2, position;
      if (opts.pointLabels.display) {
        drawPointLabels(me2, labelCount);
      }
      if (grid.display) {
        me2.ticks.forEach((tick, index) => {
          if (index !== 0) {
            offset2 = me2.getDistanceFromCenterForValue(tick.value);
            const optsAtIndex = grid.setContext(me2.getContext(index - 1));
            drawRadiusLine(me2, optsAtIndex, offset2, labelCount);
          }
        });
      }
      if (angleLines.display) {
        ctx.save();
        for (i2 = me2.getLabels().length - 1; i2 >= 0; i2--) {
          const optsAtIndex = angleLines.setContext(me2.getPointLabelContext(i2));
          const { color: color2, lineWidth } = optsAtIndex;
          if (!lineWidth || !color2) {
            continue;
          }
          ctx.lineWidth = lineWidth;
          ctx.strokeStyle = color2;
          ctx.setLineDash(optsAtIndex.borderDash);
          ctx.lineDashOffset = optsAtIndex.borderDashOffset;
          offset2 = me2.getDistanceFromCenterForValue(opts.ticks.reverse ? me2.min : me2.max);
          position = me2.getPointPosition(i2, offset2);
          ctx.beginPath();
          ctx.moveTo(me2.xCenter, me2.yCenter);
          ctx.lineTo(position.x, position.y);
          ctx.stroke();
        }
        ctx.restore();
      }
    }
    drawBorder() {
    }
    drawLabels() {
      const me2 = this;
      const ctx = me2.ctx;
      const opts = me2.options;
      const tickOpts = opts.ticks;
      if (!tickOpts.display) {
        return;
      }
      const startAngle = me2.getIndexAngle(0);
      let offset2, width;
      ctx.save();
      ctx.translate(me2.xCenter, me2.yCenter);
      ctx.rotate(startAngle);
      ctx.textAlign = "center";
      ctx.textBaseline = "middle";
      me2.ticks.forEach((tick, index) => {
        if (index === 0 && !opts.reverse) {
          return;
        }
        const optsAtIndex = tickOpts.setContext(me2.getContext(index));
        const tickFont = toFont(optsAtIndex.font);
        offset2 = me2.getDistanceFromCenterForValue(me2.ticks[index].value);
        if (optsAtIndex.showLabelBackdrop) {
          ctx.font = tickFont.string;
          width = ctx.measureText(tick.label).width;
          ctx.fillStyle = optsAtIndex.backdropColor;
          const padding = toPadding(optsAtIndex.backdropPadding);
          ctx.fillRect(-width / 2 - padding.left, -offset2 - tickFont.size / 2 - padding.top, width + padding.width, tickFont.size + padding.height);
        }
        renderText(ctx, tick.label, 0, -offset2, tickFont, {
          color: optsAtIndex.color
        });
      });
      ctx.restore();
    }
    drawTitle() {
    }
  };
  RadialLinearScale.id = "radialLinear";
  RadialLinearScale.defaults = {
    display: true,
    animate: true,
    position: "chartArea",
    angleLines: {
      display: true,
      lineWidth: 1,
      borderDash: [],
      borderDashOffset: 0
    },
    grid: {
      circular: false
    },
    startAngle: 0,
    ticks: {
      showLabelBackdrop: true,
      callback: Ticks.formatters.numeric
    },
    pointLabels: {
      backdropColor: void 0,
      backdropPadding: 2,
      display: true,
      font: {
        size: 10
      },
      callback(label) {
        return label;
      },
      padding: 5
    }
  };
  RadialLinearScale.defaultRoutes = {
    "angleLines.color": "borderColor",
    "pointLabels.color": "color",
    "ticks.color": "color"
  };
  RadialLinearScale.descriptors = {
    angleLines: {
      _fallback: "grid"
    }
  };
  var INTERVALS = {
    millisecond: { common: true, size: 1, steps: 1e3 },
    second: { common: true, size: 1e3, steps: 60 },
    minute: { common: true, size: 6e4, steps: 60 },
    hour: { common: true, size: 36e5, steps: 24 },
    day: { common: true, size: 864e5, steps: 30 },
    week: { common: false, size: 6048e5, steps: 4 },
    month: { common: true, size: 2628e6, steps: 12 },
    quarter: { common: false, size: 7884e6, steps: 4 },
    year: { common: true, size: 3154e7 }
  };
  var UNITS = Object.keys(INTERVALS);
  function sorter(a2, b2) {
    return a2 - b2;
  }
  function parse(scale, input) {
    if (isNullOrUndef(input)) {
      return null;
    }
    const adapter = scale._adapter;
    const { parser, round: round3, isoWeekday } = scale._parseOpts;
    let value = input;
    if (typeof parser === "function") {
      value = parser(value);
    }
    if (!isNumberFinite(value)) {
      value = typeof parser === "string" ? adapter.parse(value, parser) : adapter.parse(value);
    }
    if (value === null) {
      return null;
    }
    if (round3) {
      value = round3 === "week" && (isNumber(isoWeekday) || isoWeekday === true) ? adapter.startOf(value, "isoWeek", isoWeekday) : adapter.startOf(value, round3);
    }
    return +value;
  }
  function determineUnitForAutoTicks(minUnit, min2, max2, capacity) {
    const ilen = UNITS.length;
    for (let i2 = UNITS.indexOf(minUnit); i2 < ilen - 1; ++i2) {
      const interval = INTERVALS[UNITS[i2]];
      const factor = interval.steps ? interval.steps : Number.MAX_SAFE_INTEGER;
      if (interval.common && Math.ceil((max2 - min2) / (factor * interval.size)) <= capacity) {
        return UNITS[i2];
      }
    }
    return UNITS[ilen - 1];
  }
  function determineUnitForFormatting(scale, numTicks, minUnit, min2, max2) {
    for (let i2 = UNITS.length - 1; i2 >= UNITS.indexOf(minUnit); i2--) {
      const unit = UNITS[i2];
      if (INTERVALS[unit].common && scale._adapter.diff(max2, min2, unit) >= numTicks - 1) {
        return unit;
      }
    }
    return UNITS[minUnit ? UNITS.indexOf(minUnit) : 0];
  }
  function determineMajorUnit(unit) {
    for (let i2 = UNITS.indexOf(unit) + 1, ilen = UNITS.length; i2 < ilen; ++i2) {
      if (INTERVALS[UNITS[i2]].common) {
        return UNITS[i2];
      }
    }
  }
  function addTick(ticks, time, timestamps) {
    if (!timestamps) {
      ticks[time] = true;
    } else if (timestamps.length) {
      const { lo, hi: hi2 } = _lookup(timestamps, time);
      const timestamp = timestamps[lo] >= time ? timestamps[lo] : timestamps[hi2];
      ticks[timestamp] = true;
    }
  }
  function setMajorTicks(scale, ticks, map3, majorUnit) {
    const adapter = scale._adapter;
    const first = +adapter.startOf(ticks[0].value, majorUnit);
    const last = ticks[ticks.length - 1].value;
    let major, index;
    for (major = first; major <= last; major = +adapter.add(major, 1, majorUnit)) {
      index = map3[major];
      if (index >= 0) {
        ticks[index].major = true;
      }
    }
    return ticks;
  }
  function ticksFromTimestamps(scale, values, majorUnit) {
    const ticks = [];
    const map3 = {};
    const ilen = values.length;
    let i2, value;
    for (i2 = 0; i2 < ilen; ++i2) {
      value = values[i2];
      map3[value] = i2;
      ticks.push({
        value,
        major: false
      });
    }
    return ilen === 0 || !majorUnit ? ticks : setMajorTicks(scale, ticks, map3, majorUnit);
  }
  var TimeScale = class extends Scale {
    constructor(props) {
      super(props);
      this._cache = {
        data: [],
        labels: [],
        all: []
      };
      this._unit = "day";
      this._majorUnit = void 0;
      this._offsets = {};
      this._normalized = false;
      this._parseOpts = void 0;
    }
    init(scaleOpts, opts) {
      const time = scaleOpts.time || (scaleOpts.time = {});
      const adapter = this._adapter = new adapters._date(scaleOpts.adapters.date);
      mergeIf(time.displayFormats, adapter.formats());
      this._parseOpts = {
        parser: time.parser,
        round: time.round,
        isoWeekday: time.isoWeekday
      };
      super.init(scaleOpts);
      this._normalized = opts.normalized;
    }
    parse(raw, index) {
      if (raw === void 0) {
        return null;
      }
      return parse(this, raw);
    }
    beforeLayout() {
      super.beforeLayout();
      this._cache = {
        data: [],
        labels: [],
        all: []
      };
    }
    determineDataLimits() {
      const me2 = this;
      const options = me2.options;
      const adapter = me2._adapter;
      const unit = options.time.unit || "day";
      let { min: min2, max: max2, minDefined, maxDefined } = me2.getUserBounds();
      function _applyBounds(bounds) {
        if (!minDefined && !isNaN(bounds.min)) {
          min2 = Math.min(min2, bounds.min);
        }
        if (!maxDefined && !isNaN(bounds.max)) {
          max2 = Math.max(max2, bounds.max);
        }
      }
      if (!minDefined || !maxDefined) {
        _applyBounds(me2._getLabelBounds());
        if (options.bounds !== "ticks" || options.ticks.source !== "labels") {
          _applyBounds(me2.getMinMax(false));
        }
      }
      min2 = isNumberFinite(min2) && !isNaN(min2) ? min2 : +adapter.startOf(Date.now(), unit);
      max2 = isNumberFinite(max2) && !isNaN(max2) ? max2 : +adapter.endOf(Date.now(), unit) + 1;
      me2.min = Math.min(min2, max2 - 1);
      me2.max = Math.max(min2 + 1, max2);
    }
    _getLabelBounds() {
      const arr = this.getLabelTimestamps();
      let min2 = Number.POSITIVE_INFINITY;
      let max2 = Number.NEGATIVE_INFINITY;
      if (arr.length) {
        min2 = arr[0];
        max2 = arr[arr.length - 1];
      }
      return { min: min2, max: max2 };
    }
    buildTicks() {
      const me2 = this;
      const options = me2.options;
      const timeOpts = options.time;
      const tickOpts = options.ticks;
      const timestamps = tickOpts.source === "labels" ? me2.getLabelTimestamps() : me2._generate();
      if (options.bounds === "ticks" && timestamps.length) {
        me2.min = me2._userMin || timestamps[0];
        me2.max = me2._userMax || timestamps[timestamps.length - 1];
      }
      const min2 = me2.min;
      const max2 = me2.max;
      const ticks = _filterBetween(timestamps, min2, max2);
      me2._unit = timeOpts.unit || (tickOpts.autoSkip ? determineUnitForAutoTicks(timeOpts.minUnit, me2.min, me2.max, me2._getLabelCapacity(min2)) : determineUnitForFormatting(me2, ticks.length, timeOpts.minUnit, me2.min, me2.max));
      me2._majorUnit = !tickOpts.major.enabled || me2._unit === "year" ? void 0 : determineMajorUnit(me2._unit);
      me2.initOffsets(timestamps);
      if (options.reverse) {
        ticks.reverse();
      }
      return ticksFromTimestamps(me2, ticks, me2._majorUnit);
    }
    initOffsets(timestamps) {
      const me2 = this;
      let start4 = 0;
      let end2 = 0;
      let first, last;
      if (me2.options.offset && timestamps.length) {
        first = me2.getDecimalForValue(timestamps[0]);
        if (timestamps.length === 1) {
          start4 = 1 - first;
        } else {
          start4 = (me2.getDecimalForValue(timestamps[1]) - first) / 2;
        }
        last = me2.getDecimalForValue(timestamps[timestamps.length - 1]);
        if (timestamps.length === 1) {
          end2 = last;
        } else {
          end2 = (last - me2.getDecimalForValue(timestamps[timestamps.length - 2])) / 2;
        }
      }
      const limit = timestamps.length < 3 ? 0.5 : 0.25;
      start4 = _limitValue(start4, 0, limit);
      end2 = _limitValue(end2, 0, limit);
      me2._offsets = { start: start4, end: end2, factor: 1 / (start4 + 1 + end2) };
    }
    _generate() {
      const me2 = this;
      const adapter = me2._adapter;
      const min2 = me2.min;
      const max2 = me2.max;
      const options = me2.options;
      const timeOpts = options.time;
      const minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min2, max2, me2._getLabelCapacity(min2));
      const stepSize = valueOrDefault(timeOpts.stepSize, 1);
      const weekday = minor === "week" ? timeOpts.isoWeekday : false;
      const hasWeekday = isNumber(weekday) || weekday === true;
      const ticks = {};
      let first = min2;
      let time, count;
      if (hasWeekday) {
        first = +adapter.startOf(first, "isoWeek", weekday);
      }
      first = +adapter.startOf(first, hasWeekday ? "day" : minor);
      if (adapter.diff(max2, min2, minor) > 1e5 * stepSize) {
        throw new Error(min2 + " and " + max2 + " are too far apart with stepSize of " + stepSize + " " + minor);
      }
      const timestamps = options.ticks.source === "data" && me2.getDataTimestamps();
      for (time = first, count = 0; time < max2; time = +adapter.add(time, stepSize, minor), count++) {
        addTick(ticks, time, timestamps);
      }
      if (time === max2 || options.bounds === "ticks" || count === 1) {
        addTick(ticks, time, timestamps);
      }
      return Object.keys(ticks).sort((a2, b2) => a2 - b2).map((x2) => +x2);
    }
    getLabelForValue(value) {
      const me2 = this;
      const adapter = me2._adapter;
      const timeOpts = me2.options.time;
      if (timeOpts.tooltipFormat) {
        return adapter.format(value, timeOpts.tooltipFormat);
      }
      return adapter.format(value, timeOpts.displayFormats.datetime);
    }
    _tickFormatFunction(time, index, ticks, format3) {
      const me2 = this;
      const options = me2.options;
      const formats = options.time.displayFormats;
      const unit = me2._unit;
      const majorUnit = me2._majorUnit;
      const minorFormat = unit && formats[unit];
      const majorFormat = majorUnit && formats[majorUnit];
      const tick = ticks[index];
      const major = majorUnit && majorFormat && tick && tick.major;
      const label = me2._adapter.format(time, format3 || (major ? majorFormat : minorFormat));
      const formatter = options.ticks.callback;
      return formatter ? callback(formatter, [label, index, ticks], me2) : label;
    }
    generateTickLabels(ticks) {
      let i2, ilen, tick;
      for (i2 = 0, ilen = ticks.length; i2 < ilen; ++i2) {
        tick = ticks[i2];
        tick.label = this._tickFormatFunction(tick.value, i2, ticks);
      }
    }
    getDecimalForValue(value) {
      const me2 = this;
      return value === null ? NaN : (value - me2.min) / (me2.max - me2.min);
    }
    getPixelForValue(value) {
      const me2 = this;
      const offsets = me2._offsets;
      const pos = me2.getDecimalForValue(value);
      return me2.getPixelForDecimal((offsets.start + pos) * offsets.factor);
    }
    getValueForPixel(pixel) {
      const me2 = this;
      const offsets = me2._offsets;
      const pos = me2.getDecimalForPixel(pixel) / offsets.factor - offsets.end;
      return me2.min + pos * (me2.max - me2.min);
    }
    _getLabelSize(label) {
      const me2 = this;
      const ticksOpts = me2.options.ticks;
      const tickLabelWidth = me2.ctx.measureText(label).width;
      const angle = toRadians(me2.isHorizontal() ? ticksOpts.maxRotation : ticksOpts.minRotation);
      const cosRotation = Math.cos(angle);
      const sinRotation = Math.sin(angle);
      const tickFontSize = me2._resolveTickFontOptions(0).size;
      return {
        w: tickLabelWidth * cosRotation + tickFontSize * sinRotation,
        h: tickLabelWidth * sinRotation + tickFontSize * cosRotation
      };
    }
    _getLabelCapacity(exampleTime) {
      const me2 = this;
      const timeOpts = me2.options.time;
      const displayFormats = timeOpts.displayFormats;
      const format3 = displayFormats[timeOpts.unit] || displayFormats.millisecond;
      const exampleLabel = me2._tickFormatFunction(exampleTime, 0, ticksFromTimestamps(me2, [exampleTime], me2._majorUnit), format3);
      const size = me2._getLabelSize(exampleLabel);
      const capacity = Math.floor(me2.isHorizontal() ? me2.width / size.w : me2.height / size.h) - 1;
      return capacity > 0 ? capacity : 1;
    }
    getDataTimestamps() {
      const me2 = this;
      let timestamps = me2._cache.data || [];
      let i2, ilen;
      if (timestamps.length) {
        return timestamps;
      }
      const metas = me2.getMatchingVisibleMetas();
      if (me2._normalized && metas.length) {
        return me2._cache.data = metas[0].controller.getAllParsedValues(me2);
      }
      for (i2 = 0, ilen = metas.length; i2 < ilen; ++i2) {
        timestamps = timestamps.concat(metas[i2].controller.getAllParsedValues(me2));
      }
      return me2._cache.data = me2.normalize(timestamps);
    }
    getLabelTimestamps() {
      const me2 = this;
      const timestamps = me2._cache.labels || [];
      let i2, ilen;
      if (timestamps.length) {
        return timestamps;
      }
      const labels = me2.getLabels();
      for (i2 = 0, ilen = labels.length; i2 < ilen; ++i2) {
        timestamps.push(parse(me2, labels[i2]));
      }
      return me2._cache.labels = me2._normalized ? timestamps : me2.normalize(timestamps);
    }
    normalize(values) {
      return _arrayUnique(values.sort(sorter));
    }
  };
  TimeScale.id = "time";
  TimeScale.defaults = {
    bounds: "data",
    adapters: {},
    time: {
      parser: false,
      unit: false,
      round: false,
      isoWeekday: false,
      minUnit: "millisecond",
      displayFormats: {}
    },
    ticks: {
      source: "auto",
      major: {
        enabled: false
      }
    }
  };
  function interpolate2(table, val, reverse) {
    let lo = 0;
    let hi2 = table.length - 1;
    let prevSource, nextSource, prevTarget, nextTarget;
    if (reverse) {
      if (val >= table[lo].pos && val <= table[hi2].pos) {
        ({ lo, hi: hi2 } = _lookupByKey(table, "pos", val));
      }
      ({ pos: prevSource, time: prevTarget } = table[lo]);
      ({ pos: nextSource, time: nextTarget } = table[hi2]);
    } else {
      if (val >= table[lo].time && val <= table[hi2].time) {
        ({ lo, hi: hi2 } = _lookupByKey(table, "time", val));
      }
      ({ time: prevSource, pos: prevTarget } = table[lo]);
      ({ time: nextSource, pos: nextTarget } = table[hi2]);
    }
    const span = nextSource - prevSource;
    return span ? prevTarget + (nextTarget - prevTarget) * (val - prevSource) / span : prevTarget;
  }
  var TimeSeriesScale = class extends TimeScale {
    constructor(props) {
      super(props);
      this._table = [];
      this._minPos = void 0;
      this._tableRange = void 0;
    }
    initOffsets() {
      const me2 = this;
      const timestamps = me2._getTimestampsForTable();
      const table = me2._table = me2.buildLookupTable(timestamps);
      me2._minPos = interpolate2(table, me2.min);
      me2._tableRange = interpolate2(table, me2.max) - me2._minPos;
      super.initOffsets(timestamps);
    }
    buildLookupTable(timestamps) {
      const { min: min2, max: max2 } = this;
      const items = [];
      const table = [];
      let i2, ilen, prev, curr, next;
      for (i2 = 0, ilen = timestamps.length; i2 < ilen; ++i2) {
        curr = timestamps[i2];
        if (curr >= min2 && curr <= max2) {
          items.push(curr);
        }
      }
      if (items.length < 2) {
        return [
          { time: min2, pos: 0 },
          { time: max2, pos: 1 }
        ];
      }
      for (i2 = 0, ilen = items.length; i2 < ilen; ++i2) {
        next = items[i2 + 1];
        prev = items[i2 - 1];
        curr = items[i2];
        if (Math.round((next + prev) / 2) !== curr) {
          table.push({ time: curr, pos: i2 / (ilen - 1) });
        }
      }
      return table;
    }
    _getTimestampsForTable() {
      const me2 = this;
      let timestamps = me2._cache.all || [];
      if (timestamps.length) {
        return timestamps;
      }
      const data = me2.getDataTimestamps();
      const label = me2.getLabelTimestamps();
      if (data.length && label.length) {
        timestamps = me2.normalize(data.concat(label));
      } else {
        timestamps = data.length ? data : label;
      }
      timestamps = me2._cache.all = timestamps;
      return timestamps;
    }
    getDecimalForValue(value) {
      return (interpolate2(this._table, value) - this._minPos) / this._tableRange;
    }
    getValueForPixel(pixel) {
      const me2 = this;
      const offsets = me2._offsets;
      const decimal = me2.getDecimalForPixel(pixel) / offsets.factor - offsets.end;
      return interpolate2(me2._table, decimal * me2._tableRange + me2._minPos, true);
    }
  };
  TimeSeriesScale.id = "timeseries";
  TimeSeriesScale.defaults = TimeScale.defaults;
  var scales = /* @__PURE__ */ Object.freeze({
    __proto__: null,
    CategoryScale,
    LinearScale,
    LogarithmicScale,
    RadialLinearScale,
    TimeScale,
    TimeSeriesScale
  });
  var registerables = [
    controllers,
    elements,
    plugins,
    scales
  ];

  // ../../node_modules/chart.js/auto/auto.esm.js
  Chart.register(...registerables);
  var auto_esm_default = Chart;

  // ../../node_modules/date-fns/esm/_lib/toInteger/index.js
  function toInteger(dirtyNumber) {
    if (dirtyNumber === null || dirtyNumber === true || dirtyNumber === false) {
      return NaN;
    }
    var number = Number(dirtyNumber);
    if (isNaN(number)) {
      return number;
    }
    return number < 0 ? Math.ceil(number) : Math.floor(number);
  }

  // ../../node_modules/date-fns/esm/_lib/requiredArgs/index.js
  function requiredArgs(required, args) {
    if (args.length < required) {
      throw new TypeError(required + " argument" + (required > 1 ? "s" : "") + " required, but only " + args.length + " present");
    }
  }

  // ../../node_modules/date-fns/esm/toDate/index.js
  function toDate(argument) {
    requiredArgs(1, arguments);
    var argStr = Object.prototype.toString.call(argument);
    if (argument instanceof Date || typeof argument === "object" && argStr === "[object Date]") {
      return new Date(argument.getTime());
    } else if (typeof argument === "number" || argStr === "[object Number]") {
      return new Date(argument);
    } else {
      if ((typeof argument === "string" || argStr === "[object String]") && typeof console !== "undefined") {
        console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://git.io/fjule");
        console.warn(new Error().stack);
      }
      return new Date(NaN);
    }
  }

  // ../../node_modules/date-fns/esm/addDays/index.js
  function addDays(dirtyDate, dirtyAmount) {
    requiredArgs(2, arguments);
    var date = toDate(dirtyDate);
    var amount = toInteger(dirtyAmount);
    if (isNaN(amount)) {
      return new Date(NaN);
    }
    if (!amount) {
      return date;
    }
    date.setDate(date.getDate() + amount);
    return date;
  }

  // ../../node_modules/date-fns/esm/addMonths/index.js
  function addMonths(dirtyDate, dirtyAmount) {
    requiredArgs(2, arguments);
    var date = toDate(dirtyDate);
    var amount = toInteger(dirtyAmount);
    if (isNaN(amount)) {
      return new Date(NaN);
    }
    if (!amount) {
      return date;
    }
    var dayOfMonth = date.getDate();
    var endOfDesiredMonth = new Date(date.getTime());
    endOfDesiredMonth.setMonth(date.getMonth() + amount + 1, 0);
    var daysInMonth = endOfDesiredMonth.getDate();
    if (dayOfMonth >= daysInMonth) {
      return endOfDesiredMonth;
    } else {
      date.setFullYear(endOfDesiredMonth.getFullYear(), endOfDesiredMonth.getMonth(), dayOfMonth);
      return date;
    }
  }

  // ../../node_modules/date-fns/esm/addMilliseconds/index.js
  function addMilliseconds(dirtyDate, dirtyAmount) {
    requiredArgs(2, arguments);
    var timestamp = toDate(dirtyDate).getTime();
    var amount = toInteger(dirtyAmount);
    return new Date(timestamp + amount);
  }

  // ../../node_modules/date-fns/esm/addHours/index.js
  var MILLISECONDS_IN_HOUR = 36e5;
  function addHours(dirtyDate, dirtyAmount) {
    requiredArgs(2, arguments);
    var amount = toInteger(dirtyAmount);
    return addMilliseconds(dirtyDate, amount * MILLISECONDS_IN_HOUR);
  }

  // ../../node_modules/date-fns/esm/startOfWeek/index.js
  function startOfWeek(dirtyDate, dirtyOptions) {
    requiredArgs(1, arguments);
    var options = dirtyOptions || {};
    var locale2 = options.locale;
    var localeWeekStartsOn = locale2 && locale2.options && locale2.options.weekStartsOn;
    var defaultWeekStartsOn = localeWeekStartsOn == null ? 0 : toInteger(localeWeekStartsOn);
    var weekStartsOn = options.weekStartsOn == null ? defaultWeekStartsOn : toInteger(options.weekStartsOn);
    if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
      throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");
    }
    var date = toDate(dirtyDate);
    var day = date.getDay();
    var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;
    date.setDate(date.getDate() - diff);
    date.setHours(0, 0, 0, 0);
    return date;
  }

  // ../../node_modules/date-fns/esm/_lib/getTimezoneOffsetInMilliseconds/index.js
  function getTimezoneOffsetInMilliseconds(date) {
    var utcDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds()));
    utcDate.setUTCFullYear(date.getFullYear());
    return date.getTime() - utcDate.getTime();
  }

  // ../../node_modules/date-fns/esm/startOfDay/index.js
  function startOfDay(dirtyDate) {
    requiredArgs(1, arguments);
    var date = toDate(dirtyDate);
    date.setHours(0, 0, 0, 0);
    return date;
  }

  // ../../node_modules/date-fns/esm/differenceInCalendarDays/index.js
  var MILLISECONDS_IN_DAY = 864e5;
  function differenceInCalendarDays(dirtyDateLeft, dirtyDateRight) {
    requiredArgs(2, arguments);
    var startOfDayLeft = startOfDay(dirtyDateLeft);
    var startOfDayRight = startOfDay(dirtyDateRight);
    var timestampLeft = startOfDayLeft.getTime() - getTimezoneOffsetInMilliseconds(startOfDayLeft);
    var timestampRight = startOfDayRight.getTime() - getTimezoneOffsetInMilliseconds(startOfDayRight);
    return Math.round((timestampLeft - timestampRight) / MILLISECONDS_IN_DAY);
  }

  // ../../node_modules/date-fns/esm/addMinutes/index.js
  var MILLISECONDS_IN_MINUTE = 6e4;
  function addMinutes(dirtyDate, dirtyAmount) {
    requiredArgs(2, arguments);
    var amount = toInteger(dirtyAmount);
    return addMilliseconds(dirtyDate, amount * MILLISECONDS_IN_MINUTE);
  }

  // ../../node_modules/date-fns/esm/addQuarters/index.js
  function addQuarters(dirtyDate, dirtyAmount) {
    requiredArgs(2, arguments);
    var amount = toInteger(dirtyAmount);
    var months = amount * 3;
    return addMonths(dirtyDate, months);
  }

  // ../../node_modules/date-fns/esm/addSeconds/index.js
  function addSeconds(dirtyDate, dirtyAmount) {
    requiredArgs(2, arguments);
    var amount = toInteger(dirtyAmount);
    return addMilliseconds(dirtyDate, amount * 1e3);
  }

  // ../../node_modules/date-fns/esm/addWeeks/index.js
  function addWeeks(dirtyDate, dirtyAmount) {
    requiredArgs(2, arguments);
    var amount = toInteger(dirtyAmount);
    var days = amount * 7;
    return addDays(dirtyDate, days);
  }

  // ../../node_modules/date-fns/esm/addYears/index.js
  function addYears(dirtyDate, dirtyAmount) {
    requiredArgs(2, arguments);
    var amount = toInteger(dirtyAmount);
    return addMonths(dirtyDate, amount * 12);
  }

  // ../../node_modules/date-fns/esm/compareAsc/index.js
  function compareAsc(dirtyDateLeft, dirtyDateRight) {
    requiredArgs(2, arguments);
    var dateLeft = toDate(dirtyDateLeft);
    var dateRight = toDate(dirtyDateRight);
    var diff = dateLeft.getTime() - dateRight.getTime();
    if (diff < 0) {
      return -1;
    } else if (diff > 0) {
      return 1;
    } else {
      return diff;
    }
  }

  // ../../node_modules/date-fns/esm/isValid/index.js
  function isValid(dirtyDate) {
    requiredArgs(1, arguments);
    var date = toDate(dirtyDate);
    return !isNaN(date);
  }

  // ../../node_modules/date-fns/esm/differenceInCalendarMonths/index.js
  function differenceInCalendarMonths(dirtyDateLeft, dirtyDateRight) {
    requiredArgs(2, arguments);
    var dateLeft = toDate(dirtyDateLeft);
    var dateRight = toDate(dirtyDateRight);
    var yearDiff = dateLeft.getFullYear() - dateRight.getFullYear();
    var monthDiff = dateLeft.getMonth() - dateRight.getMonth();
    return yearDiff * 12 + monthDiff;
  }

  // ../../node_modules/date-fns/esm/differenceInCalendarYears/index.js
  function differenceInCalendarYears(dirtyDateLeft, dirtyDateRight) {
    requiredArgs(2, arguments);
    var dateLeft = toDate(dirtyDateLeft);
    var dateRight = toDate(dirtyDateRight);
    return dateLeft.getFullYear() - dateRight.getFullYear();
  }

  // ../../node_modules/date-fns/esm/differenceInDays/index.js
  function compareLocalAsc(dateLeft, dateRight) {
    var diff = dateLeft.getFullYear() - dateRight.getFullYear() || dateLeft.getMonth() - dateRight.getMonth() || dateLeft.getDate() - dateRight.getDate() || dateLeft.getHours() - dateRight.getHours() || dateLeft.getMinutes() - dateRight.getMinutes() || dateLeft.getSeconds() - dateRight.getSeconds() || dateLeft.getMilliseconds() - dateRight.getMilliseconds();
    if (diff < 0) {
      return -1;
    } else if (diff > 0) {
      return 1;
    } else {
      return diff;
    }
  }
  function differenceInDays(dirtyDateLeft, dirtyDateRight) {
    requiredArgs(2, arguments);
    var dateLeft = toDate(dirtyDateLeft);
    var dateRight = toDate(dirtyDateRight);
    var sign2 = compareLocalAsc(dateLeft, dateRight);
    var difference = Math.abs(differenceInCalendarDays(dateLeft, dateRight));
    dateLeft.setDate(dateLeft.getDate() - sign2 * difference);
    var isLastDayNotFull = Number(compareLocalAsc(dateLeft, dateRight) === -sign2);
    var result = sign2 * (difference - isLastDayNotFull);
    return result === 0 ? 0 : result;
  }

  // ../../node_modules/date-fns/esm/differenceInMilliseconds/index.js
  function differenceInMilliseconds(dirtyDateLeft, dirtyDateRight) {
    requiredArgs(2, arguments);
    var dateLeft = toDate(dirtyDateLeft);
    var dateRight = toDate(dirtyDateRight);
    return dateLeft.getTime() - dateRight.getTime();
  }

  // ../../node_modules/date-fns/esm/differenceInHours/index.js
  var MILLISECONDS_IN_HOUR2 = 36e5;
  function differenceInHours(dirtyDateLeft, dirtyDateRight) {
    requiredArgs(2, arguments);
    var diff = differenceInMilliseconds(dirtyDateLeft, dirtyDateRight) / MILLISECONDS_IN_HOUR2;
    return diff > 0 ? Math.floor(diff) : Math.ceil(diff);
  }

  // ../../node_modules/date-fns/esm/differenceInMinutes/index.js
  var MILLISECONDS_IN_MINUTE2 = 6e4;
  function differenceInMinutes(dirtyDateLeft, dirtyDateRight) {
    requiredArgs(2, arguments);
    var diff = differenceInMilliseconds(dirtyDateLeft, dirtyDateRight) / MILLISECONDS_IN_MINUTE2;
    return diff > 0 ? Math.floor(diff) : Math.ceil(diff);
  }

  // ../../node_modules/date-fns/esm/endOfDay/index.js
  function endOfDay(dirtyDate) {
    requiredArgs(1, arguments);
    var date = toDate(dirtyDate);
    date.setHours(23, 59, 59, 999);
    return date;
  }

  // ../../node_modules/date-fns/esm/endOfMonth/index.js
  function endOfMonth(dirtyDate) {
    requiredArgs(1, arguments);
    var date = toDate(dirtyDate);
    var month = date.getMonth();
    date.setFullYear(date.getFullYear(), month + 1, 0);
    date.setHours(23, 59, 59, 999);
    return date;
  }

  // ../../node_modules/date-fns/esm/isLastDayOfMonth/index.js
  function isLastDayOfMonth(dirtyDate) {
    requiredArgs(1, arguments);
    var date = toDate(dirtyDate);
    return endOfDay(date).getTime() === endOfMonth(date).getTime();
  }

  // ../../node_modules/date-fns/esm/differenceInMonths/index.js
  function differenceInMonths(dirtyDateLeft, dirtyDateRight) {
    requiredArgs(2, arguments);
    var dateLeft = toDate(dirtyDateLeft);
    var dateRight = toDate(dirtyDateRight);
    var sign2 = compareAsc(dateLeft, dateRight);
    var difference = Math.abs(differenceInCalendarMonths(dateLeft, dateRight));
    var result;
    if (difference < 1) {
      result = 0;
    } else {
      if (dateLeft.getMonth() === 1 && dateLeft.getDate() > 27) {
        dateLeft.setDate(30);
      }
      dateLeft.setMonth(dateLeft.getMonth() - sign2 * difference);
      var isLastMonthNotFull = compareAsc(dateLeft, dateRight) === -sign2;
      if (isLastDayOfMonth(toDate(dirtyDateLeft)) && difference === 1 && compareAsc(dirtyDateLeft, dateRight) === 1) {
        isLastMonthNotFull = false;
      }
      result = sign2 * (difference - Number(isLastMonthNotFull));
    }
    return result === 0 ? 0 : result;
  }

  // ../../node_modules/date-fns/esm/differenceInQuarters/index.js
  function differenceInQuarters(dirtyDateLeft, dirtyDateRight) {
    requiredArgs(2, arguments);
    var diff = differenceInMonths(dirtyDateLeft, dirtyDateRight) / 3;
    return diff > 0 ? Math.floor(diff) : Math.ceil(diff);
  }

  // ../../node_modules/date-fns/esm/differenceInSeconds/index.js
  function differenceInSeconds(dirtyDateLeft, dirtyDateRight) {
    requiredArgs(2, arguments);
    var diff = differenceInMilliseconds(dirtyDateLeft, dirtyDateRight) / 1e3;
    return diff > 0 ? Math.floor(diff) : Math.ceil(diff);
  }

  // ../../node_modules/date-fns/esm/differenceInWeeks/index.js
  function differenceInWeeks(dirtyDateLeft, dirtyDateRight) {
    requiredArgs(2, arguments);
    var diff = differenceInDays(dirtyDateLeft, dirtyDateRight) / 7;
    return diff > 0 ? Math.floor(diff) : Math.ceil(diff);
  }

  // ../../node_modules/date-fns/esm/differenceInYears/index.js
  function differenceInYears(dirtyDateLeft, dirtyDateRight) {
    requiredArgs(2, arguments);
    var dateLeft = toDate(dirtyDateLeft);
    var dateRight = toDate(dirtyDateRight);
    var sign2 = compareAsc(dateLeft, dateRight);
    var difference = Math.abs(differenceInCalendarYears(dateLeft, dateRight));
    dateLeft.setFullYear(1584);
    dateRight.setFullYear(1584);
    var isLastYearNotFull = compareAsc(dateLeft, dateRight) === -sign2;
    var result = sign2 * (difference - Number(isLastYearNotFull));
    return result === 0 ? 0 : result;
  }

  // ../../node_modules/date-fns/esm/startOfMinute/index.js
  function startOfMinute(dirtyDate) {
    requiredArgs(1, arguments);
    var date = toDate(dirtyDate);
    date.setSeconds(0, 0);
    return date;
  }

  // ../../node_modules/date-fns/esm/startOfQuarter/index.js
  function startOfQuarter(dirtyDate) {
    requiredArgs(1, arguments);
    var date = toDate(dirtyDate);
    var currentMonth = date.getMonth();
    var month = currentMonth - currentMonth % 3;
    date.setMonth(month, 1);
    date.setHours(0, 0, 0, 0);
    return date;
  }

  // ../../node_modules/date-fns/esm/startOfMonth/index.js
  function startOfMonth(dirtyDate) {
    requiredArgs(1, arguments);
    var date = toDate(dirtyDate);
    date.setDate(1);
    date.setHours(0, 0, 0, 0);
    return date;
  }

  // ../../node_modules/date-fns/esm/startOfYear/index.js
  function startOfYear(dirtyDate) {
    requiredArgs(1, arguments);
    var cleanDate = toDate(dirtyDate);
    var date = new Date(0);
    date.setFullYear(cleanDate.getFullYear(), 0, 1);
    date.setHours(0, 0, 0, 0);
    return date;
  }

  // ../../node_modules/date-fns/esm/endOfYear/index.js
  function endOfYear(dirtyDate) {
    requiredArgs(1, arguments);
    var date = toDate(dirtyDate);
    var year = date.getFullYear();
    date.setFullYear(year + 1, 0, 0);
    date.setHours(23, 59, 59, 999);
    return date;
  }

  // ../../node_modules/date-fns/esm/endOfHour/index.js
  function endOfHour(dirtyDate) {
    requiredArgs(1, arguments);
    var date = toDate(dirtyDate);
    date.setMinutes(59, 59, 999);
    return date;
  }

  // ../../node_modules/date-fns/esm/endOfWeek/index.js
  function endOfWeek(dirtyDate, dirtyOptions) {
    requiredArgs(1, arguments);
    var options = dirtyOptions || {};
    var locale2 = options.locale;
    var localeWeekStartsOn = locale2 && locale2.options && locale2.options.weekStartsOn;
    var defaultWeekStartsOn = localeWeekStartsOn == null ? 0 : toInteger(localeWeekStartsOn);
    var weekStartsOn = options.weekStartsOn == null ? defaultWeekStartsOn : toInteger(options.weekStartsOn);
    if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
      throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");
    }
    var date = toDate(dirtyDate);
    var day = date.getDay();
    var diff = (day < weekStartsOn ? -7 : 0) + 6 - (day - weekStartsOn);
    date.setDate(date.getDate() + diff);
    date.setHours(23, 59, 59, 999);
    return date;
  }

  // ../../node_modules/date-fns/esm/endOfMinute/index.js
  function endOfMinute(dirtyDate) {
    requiredArgs(1, arguments);
    var date = toDate(dirtyDate);
    date.setSeconds(59, 999);
    return date;
  }

  // ../../node_modules/date-fns/esm/endOfQuarter/index.js
  function endOfQuarter(dirtyDate) {
    requiredArgs(1, arguments);
    var date = toDate(dirtyDate);
    var currentMonth = date.getMonth();
    var month = currentMonth - currentMonth % 3 + 3;
    date.setMonth(month, 0);
    date.setHours(23, 59, 59, 999);
    return date;
  }

  // ../../node_modules/date-fns/esm/endOfSecond/index.js
  function endOfSecond(dirtyDate) {
    requiredArgs(1, arguments);
    var date = toDate(dirtyDate);
    date.setMilliseconds(999);
    return date;
  }

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

  // ../../node_modules/date-fns/esm/locale/_lib/buildFormatLongFn/index.js
  function buildFormatLongFn(args) {
    return function() {
      var options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
      var width = options.width ? String(options.width) : args.defaultWidth;
      var format3 = args.formats[width] || args.formats[args.defaultWidth];
      return format3;
    };
  }

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

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

  // ../../node_modules/date-fns/esm/locale/_lib/buildLocalizeFn/index.js
  function buildLocalizeFn(args) {
    return function(dirtyIndex, dirtyOptions) {
      var options = dirtyOptions || {};
      var context = options.context ? String(options.context) : "standalone";
      var valuesArray;
      if (context === "formatting" && args.formattingValues) {
        var defaultWidth = args.defaultFormattingWidth || args.defaultWidth;
        var width = options.width ? String(options.width) : defaultWidth;
        valuesArray = args.formattingValues[width] || args.formattingValues[defaultWidth];
      } else {
        var _defaultWidth = args.defaultWidth;
        var _width = options.width ? String(options.width) : args.defaultWidth;
        valuesArray = args.values[_width] || args.values[_defaultWidth];
      }
      var index = args.argumentCallback ? args.argumentCallback(dirtyIndex) : dirtyIndex;
      return valuesArray[index];
    };
  }

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

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

  // ../../node_modules/date-fns/esm/locale/_lib/buildMatchFn/index.js
  function buildMatchFn(args) {
    return function(string) {
      var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
      var width = options.width;
      var matchPattern = width && args.matchPatterns[width] || args.matchPatterns[args.defaultMatchWidth];
      var matchResult = string.match(matchPattern);
      if (!matchResult) {
        return null;
      }
      var matchedString = matchResult[0];
      var parsePatterns = width && args.parsePatterns[width] || args.parsePatterns[args.defaultParseWidth];
      var key = Array.isArray(parsePatterns) ? findIndex(parsePatterns, function(pattern) {
        return pattern.test(matchedString);
      }) : findKey(parsePatterns, function(pattern) {
        return pattern.test(matchedString);
      });
      var value;
      value = args.valueCallback ? args.valueCallback(key) : key;
      value = options.valueCallback ? options.valueCallback(value) : value;
      var rest = string.slice(matchedString.length);
      return {
        value,
        rest
      };
    };
  }
  function findKey(object, predicate) {
    for (var key in object) {
      if (object.hasOwnProperty(key) && predicate(object[key])) {
        return key;
      }
    }
    return void 0;
  }
  function findIndex(array, predicate) {
    for (var key = 0; key < array.length; key++) {
      if (predicate(array[key])) {
        return key;
      }
    }
    return void 0;
  }

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

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

  // ../../node_modules/date-fns/esm/subMilliseconds/index.js
  function subMilliseconds(dirtyDate, dirtyAmount) {
    requiredArgs(2, arguments);
    var amount = toInteger(dirtyAmount);
    return addMilliseconds(dirtyDate, -amount);
  }

  // ../../node_modules/date-fns/esm/_lib/addLeadingZeros/index.js
  function addLeadingZeros(number, targetLength) {
    var sign2 = number < 0 ? "-" : "";
    var output = Math.abs(number).toString();
    while (output.length < targetLength) {
      output = "0" + output;
    }
    return sign2 + output;
  }

  // ../../node_modules/date-fns/esm/_lib/format/lightFormatters/index.js
  var formatters2 = {
    y: function(date, token) {
      var signedYear = date.getUTCFullYear();
      var year = signedYear > 0 ? signedYear : 1 - signedYear;
      return addLeadingZeros(token === "yy" ? year % 100 : year, token.length);
    },
    M: function(date, token) {
      var month = date.getUTCMonth();
      return token === "M" ? String(month + 1) : addLeadingZeros(month + 1, 2);
    },
    d: function(date, token) {
      return addLeadingZeros(date.getUTCDate(), token.length);
    },
    a: function(date, token) {
      var dayPeriodEnumValue = date.getUTCHours() / 12 >= 1 ? "pm" : "am";
      switch (token) {
        case "a":
        case "aa":
          return dayPeriodEnumValue.toUpperCase();
        case "aaa":
          return dayPeriodEnumValue;
        case "aaaaa":
          return dayPeriodEnumValue[0];
        case "aaaa":
        default:
          return dayPeriodEnumValue === "am" ? "a.m." : "p.m.";
      }
    },
    h: function(date, token) {
      return addLeadingZeros(date.getUTCHours() % 12 || 12, token.length);
    },
    H: function(date, token) {
      return addLeadingZeros(date.getUTCHours(), token.length);
    },
    m: function(date, token) {
      return addLeadingZeros(date.getUTCMinutes(), token.length);
    },
    s: function(date, token) {
      return addLeadingZeros(date.getUTCSeconds(), token.length);
    },
    S: function(date, token) {
      var numberOfDigits = token.length;
      var milliseconds = date.getUTCMilliseconds();
      var fractionalSeconds = Math.floor(milliseconds * Math.pow(10, numberOfDigits - 3));
      return addLeadingZeros(fractionalSeconds, token.length);
    }
  };
  var lightFormatters_default = formatters2;

  // ../../node_modules/date-fns/esm/_lib/getUTCDayOfYear/index.js
  var MILLISECONDS_IN_DAY2 = 864e5;
  function getUTCDayOfYear(dirtyDate) {
    requiredArgs(1, arguments);
    var date = toDate(dirtyDate);
    var timestamp = date.getTime();
    date.setUTCMonth(0, 1);
    date.setUTCHours(0, 0, 0, 0);
    var startOfYearTimestamp = date.getTime();
    var difference = timestamp - startOfYearTimestamp;
    return Math.floor(difference / MILLISECONDS_IN_DAY2) + 1;
  }

  // ../../node_modules/date-fns/esm/_lib/startOfUTCISOWeek/index.js
  function startOfUTCISOWeek(dirtyDate) {
    requiredArgs(1, arguments);
    var weekStartsOn = 1;
    var date = toDate(dirtyDate);
    var day = date.getUTCDay();
    var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;
    date.setUTCDate(date.getUTCDate() - diff);
    date.setUTCHours(0, 0, 0, 0);
    return date;
  }

  // ../../node_modules/date-fns/esm/_lib/getUTCISOWeekYear/index.js
  function getUTCISOWeekYear(dirtyDate) {
    requiredArgs(1, arguments);
    var date = toDate(dirtyDate);
    var year = date.getUTCFullYear();
    var fourthOfJanuaryOfNextYear = new Date(0);
    fourthOfJanuaryOfNextYear.setUTCFullYear(year + 1, 0, 4);
    fourthOfJanuaryOfNextYear.setUTCHours(0, 0, 0, 0);
    var startOfNextYear = startOfUTCISOWeek(fourthOfJanuaryOfNextYear);
    var fourthOfJanuaryOfThisYear = new Date(0);
    fourthOfJanuaryOfThisYear.setUTCFullYear(year, 0, 4);
    fourthOfJanuaryOfThisYear.setUTCHours(0, 0, 0, 0);
    var startOfThisYear = startOfUTCISOWeek(fourthOfJanuaryOfThisYear);
    if (date.getTime() >= startOfNextYear.getTime()) {
      return year + 1;
    } else if (date.getTime() >= startOfThisYear.getTime()) {
      return year;
    } else {
      return year - 1;
    }
  }

  // ../../node_modules/date-fns/esm/_lib/startOfUTCISOWeekYear/index.js
  function startOfUTCISOWeekYear(dirtyDate) {
    requiredArgs(1, arguments);
    var year = getUTCISOWeekYear(dirtyDate);
    var fourthOfJanuary = new Date(0);
    fourthOfJanuary.setUTCFullYear(year, 0, 4);
    fourthOfJanuary.setUTCHours(0, 0, 0, 0);
    var date = startOfUTCISOWeek(fourthOfJanuary);
    return date;
  }

  // ../../node_modules/date-fns/esm/_lib/getUTCISOWeek/index.js
  var MILLISECONDS_IN_WEEK = 6048e5;
  function getUTCISOWeek(dirtyDate) {
    requiredArgs(1, arguments);
    var date = toDate(dirtyDate);
    var diff = startOfUTCISOWeek(date).getTime() - startOfUTCISOWeekYear(date).getTime();
    return Math.round(diff / MILLISECONDS_IN_WEEK) + 1;
  }

  // ../../node_modules/date-fns/esm/_lib/startOfUTCWeek/index.js
  function startOfUTCWeek(dirtyDate, dirtyOptions) {
    requiredArgs(1, arguments);
    var options = dirtyOptions || {};
    var locale2 = options.locale;
    var localeWeekStartsOn = locale2 && locale2.options && locale2.options.weekStartsOn;
    var defaultWeekStartsOn = localeWeekStartsOn == null ? 0 : toInteger(localeWeekStartsOn);
    var weekStartsOn = options.weekStartsOn == null ? defaultWeekStartsOn : toInteger(options.weekStartsOn);
    if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
      throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");
    }
    var date = toDate(dirtyDate);
    var day = date.getUTCDay();
    var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;
    date.setUTCDate(date.getUTCDate() - diff);
    date.setUTCHours(0, 0, 0, 0);
    return date;
  }

  // ../../node_modules/date-fns/esm/_lib/getUTCWeekYear/index.js
  function getUTCWeekYear(dirtyDate, dirtyOptions) {
    requiredArgs(1, arguments);
    var date = toDate(dirtyDate, dirtyOptions);
    var year = date.getUTCFullYear();
    var options = dirtyOptions || {};
    var locale2 = options.locale;
    var localeFirstWeekContainsDate = locale2 && locale2.options && locale2.options.firstWeekContainsDate;
    var defaultFirstWeekContainsDate = localeFirstWeekContainsDate == null ? 1 : toInteger(localeFirstWeekContainsDate);
    var firstWeekContainsDate = options.firstWeekContainsDate == null ? defaultFirstWeekContainsDate : toInteger(options.firstWeekContainsDate);
    if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) {
      throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");
    }
    var firstWeekOfNextYear = new Date(0);
    firstWeekOfNextYear.setUTCFullYear(year + 1, 0, firstWeekContainsDate);
    firstWeekOfNextYear.setUTCHours(0, 0, 0, 0);
    var startOfNextYear = startOfUTCWeek(firstWeekOfNextYear, dirtyOptions);
    var firstWeekOfThisYear = new Date(0);
    firstWeekOfThisYear.setUTCFullYear(year, 0, firstWeekContainsDate);
    firstWeekOfThisYear.setUTCHours(0, 0, 0, 0);
    var startOfThisYear = startOfUTCWeek(firstWeekOfThisYear, dirtyOptions);
    if (date.getTime() >= startOfNextYear.getTime()) {
      return year + 1;
    } else if (date.getTime() >= startOfThisYear.getTime()) {
      return year;
    } else {
      return year - 1;
    }
  }

  // ../../node_modules/date-fns/esm/_lib/startOfUTCWeekYear/index.js
  function startOfUTCWeekYear(dirtyDate, dirtyOptions) {
    requiredArgs(1, arguments);
    var options = dirtyOptions || {};
    var locale2 = options.locale;
    var localeFirstWeekContainsDate = locale2 && locale2.options && locale2.options.firstWeekContainsDate;
    var defaultFirstWeekContainsDate = localeFirstWeekContainsDate == null ? 1 : toInteger(localeFirstWeekContainsDate);
    var firstWeekContainsDate = options.firstWeekContainsDate == null ? defaultFirstWeekContainsDate : toInteger(options.firstWeekContainsDate);
    var year = getUTCWeekYear(dirtyDate, dirtyOptions);
    var firstWeek = new Date(0);
    firstWeek.setUTCFullYear(year, 0, firstWeekContainsDate);
    firstWeek.setUTCHours(0, 0, 0, 0);
    var date = startOfUTCWeek(firstWeek, dirtyOptions);
    return date;
  }

  // ../../node_modules/date-fns/esm/_lib/getUTCWeek/index.js
  var MILLISECONDS_IN_WEEK2 = 6048e5;
  function getUTCWeek(dirtyDate, options) {
    requiredArgs(1, arguments);
    var date = toDate(dirtyDate);
    var diff = startOfUTCWeek(date, options).getTime() - startOfUTCWeekYear(date, options).getTime();
    return Math.round(diff / MILLISECONDS_IN_WEEK2) + 1;
  }

  // ../../node_modules/date-fns/esm/_lib/format/formatters/index.js
  var dayPeriodEnum = {
    am: "am",
    pm: "pm",
    midnight: "midnight",
    noon: "noon",
    morning: "morning",
    afternoon: "afternoon",
    evening: "evening",
    night: "night"
  };
  var formatters3 = {
    G: function(date, token, localize2) {
      var era = date.getUTCFullYear() > 0 ? 1 : 0;
      switch (token) {
        case "G":
        case "GG":
        case "GGG":
          return localize2.era(era, {
            width: "abbreviated"
          });
        case "GGGGG":
          return localize2.era(era, {
            width: "narrow"
          });
        case "GGGG":
        default:
          return localize2.era(era, {
            width: "wide"
          });
      }
    },
    y: function(date, token, localize2) {
      if (token === "yo") {
        var signedYear = date.getUTCFullYear();
        var year = signedYear > 0 ? signedYear : 1 - signedYear;
        return localize2.ordinalNumber(year, {
          unit: "year"
        });
      }
      return lightFormatters_default.y(date, token);
    },
    Y: function(date, token, localize2, options) {
      var signedWeekYear = getUTCWeekYear(date, options);
      var weekYear = signedWeekYear > 0 ? signedWeekYear : 1 - signedWeekYear;
      if (token === "YY") {
        var twoDigitYear = weekYear % 100;
        return addLeadingZeros(twoDigitYear, 2);
      }
      if (token === "Yo") {
        return localize2.ordinalNumber(weekYear, {
          unit: "year"
        });
      }
      return addLeadingZeros(weekYear, token.length);
    },
    R: function(date, token) {
      var isoWeekYear = getUTCISOWeekYear(date);
      return addLeadingZeros(isoWeekYear, token.length);
    },
    u: function(date, token) {
      var year = date.getUTCFullYear();
      return addLeadingZeros(year, token.length);
    },
    Q: function(date, token, localize2) {
      var quarter = Math.ceil((date.getUTCMonth() + 1) / 3);
      switch (token) {
        case "Q":
          return String(quarter);
        case "QQ":
          return addLeadingZeros(quarter, 2);
        case "Qo":
          return localize2.ordinalNumber(quarter, {
            unit: "quarter"
          });
        case "QQQ":
          return localize2.quarter(quarter, {
            width: "abbreviated",
            context: "formatting"
          });
        case "QQQQQ":
          return localize2.quarter(quarter, {
            width: "narrow",
            context: "formatting"
          });
        case "QQQQ":
        default:
          return localize2.quarter(quarter, {
            width: "wide",
            context: "formatting"
          });
      }
    },
    q: function(date, token, localize2) {
      var quarter = Math.ceil((date.getUTCMonth() + 1) / 3);
      switch (token) {
        case "q":
          return String(quarter);
        case "qq":
          return addLeadingZeros(quarter, 2);
        case "qo":
          return localize2.ordinalNumber(quarter, {
            unit: "quarter"
          });
        case "qqq":
          return localize2.quarter(quarter, {
            width: "abbreviated",
            context: "standalone"
          });
        case "qqqqq":
          return localize2.quarter(quarter, {
            width: "narrow",
            context: "standalone"
          });
        case "qqqq":
        default:
          return localize2.quarter(quarter, {
            width: "wide",
            context: "standalone"
          });
      }
    },
    M: function(date, token, localize2) {
      var month = date.getUTCMonth();
      switch (token) {
        case "M":
        case "MM":
          return lightFormatters_default.M(date, token);
        case "Mo":
          return localize2.ordinalNumber(month + 1, {
            unit: "month"
          });
        case "MMM":
          return localize2.month(month, {
            width: "abbreviated",
            context: "formatting"
          });
        case "MMMMM":
          return localize2.month(month, {
            width: "narrow",
            context: "formatting"
          });
        case "MMMM":
        default:
          return localize2.month(month, {
            width: "wide",
            context: "formatting"
          });
      }
    },
    L: function(date, token, localize2) {
      var month = date.getUTCMonth();
      switch (token) {
        case "L":
          return String(month + 1);
        case "LL":
          return addLeadingZeros(month + 1, 2);
        case "Lo":
          return localize2.ordinalNumber(month + 1, {
            unit: "month"
          });
        case "LLL":
          return localize2.month(month, {
            width: "abbreviated",
            context: "standalone"
          });
        case "LLLLL":
          return localize2.month(month, {
            width: "narrow",
            context: "standalone"
          });
        case "LLLL":
        default:
          return localize2.month(month, {
            width: "wide",
            context: "standalone"
          });
      }
    },
    w: function(date, token, localize2, options) {
      var week = getUTCWeek(date, options);
      if (token === "wo") {
        return localize2.ordinalNumber(week, {
          unit: "week"
        });
      }
      return addLeadingZeros(week, token.length);
    },
    I: function(date, token, localize2) {
      var isoWeek = getUTCISOWeek(date);
      if (token === "Io") {
        return localize2.ordinalNumber(isoWeek, {
          unit: "week"
        });
      }
      return addLeadingZeros(isoWeek, token.length);
    },
    d: function(date, token, localize2) {
      if (token === "do") {
        return localize2.ordinalNumber(date.getUTCDate(), {
          unit: "date"
        });
      }
      return lightFormatters_default.d(date, token);
    },
    D: function(date, token, localize2) {
      var dayOfYear = getUTCDayOfYear(date);
      if (token === "Do") {
        return localize2.ordinalNumber(dayOfYear, {
          unit: "dayOfYear"
        });
      }
      return addLeadingZeros(dayOfYear, token.length);
    },
    E: function(date, token, localize2) {
      var dayOfWeek = date.getUTCDay();
      switch (token) {
        case "E":
        case "EE":
        case "EEE":
          return localize2.day(dayOfWeek, {
            width: "abbreviated",
            context: "formatting"
          });
        case "EEEEE":
          return localize2.day(dayOfWeek, {
            width: "narrow",
            context: "formatting"
          });
        case "EEEEEE":
          return localize2.day(dayOfWeek, {
            width: "short",
            context: "formatting"
          });
        case "EEEE":
        default:
          return localize2.day(dayOfWeek, {
            width: "wide",
            context: "formatting"
          });
      }
    },
    e: function(date, token, localize2, options) {
      var dayOfWeek = date.getUTCDay();
      var localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;
      switch (token) {
        case "e":
          return String(localDayOfWeek);
        case "ee":
          return addLeadingZeros(localDayOfWeek, 2);
        case "eo":
          return localize2.ordinalNumber(localDayOfWeek, {
            unit: "day"
          });
        case "eee":
          return localize2.day(dayOfWeek, {
            width: "abbreviated",
            context: "formatting"
          });
        case "eeeee":
          return localize2.day(dayOfWeek, {
            width: "narrow",
            context: "formatting"
          });
        case "eeeeee":
          return localize2.day(dayOfWeek, {
            width: "short",
            context: "formatting"
          });
        case "eeee":
        default:
          return localize2.day(dayOfWeek, {
            width: "wide",
            context: "formatting"
          });
      }
    },
    c: function(date, token, localize2, options) {
      var dayOfWeek = date.getUTCDay();
      var localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;
      switch (token) {
        case "c":
          return String(localDayOfWeek);
        case "cc":
          return addLeadingZeros(localDayOfWeek, token.length);
        case "co":
          return localize2.ordinalNumber(localDayOfWeek, {
            unit: "day"
          });
        case "ccc":
          return localize2.day(dayOfWeek, {
            width: "abbreviated",
            context: "standalone"
          });
        case "ccccc":
          return localize2.day(dayOfWeek, {
            width: "narrow",
            context: "standalone"
          });
        case "cccccc":
          return localize2.day(dayOfWeek, {
            width: "short",
            context: "standalone"
          });
        case "cccc":
        default:
          return localize2.day(dayOfWeek, {
            width: "wide",
            context: "standalone"
          });
      }
    },
    i: function(date, token, localize2) {
      var dayOfWeek = date.getUTCDay();
      var isoDayOfWeek = dayOfWeek === 0 ? 7 : dayOfWeek;
      switch (token) {
        case "i":
          return String(isoDayOfWeek);
        case "ii":
          return addLeadingZeros(isoDayOfWeek, token.length);
        case "io":
          return localize2.ordinalNumber(isoDayOfWeek, {
            unit: "day"
          });
        case "iii":
          return localize2.day(dayOfWeek, {
            width: "abbreviated",
            context: "formatting"
          });
        case "iiiii":
          return localize2.day(dayOfWeek, {
            width: "narrow",
            context: "formatting"
          });
        case "iiiiii":
          return localize2.day(dayOfWeek, {
            width: "short",
            context: "formatting"
          });
        case "iiii":
        default:
          return localize2.day(dayOfWeek, {
            width: "wide",
            context: "formatting"
          });
      }
    },
    a: function(date, token, localize2) {
      var hours = date.getUTCHours();
      var dayPeriodEnumValue = hours / 12 >= 1 ? "pm" : "am";
      switch (token) {
        case "a":
        case "aa":
          return localize2.dayPeriod(dayPeriodEnumValue, {
            width: "abbreviated",
            context: "formatting"
          });
        case "aaa":
          return localize2.dayPeriod(dayPeriodEnumValue, {
            width: "abbreviated",
            context: "formatting"
          }).toLowerCase();
        case "aaaaa":
          return localize2.dayPeriod(dayPeriodEnumValue, {
            width: "narrow",
            context: "formatting"
          });
        case "aaaa":
        default:
          return localize2.dayPeriod(dayPeriodEnumValue, {
            width: "wide",
            context: "formatting"
          });
      }
    },
    b: function(date, token, localize2) {
      var hours = date.getUTCHours();
      var dayPeriodEnumValue;
      if (hours === 12) {
        dayPeriodEnumValue = dayPeriodEnum.noon;
      } else if (hours === 0) {
        dayPeriodEnumValue = dayPeriodEnum.midnight;
      } else {
        dayPeriodEnumValue = hours / 12 >= 1 ? "pm" : "am";
      }
      switch (token) {
        case "b":
        case "bb":
          return localize2.dayPeriod(dayPeriodEnumValue, {
            width: "abbreviated",
            context: "formatting"
          });
        case "bbb":
          return localize2.dayPeriod(dayPeriodEnumValue, {
            width: "abbreviated",
            context: "formatting"
          }).toLowerCase();
        case "bbbbb":
          return localize2.dayPeriod(dayPeriodEnumValue, {
            width: "narrow",
            context: "formatting"
          });
        case "bbbb":
        default:
          return localize2.dayPeriod(dayPeriodEnumValue, {
            width: "wide",
            context: "formatting"
          });
      }
    },
    B: function(date, token, localize2) {
      var hours = date.getUTCHours();
      var dayPeriodEnumValue;
      if (hours >= 17) {
        dayPeriodEnumValue = dayPeriodEnum.evening;
      } else if (hours >= 12) {
        dayPeriodEnumValue = dayPeriodEnum.afternoon;
      } else if (hours >= 4) {
        dayPeriodEnumValue = dayPeriodEnum.morning;
      } else {
        dayPeriodEnumValue = dayPeriodEnum.night;
      }
      switch (token) {
        case "B":
        case "BB":
        case "BBB":
          return localize2.dayPeriod(dayPeriodEnumValue, {
            width: "abbreviated",
            context: "formatting"
          });
        case "BBBBB":
          return localize2.dayPeriod(dayPeriodEnumValue, {
            width: "narrow",
            context: "formatting"
          });
        case "BBBB":
        default:
          return localize2.dayPeriod(dayPeriodEnumValue, {
            width: "wide",
            context: "formatting"
          });
      }
    },
    h: function(date, token, localize2) {
      if (token === "ho") {
        var hours = date.getUTCHours() % 12;
        if (hours === 0)
          hours = 12;
        return localize2.ordinalNumber(hours, {
          unit: "hour"
        });
      }
      return lightFormatters_default.h(date, token);
    },
    H: function(date, token, localize2) {
      if (token === "Ho") {
        return localize2.ordinalNumber(date.getUTCHours(), {
          unit: "hour"
        });
      }
      return lightFormatters_default.H(date, token);
    },
    K: function(date, token, localize2) {
      var hours = date.getUTCHours() % 12;
      if (token === "Ko") {
        return localize2.ordinalNumber(hours, {
          unit: "hour"
        });
      }
      return addLeadingZeros(hours, token.length);
    },
    k: function(date, token, localize2) {
      var hours = date.getUTCHours();
      if (hours === 0)
        hours = 24;
      if (token === "ko") {
        return localize2.ordinalNumber(hours, {
          unit: "hour"
        });
      }
      return addLeadingZeros(hours, token.length);
    },
    m: function(date, token, localize2) {
      if (token === "mo") {
        return localize2.ordinalNumber(date.getUTCMinutes(), {
          unit: "minute"
        });
      }
      return lightFormatters_default.m(date, token);
    },
    s: function(date, token, localize2) {
      if (token === "so") {
        return localize2.ordinalNumber(date.getUTCSeconds(), {
          unit: "second"
        });
      }
      return lightFormatters_default.s(date, token);
    },
    S: function(date, token) {
      return lightFormatters_default.S(date, token);
    },
    X: function(date, token, _localize, options) {
      var originalDate = options._originalDate || date;
      var timezoneOffset = originalDate.getTimezoneOffset();
      if (timezoneOffset === 0) {
        return "Z";
      }
      switch (token) {
        case "X":
          return formatTimezoneWithOptionalMinutes(timezoneOffset);
        case "XXXX":
        case "XX":
          return formatTimezone(timezoneOffset);
        case "XXXXX":
        case "XXX":
        default:
          return formatTimezone(timezoneOffset, ":");
      }
    },
    x: function(date, token, _localize, options) {
      var originalDate = options._originalDate || date;
      var timezoneOffset = originalDate.getTimezoneOffset();
      switch (token) {
        case "x":
          return formatTimezoneWithOptionalMinutes(timezoneOffset);
        case "xxxx":
        case "xx":
          return formatTimezone(timezoneOffset);
        case "xxxxx":
        case "xxx":
        default:
          return formatTimezone(timezoneOffset, ":");
      }
    },
    O: function(date, token, _localize, options) {
      var originalDate = options._originalDate || date;
      var timezoneOffset = originalDate.getTimezoneOffset();
      switch (token) {
        case "O":
        case "OO":
        case "OOO":
          return "GMT" + formatTimezoneShort(timezoneOffset, ":");
        case "OOOO":
        default:
          return "GMT" + formatTimezone(timezoneOffset, ":");
      }
    },
    z: function(date, token, _localize, options) {
      var originalDate = options._originalDate || date;
      var timezoneOffset = originalDate.getTimezoneOffset();
      switch (token) {
        case "z":
        case "zz":
        case "zzz":
          return "GMT" + formatTimezoneShort(timezoneOffset, ":");
        case "zzzz":
        default:
          return "GMT" + formatTimezone(timezoneOffset, ":");
      }
    },
    t: function(date, token, _localize, options) {
      var originalDate = options._originalDate || date;
      var timestamp = Math.floor(originalDate.getTime() / 1e3);
      return addLeadingZeros(timestamp, token.length);
    },
    T: function(date, token, _localize, options) {
      var originalDate = options._originalDate || date;
      var timestamp = originalDate.getTime();
      return addLeadingZeros(timestamp, token.length);
    }
  };
  function formatTimezoneShort(offset2, dirtyDelimiter) {
    var sign2 = offset2 > 0 ? "-" : "+";
    var absOffset = Math.abs(offset2);
    var hours = Math.floor(absOffset / 60);
    var minutes = absOffset % 60;
    if (minutes === 0) {
      return sign2 + String(hours);
    }
    var delimiter = dirtyDelimiter || "";
    return sign2 + String(hours) + delimiter + addLeadingZeros(minutes, 2);
  }
  function formatTimezoneWithOptionalMinutes(offset2, dirtyDelimiter) {
    if (offset2 % 60 === 0) {
      var sign2 = offset2 > 0 ? "-" : "+";
      return sign2 + addLeadingZeros(Math.abs(offset2) / 60, 2);
    }
    return formatTimezone(offset2, dirtyDelimiter);
  }
  function formatTimezone(offset2, dirtyDelimiter) {
    var delimiter = dirtyDelimiter || "";
    var sign2 = offset2 > 0 ? "-" : "+";
    var absOffset = Math.abs(offset2);
    var hours = addLeadingZeros(Math.floor(absOffset / 60), 2);
    var minutes = addLeadingZeros(absOffset % 60, 2);
    return sign2 + hours + delimiter + minutes;
  }
  var formatters_default = formatters3;

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

  // ../../node_modules/date-fns/esm/_lib/protectedTokens/index.js
  var protectedDayOfYearTokens = ["D", "DD"];
  var protectedWeekYearTokens = ["YY", "YYYY"];
  function isProtectedDayOfYearToken(token) {
    return protectedDayOfYearTokens.indexOf(token) !== -1;
  }
  function isProtectedWeekYearToken(token) {
    return protectedWeekYearTokens.indexOf(token) !== -1;
  }
  function throwProtectedError(token, format3, input) {
    if (token === "YYYY") {
      throw new RangeError("Use `yyyy` instead of `YYYY` (in `".concat(format3, "`) for formatting years to the input `").concat(input, "`; see: https://git.io/fxCyr"));
    } else if (token === "YY") {
      throw new RangeError("Use `yy` instead of `YY` (in `".concat(format3, "`) for formatting years to the input `").concat(input, "`; see: https://git.io/fxCyr"));
    } else if (token === "D") {
      throw new RangeError("Use `d` instead of `D` (in `".concat(format3, "`) for formatting days of the month to the input `").concat(input, "`; see: https://git.io/fxCyr"));
    } else if (token === "DD") {
      throw new RangeError("Use `dd` instead of `DD` (in `".concat(format3, "`) for formatting days of the month to the input `").concat(input, "`; see: https://git.io/fxCyr"));
    }
  }

  // ../../node_modules/date-fns/esm/format/index.js
  var formattingTokensRegExp = /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g;
  var longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g;
  var escapedStringRegExp = /^'([^]*?)'?$/;
  var doubleQuoteRegExp = /''/g;
  var unescapedLatinCharacterRegExp = /[a-zA-Z]/;
  function format2(dirtyDate, dirtyFormatStr, dirtyOptions) {
    requiredArgs(2, arguments);
    var formatStr = String(dirtyFormatStr);
    var options = dirtyOptions || {};
    var locale2 = options.locale || en_US_default;
    var localeFirstWeekContainsDate = locale2.options && locale2.options.firstWeekContainsDate;
    var defaultFirstWeekContainsDate = localeFirstWeekContainsDate == null ? 1 : toInteger(localeFirstWeekContainsDate);
    var firstWeekContainsDate = options.firstWeekContainsDate == null ? defaultFirstWeekContainsDate : toInteger(options.firstWeekContainsDate);
    if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) {
      throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");
    }
    var localeWeekStartsOn = locale2.options && locale2.options.weekStartsOn;
    var defaultWeekStartsOn = localeWeekStartsOn == null ? 0 : toInteger(localeWeekStartsOn);
    var weekStartsOn = options.weekStartsOn == null ? defaultWeekStartsOn : toInteger(options.weekStartsOn);
    if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
      throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");
    }
    if (!locale2.localize) {
      throw new RangeError("locale must contain localize property");
    }
    if (!locale2.formatLong) {
      throw new RangeError("locale must contain formatLong property");
    }
    var originalDate = toDate(dirtyDate);
    if (!isValid(originalDate)) {
      throw new RangeError("Invalid time value");
    }
    var timezoneOffset = getTimezoneOffsetInMilliseconds(originalDate);
    var utcDate = subMilliseconds(originalDate, timezoneOffset);
    var formatterOptions = {
      firstWeekContainsDate,
      weekStartsOn,
      locale: locale2,
      _originalDate: originalDate
    };
    var result = formatStr.match(longFormattingTokensRegExp).map(function(substring) {
      var firstCharacter = substring[0];
      if (firstCharacter === "p" || firstCharacter === "P") {
        var longFormatter = longFormatters_default[firstCharacter];
        return longFormatter(substring, locale2.formatLong, formatterOptions);
      }
      return substring;
    }).join("").match(formattingTokensRegExp).map(function(substring) {
      if (substring === "''") {
        return "'";
      }
      var firstCharacter = substring[0];
      if (firstCharacter === "'") {
        return cleanEscapedString(substring);
      }
      var formatter = formatters_default[firstCharacter];
      if (formatter) {
        if (!options.useAdditionalWeekYearTokens && isProtectedWeekYearToken(substring)) {
          throwProtectedError(substring, dirtyFormatStr, dirtyDate);
        }
        if (!options.useAdditionalDayOfYearTokens && isProtectedDayOfYearToken(substring)) {
          throwProtectedError(substring, dirtyFormatStr, dirtyDate);
        }
        return formatter(utcDate, substring, locale2.localize, formatterOptions);
      }
      if (firstCharacter.match(unescapedLatinCharacterRegExp)) {
        throw new RangeError("Format string contains an unescaped latin alphabet character `" + firstCharacter + "`");
      }
      return substring;
    }).join("");
    return result;
  }
  function cleanEscapedString(input) {
    return input.match(escapedStringRegExp)[1].replace(doubleQuoteRegExp, "'");
  }

  // ../../node_modules/date-fns/esm/_lib/assign/index.js
  function assign(target, dirtyObject) {
    if (target == null) {
      throw new TypeError("assign requires that input parameter not be null or undefined");
    }
    dirtyObject = dirtyObject || {};
    for (var property in dirtyObject) {
      if (Object.prototype.hasOwnProperty.call(dirtyObject, property)) {
        target[property] = dirtyObject[property];
      }
    }
    return target;
  }

  // ../../node_modules/date-fns/esm/_lib/setUTCDay/index.js
  function setUTCDay(dirtyDate, dirtyDay, dirtyOptions) {
    requiredArgs(2, arguments);
    var options = dirtyOptions || {};
    var locale2 = options.locale;
    var localeWeekStartsOn = locale2 && locale2.options && locale2.options.weekStartsOn;
    var defaultWeekStartsOn = localeWeekStartsOn == null ? 0 : toInteger(localeWeekStartsOn);
    var weekStartsOn = options.weekStartsOn == null ? defaultWeekStartsOn : toInteger(options.weekStartsOn);
    if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
      throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");
    }
    var date = toDate(dirtyDate);
    var day = toInteger(dirtyDay);
    var currentDay = date.getUTCDay();
    var remainder = day % 7;
    var dayIndex = (remainder + 7) % 7;
    var diff = (dayIndex < weekStartsOn ? 7 : 0) + day - currentDay;
    date.setUTCDate(date.getUTCDate() + diff);
    return date;
  }

  // ../../node_modules/date-fns/esm/_lib/setUTCISODay/index.js
  function setUTCISODay(dirtyDate, dirtyDay) {
    requiredArgs(2, arguments);
    var day = toInteger(dirtyDay);
    if (day % 7 === 0) {
      day = day - 7;
    }
    var weekStartsOn = 1;
    var date = toDate(dirtyDate);
    var currentDay = date.getUTCDay();
    var remainder = day % 7;
    var dayIndex = (remainder + 7) % 7;
    var diff = (dayIndex < weekStartsOn ? 7 : 0) + day - currentDay;
    date.setUTCDate(date.getUTCDate() + diff);
    return date;
  }

  // ../../node_modules/date-fns/esm/_lib/setUTCISOWeek/index.js
  function setUTCISOWeek(dirtyDate, dirtyISOWeek) {
    requiredArgs(2, arguments);
    var date = toDate(dirtyDate);
    var isoWeek = toInteger(dirtyISOWeek);
    var diff = getUTCISOWeek(date) - isoWeek;
    date.setUTCDate(date.getUTCDate() - diff * 7);
    return date;
  }

  // ../../node_modules/date-fns/esm/_lib/setUTCWeek/index.js
  function setUTCWeek(dirtyDate, dirtyWeek, options) {
    requiredArgs(2, arguments);
    var date = toDate(dirtyDate);
    var week = toInteger(dirtyWeek);
    var diff = getUTCWeek(date, options) - week;
    date.setUTCDate(date.getUTCDate() - diff * 7);
    return date;
  }

  // ../../node_modules/date-fns/esm/parse/_lib/parsers/index.js
  var MILLISECONDS_IN_HOUR3 = 36e5;
  var MILLISECONDS_IN_MINUTE3 = 6e4;
  var MILLISECONDS_IN_SECOND = 1e3;
  var numericPatterns = {
    month: /^(1[0-2]|0?\d)/,
    date: /^(3[0-1]|[0-2]?\d)/,
    dayOfYear: /^(36[0-6]|3[0-5]\d|[0-2]?\d?\d)/,
    week: /^(5[0-3]|[0-4]?\d)/,
    hour23h: /^(2[0-3]|[0-1]?\d)/,
    hour24h: /^(2[0-4]|[0-1]?\d)/,
    hour11h: /^(1[0-1]|0?\d)/,
    hour12h: /^(1[0-2]|0?\d)/,
    minute: /^[0-5]?\d/,
    second: /^[0-5]?\d/,
    singleDigit: /^\d/,
    twoDigits: /^\d{1,2}/,
    threeDigits: /^\d{1,3}/,
    fourDigits: /^\d{1,4}/,
    anyDigitsSigned: /^-?\d+/,
    singleDigitSigned: /^-?\d/,
    twoDigitsSigned: /^-?\d{1,2}/,
    threeDigitsSigned: /^-?\d{1,3}/,
    fourDigitsSigned: /^-?\d{1,4}/
  };
  var timezonePatterns = {
    basicOptionalMinutes: /^([+-])(\d{2})(\d{2})?|Z/,
    basic: /^([+-])(\d{2})(\d{2})|Z/,
    basicOptionalSeconds: /^([+-])(\d{2})(\d{2})((\d{2}))?|Z/,
    extended: /^([+-])(\d{2}):(\d{2})|Z/,
    extendedOptionalSeconds: /^([+-])(\d{2}):(\d{2})(:(\d{2}))?|Z/
  };
  function parseNumericPattern(pattern, string, valueCallback) {
    var matchResult = string.match(pattern);
    if (!matchResult) {
      return null;
    }
    var value = parseInt(matchResult[0], 10);
    return {
      value: valueCallback ? valueCallback(value) : value,
      rest: string.slice(matchResult[0].length)
    };
  }
  function parseTimezonePattern(pattern, string) {
    var matchResult = string.match(pattern);
    if (!matchResult) {
      return null;
    }
    if (matchResult[0] === "Z") {
      return {
        value: 0,
        rest: string.slice(1)
      };
    }
    var sign2 = matchResult[1] === "+" ? 1 : -1;
    var hours = matchResult[2] ? parseInt(matchResult[2], 10) : 0;
    var minutes = matchResult[3] ? parseInt(matchResult[3], 10) : 0;
    var seconds = matchResult[5] ? parseInt(matchResult[5], 10) : 0;
    return {
      value: sign2 * (hours * MILLISECONDS_IN_HOUR3 + minutes * MILLISECONDS_IN_MINUTE3 + seconds * MILLISECONDS_IN_SECOND),
      rest: string.slice(matchResult[0].length)
    };
  }
  function parseAnyDigitsSigned(string, valueCallback) {
    return parseNumericPattern(numericPatterns.anyDigitsSigned, string, valueCallback);
  }
  function parseNDigits(n2, string, valueCallback) {
    switch (n2) {
      case 1:
        return parseNumericPattern(numericPatterns.singleDigit, string, valueCallback);
      case 2:
        return parseNumericPattern(numericPatterns.twoDigits, string, valueCallback);
      case 3:
        return parseNumericPattern(numericPatterns.threeDigits, string, valueCallback);
      case 4:
        return parseNumericPattern(numericPatterns.fourDigits, string, valueCallback);
      default:
        return parseNumericPattern(new RegExp("^\\d{1," + n2 + "}"), string, valueCallback);
    }
  }
  function parseNDigitsSigned(n2, string, valueCallback) {
    switch (n2) {
      case 1:
        return parseNumericPattern(numericPatterns.singleDigitSigned, string, valueCallback);
      case 2:
        return parseNumericPattern(numericPatterns.twoDigitsSigned, string, valueCallback);
      case 3:
        return parseNumericPattern(numericPatterns.threeDigitsSigned, string, valueCallback);
      case 4:
        return parseNumericPattern(numericPatterns.fourDigitsSigned, string, valueCallback);
      default:
        return parseNumericPattern(new RegExp("^-?\\d{1," + n2 + "}"), string, valueCallback);
    }
  }
  function dayPeriodEnumToHours(enumValue) {
    switch (enumValue) {
      case "morning":
        return 4;
      case "evening":
        return 17;
      case "pm":
      case "noon":
      case "afternoon":
        return 12;
      case "am":
      case "midnight":
      case "night":
      default:
        return 0;
    }
  }
  function normalizeTwoDigitYear(twoDigitYear, currentYear) {
    var isCommonEra = currentYear > 0;
    var absCurrentYear = isCommonEra ? currentYear : 1 - currentYear;
    var result;
    if (absCurrentYear <= 50) {
      result = twoDigitYear || 100;
    } else {
      var rangeEnd = absCurrentYear + 50;
      var rangeEndCentury = Math.floor(rangeEnd / 100) * 100;
      var isPreviousCentury = twoDigitYear >= rangeEnd % 100;
      result = twoDigitYear + rangeEndCentury - (isPreviousCentury ? 100 : 0);
    }
    return isCommonEra ? result : 1 - result;
  }
  var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  var DAYS_IN_MONTH_LEAP_YEAR = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  function isLeapYearIndex(year) {
    return year % 400 === 0 || year % 4 === 0 && year % 100 !== 0;
  }
  var parsers = {
    G: {
      priority: 140,
      parse: function(string, token, match2, _options) {
        switch (token) {
          case "G":
          case "GG":
          case "GGG":
            return match2.era(string, {
              width: "abbreviated"
            }) || match2.era(string, {
              width: "narrow"
            });
          case "GGGGG":
            return match2.era(string, {
              width: "narrow"
            });
          case "GGGG":
          default:
            return match2.era(string, {
              width: "wide"
            }) || match2.era(string, {
              width: "abbreviated"
            }) || match2.era(string, {
              width: "narrow"
            });
        }
      },
      set: function(date, flags, value, _options) {
        flags.era = value;
        date.setUTCFullYear(value, 0, 1);
        date.setUTCHours(0, 0, 0, 0);
        return date;
      },
      incompatibleTokens: ["R", "u", "t", "T"]
    },
    y: {
      priority: 130,
      parse: function(string, token, match2, _options) {
        var valueCallback = function(year) {
          return {
            year,
            isTwoDigitYear: token === "yy"
          };
        };
        switch (token) {
          case "y":
            return parseNDigits(4, string, valueCallback);
          case "yo":
            return match2.ordinalNumber(string, {
              unit: "year",
              valueCallback
            });
          default:
            return parseNDigits(token.length, string, valueCallback);
        }
      },
      validate: function(_date, value, _options) {
        return value.isTwoDigitYear || value.year > 0;
      },
      set: function(date, flags, value, _options) {
        var currentYear = date.getUTCFullYear();
        if (value.isTwoDigitYear) {
          var normalizedTwoDigitYear = normalizeTwoDigitYear(value.year, currentYear);
          date.setUTCFullYear(normalizedTwoDigitYear, 0, 1);
          date.setUTCHours(0, 0, 0, 0);
          return date;
        }
        var year = !("era" in flags) || flags.era === 1 ? value.year : 1 - value.year;
        date.setUTCFullYear(year, 0, 1);
        date.setUTCHours(0, 0, 0, 0);
        return date;
      },
      incompatibleTokens: ["Y", "R", "u", "w", "I", "i", "e", "c", "t", "T"]
    },
    Y: {
      priority: 130,
      parse: function(string, token, match2, _options) {
        var valueCallback = function(year) {
          return {
            year,
            isTwoDigitYear: token === "YY"
          };
        };
        switch (token) {
          case "Y":
            return parseNDigits(4, string, valueCallback);
          case "Yo":
            return match2.ordinalNumber(string, {
              unit: "year",
              valueCallback
            });
          default:
            return parseNDigits(token.length, string, valueCallback);
        }
      },
      validate: function(_date, value, _options) {
        return value.isTwoDigitYear || value.year > 0;
      },
      set: function(date, flags, value, options) {
        var currentYear = getUTCWeekYear(date, options);
        if (value.isTwoDigitYear) {
          var normalizedTwoDigitYear = normalizeTwoDigitYear(value.year, currentYear);
          date.setUTCFullYear(normalizedTwoDigitYear, 0, options.firstWeekContainsDate);
          date.setUTCHours(0, 0, 0, 0);
          return startOfUTCWeek(date, options);
        }
        var year = !("era" in flags) || flags.era === 1 ? value.year : 1 - value.year;
        date.setUTCFullYear(year, 0, options.firstWeekContainsDate);
        date.setUTCHours(0, 0, 0, 0);
        return startOfUTCWeek(date, options);
      },
      incompatibleTokens: ["y", "R", "u", "Q", "q", "M", "L", "I", "d", "D", "i", "t", "T"]
    },
    R: {
      priority: 130,
      parse: function(string, token, _match, _options) {
        if (token === "R") {
          return parseNDigitsSigned(4, string);
        }
        return parseNDigitsSigned(token.length, string);
      },
      set: function(_date, _flags, value, _options) {
        var firstWeekOfYear = new Date(0);
        firstWeekOfYear.setUTCFullYear(value, 0, 4);
        firstWeekOfYear.setUTCHours(0, 0, 0, 0);
        return startOfUTCISOWeek(firstWeekOfYear);
      },
      incompatibleTokens: ["G", "y", "Y", "u", "Q", "q", "M", "L", "w", "d", "D", "e", "c", "t", "T"]
    },
    u: {
      priority: 130,
      parse: function(string, token, _match, _options) {
        if (token === "u") {
          return parseNDigitsSigned(4, string);
        }
        return parseNDigitsSigned(token.length, string);
      },
      set: function(date, _flags, value, _options) {
        date.setUTCFullYear(value, 0, 1);
        date.setUTCHours(0, 0, 0, 0);
        return date;
      },
      incompatibleTokens: ["G", "y", "Y", "R", "w", "I", "i", "e", "c", "t", "T"]
    },
    Q: {
      priority: 120,
      parse: function(string, token, match2, _options) {
        switch (token) {
          case "Q":
          case "QQ":
            return parseNDigits(token.length, string);
          case "Qo":
            return match2.ordinalNumber(string, {
              unit: "quarter"
            });
          case "QQQ":
            return match2.quarter(string, {
              width: "abbreviated",
              context: "formatting"
            }) || match2.quarter(string, {
              width: "narrow",
              context: "formatting"
            });
          case "QQQQQ":
            return match2.quarter(string, {
              width: "narrow",
              context: "formatting"
            });
          case "QQQQ":
          default:
            return match2.quarter(string, {
              width: "wide",
              context: "formatting"
            }) || match2.quarter(string, {
              width: "abbreviated",
              context: "formatting"
            }) || match2.quarter(string, {
              width: "narrow",
              context: "formatting"
            });
        }
      },
      validate: function(_date, value, _options) {
        return value >= 1 && value <= 4;
      },
      set: function(date, _flags, value, _options) {
        date.setUTCMonth((value - 1) * 3, 1);
        date.setUTCHours(0, 0, 0, 0);
        return date;
      },
      incompatibleTokens: ["Y", "R", "q", "M", "L", "w", "I", "d", "D", "i", "e", "c", "t", "T"]
    },
    q: {
      priority: 120,
      parse: function(string, token, match2, _options) {
        switch (token) {
          case "q":
          case "qq":
            return parseNDigits(token.length, string);
          case "qo":
            return match2.ordinalNumber(string, {
              unit: "quarter"
            });
          case "qqq":
            return match2.quarter(string, {
              width: "abbreviated",
              context: "standalone"
            }) || match2.quarter(string, {
              width: "narrow",
              context: "standalone"
            });
          case "qqqqq":
            return match2.quarter(string, {
              width: "narrow",
              context: "standalone"
            });
          case "qqqq":
          default:
            return match2.quarter(string, {
              width: "wide",
              context: "standalone"
            }) || match2.quarter(string, {
              width: "abbreviated",
              context: "standalone"
            }) || match2.quarter(string, {
              width: "narrow",
              context: "standalone"
            });
        }
      },
      validate: function(_date, value, _options) {
        return value >= 1 && value <= 4;
      },
      set: function(date, _flags, value, _options) {
        date.setUTCMonth((value - 1) * 3, 1);
        date.setUTCHours(0, 0, 0, 0);
        return date;
      },
      incompatibleTokens: ["Y", "R", "Q", "M", "L", "w", "I", "d", "D", "i", "e", "c", "t", "T"]
    },
    M: {
      priority: 110,
      parse: function(string, token, match2, _options) {
        var valueCallback = function(value) {
          return value - 1;
        };
        switch (token) {
          case "M":
            return parseNumericPattern(numericPatterns.month, string, valueCallback);
          case "MM":
            return parseNDigits(2, string, valueCallback);
          case "Mo":
            return match2.ordinalNumber(string, {
              unit: "month",
              valueCallback
            });
          case "MMM":
            return match2.month(string, {
              width: "abbreviated",
              context: "formatting"
            }) || match2.month(string, {
              width: "narrow",
              context: "formatting"
            });
          case "MMMMM":
            return match2.month(string, {
              width: "narrow",
              context: "formatting"
            });
          case "MMMM":
          default:
            return match2.month(string, {
              width: "wide",
              context: "formatting"
            }) || match2.month(string, {
              width: "abbreviated",
              context: "formatting"
            }) || match2.month(string, {
              width: "narrow",
              context: "formatting"
            });
        }
      },
      validate: function(_date, value, _options) {
        return value >= 0 && value <= 11;
      },
      set: function(date, _flags, value, _options) {
        date.setUTCMonth(value, 1);
        date.setUTCHours(0, 0, 0, 0);
        return date;
      },
      incompatibleTokens: ["Y", "R", "q", "Q", "L", "w", "I", "D", "i", "e", "c", "t", "T"]
    },
    L: {
      priority: 110,
      parse: function(string, token, match2, _options) {
        var valueCallback = function(value) {
          return value - 1;
        };
        switch (token) {
          case "L":
            return parseNumericPattern(numericPatterns.month, string, valueCallback);
          case "LL":
            return parseNDigits(2, string, valueCallback);
          case "Lo":
            return match2.ordinalNumber(string, {
              unit: "month",
              valueCallback
            });
          case "LLL":
            return match2.month(string, {
              width: "abbreviated",
              context: "standalone"
            }) || match2.month(string, {
              width: "narrow",
              context: "standalone"
            });
          case "LLLLL":
            return match2.month(string, {
              width: "narrow",
              context: "standalone"
            });
          case "LLLL":
          default:
            return match2.month(string, {
              width: "wide",
              context: "standalone"
            }) || match2.month(string, {
              width: "abbreviated",
              context: "standalone"
            }) || match2.month(string, {
              width: "narrow",
              context: "standalone"
            });
        }
      },
      validate: function(_date, value, _options) {
        return value >= 0 && value <= 11;
      },
      set: function(date, _flags, value, _options) {
        date.setUTCMonth(value, 1);
        date.setUTCHours(0, 0, 0, 0);
        return date;
      },
      incompatibleTokens: ["Y", "R", "q", "Q", "M", "w", "I", "D", "i", "e", "c", "t", "T"]
    },
    w: {
      priority: 100,
      parse: function(string, token, match2, _options) {
        switch (token) {
          case "w":
            return parseNumericPattern(numericPatterns.week, string);
          case "wo":
            return match2.ordinalNumber(string, {
              unit: "week"
            });
          default:
            return parseNDigits(token.length, string);
        }
      },
      validate: function(_date, value, _options) {
        return value >= 1 && value <= 53;
      },
      set: function(date, _flags, value, options) {
        return startOfUTCWeek(setUTCWeek(date, value, options), options);
      },
      incompatibleTokens: ["y", "R", "u", "q", "Q", "M", "L", "I", "d", "D", "i", "t", "T"]
    },
    I: {
      priority: 100,
      parse: function(string, token, match2, _options) {
        switch (token) {
          case "I":
            return parseNumericPattern(numericPatterns.week, string);
          case "Io":
            return match2.ordinalNumber(string, {
              unit: "week"
            });
          default:
            return parseNDigits(token.length, string);
        }
      },
      validate: function(_date, value, _options) {
        return value >= 1 && value <= 53;
      },
      set: function(date, _flags, value, options) {
        return startOfUTCISOWeek(setUTCISOWeek(date, value, options), options);
      },
      incompatibleTokens: ["y", "Y", "u", "q", "Q", "M", "L", "w", "d", "D", "e", "c", "t", "T"]
    },
    d: {
      priority: 90,
      subPriority: 1,
      parse: function(string, token, match2, _options) {
        switch (token) {
          case "d":
            return parseNumericPattern(numericPatterns.date, string);
          case "do":
            return match2.ordinalNumber(string, {
              unit: "date"
            });
          default:
            return parseNDigits(token.length, string);
        }
      },
      validate: function(date, value, _options) {
        var year = date.getUTCFullYear();
        var isLeapYear = isLeapYearIndex(year);
        var month = date.getUTCMonth();
        if (isLeapYear) {
          return value >= 1 && value <= DAYS_IN_MONTH_LEAP_YEAR[month];
        } else {
          return value >= 1 && value <= DAYS_IN_MONTH[month];
        }
      },
      set: function(date, _flags, value, _options) {
        date.setUTCDate(value);
        date.setUTCHours(0, 0, 0, 0);
        return date;
      },
      incompatibleTokens: ["Y", "R", "q", "Q", "w", "I", "D", "i", "e", "c", "t", "T"]
    },
    D: {
      priority: 90,
      subPriority: 1,
      parse: function(string, token, match2, _options) {
        switch (token) {
          case "D":
          case "DD":
            return parseNumericPattern(numericPatterns.dayOfYear, string);
          case "Do":
            return match2.ordinalNumber(string, {
              unit: "date"
            });
          default:
            return parseNDigits(token.length, string);
        }
      },
      validate: function(date, value, _options) {
        var year = date.getUTCFullYear();
        var isLeapYear = isLeapYearIndex(year);
        if (isLeapYear) {
          return value >= 1 && value <= 366;
        } else {
          return value >= 1 && value <= 365;
        }
      },
      set: function(date, _flags, value, _options) {
        date.setUTCMonth(0, value);
        date.setUTCHours(0, 0, 0, 0);
        return date;
      },
      incompatibleTokens: ["Y", "R", "q", "Q", "M", "L", "w", "I", "d", "E", "i", "e", "c", "t", "T"]
    },
    E: {
      priority: 90,
      parse: function(string, token, match2, _options) {
        switch (token) {
          case "E":
          case "EE":
          case "EEE":
            return match2.day(string, {
              width: "abbreviated",
              context: "formatting"
            }) || match2.day(string, {
              width: "short",
              context: "formatting"
            }) || match2.day(string, {
              width: "narrow",
              context: "formatting"
            });
          case "EEEEE":
            return match2.day(string, {
              width: "narrow",
              context: "formatting"
            });
          case "EEEEEE":
            return match2.day(string, {
              width: "short",
              context: "formatting"
            }) || match2.day(string, {
              width: "narrow",
              context: "formatting"
            });
          case "EEEE":
          default:
            return match2.day(string, {
              width: "wide",
              context: "formatting"
            }) || match2.day(string, {
              width: "abbreviated",
              context: "formatting"
            }) || match2.day(string, {
              width: "short",
              context: "formatting"
            }) || match2.day(string, {
              width: "narrow",
              context: "formatting"
            });
        }
      },
      validate: function(_date, value, _options) {
        return value >= 0 && value <= 6;
      },
      set: function(date, _flags, value, options) {
        date = setUTCDay(date, value, options);
        date.setUTCHours(0, 0, 0, 0);
        return date;
      },
      incompatibleTokens: ["D", "i", "e", "c", "t", "T"]
    },
    e: {
      priority: 90,
      parse: function(string, token, match2, options) {
        var valueCallback = function(value) {
          var wholeWeekDays = Math.floor((value - 1) / 7) * 7;
          return (value + options.weekStartsOn + 6) % 7 + wholeWeekDays;
        };
        switch (token) {
          case "e":
          case "ee":
            return parseNDigits(token.length, string, valueCallback);
          case "eo":
            return match2.ordinalNumber(string, {
              unit: "day",
              valueCallback
            });
          case "eee":
            return match2.day(string, {
              width: "abbreviated",
              context: "formatting"
            }) || match2.day(string, {
              width: "short",
              context: "formatting"
            }) || match2.day(string, {
              width: "narrow",
              context: "formatting"
            });
          case "eeeee":
            return match2.day(string, {
              width: "narrow",
              context: "formatting"
            });
          case "eeeeee":
            return match2.day(string, {
              width: "short",
              context: "formatting"
            }) || match2.day(string, {
              width: "narrow",
              context: "formatting"
            });
          case "eeee":
          default:
            return match2.day(string, {
              width: "wide",
              context: "formatting"
            }) || match2.day(string, {
              width: "abbreviated",
              context: "formatting"
            }) || match2.day(string, {
              width: "short",
              context: "formatting"
            }) || match2.day(string, {
              width: "narrow",
              context: "formatting"
            });
        }
      },
      validate: function(_date, value, _options) {
        return value >= 0 && value <= 6;
      },
      set: function(date, _flags, value, options) {
        date = setUTCDay(date, value, options);
        date.setUTCHours(0, 0, 0, 0);
        return date;
      },
      incompatibleTokens: ["y", "R", "u", "q", "Q", "M", "L", "I", "d", "D", "E", "i", "c", "t", "T"]
    },
    c: {
      priority: 90,
      parse: function(string, token, match2, options) {
        var valueCallback = function(value) {
          var wholeWeekDays = Math.floor((value - 1) / 7) * 7;
          return (value + options.weekStartsOn + 6) % 7 + wholeWeekDays;
        };
        switch (token) {
          case "c":
          case "cc":
            return parseNDigits(token.length, string, valueCallback);
          case "co":
            return match2.ordinalNumber(string, {
              unit: "day",
              valueCallback
            });
          case "ccc":
            return match2.day(string, {
              width: "abbreviated",
              context: "standalone"
            }) || match2.day(string, {
              width: "short",
              context: "standalone"
            }) || match2.day(string, {
              width: "narrow",
              context: "standalone"
            });
          case "ccccc":
            return match2.day(string, {
              width: "narrow",
              context: "standalone"
            });
          case "cccccc":
            return match2.day(string, {
              width: "short",
              context: "standalone"
            }) || match2.day(string, {
              width: "narrow",
              context: "standalone"
            });
          case "cccc":
          default:
            return match2.day(string, {
              width: "wide",
              context: "standalone"
            }) || match2.day(string, {
              width: "abbreviated",
              context: "standalone"
            }) || match2.day(string, {
              width: "short",
              context: "standalone"
            }) || match2.day(string, {
              width: "narrow",
              context: "standalone"
            });
        }
      },
      validate: function(_date, value, _options) {
        return value >= 0 && value <= 6;
      },
      set: function(date, _flags, value, options) {
        date = setUTCDay(date, value, options);
        date.setUTCHours(0, 0, 0, 0);
        return date;
      },
      incompatibleTokens: ["y", "R", "u", "q", "Q", "M", "L", "I", "d", "D", "E", "i", "e", "t", "T"]
    },
    i: {
      priority: 90,
      parse: function(string, token, match2, _options) {
        var valueCallback = function(value) {
          if (value === 0) {
            return 7;
          }
          return value;
        };
        switch (token) {
          case "i":
          case "ii":
            return parseNDigits(token.length, string);
          case "io":
            return match2.ordinalNumber(string, {
              unit: "day"
            });
          case "iii":
            return match2.day(string, {
              width: "abbreviated",
              context: "formatting",
              valueCallback
            }) || match2.day(string, {
              width: "short",
              context: "formatting",
              valueCallback
            }) || match2.day(string, {
              width: "narrow",
              context: "formatting",
              valueCallback
            });
          case "iiiii":
            return match2.day(string, {
              width: "narrow",
              context: "formatting",
              valueCallback
            });
          case "iiiiii":
            return match2.day(string, {
              width: "short",
              context: "formatting",
              valueCallback
            }) || match2.day(string, {
              width: "narrow",
              context: "formatting",
              valueCallback
            });
          case "iiii":
          default:
            return match2.day(string, {
              width: "wide",
              context: "formatting",
              valueCallback
            }) || match2.day(string, {
              width: "abbreviated",
              context: "formatting",
              valueCallback
            }) || match2.day(string, {
              width: "short",
              context: "formatting",
              valueCallback
            }) || match2.day(string, {
              width: "narrow",
              context: "formatting",
              valueCallback
            });
        }
      },
      validate: function(_date, value, _options) {
        return value >= 1 && value <= 7;
      },
      set: function(date, _flags, value, options) {
        date = setUTCISODay(date, value, options);
        date.setUTCHours(0, 0, 0, 0);
        return date;
      },
      incompatibleTokens: ["y", "Y", "u", "q", "Q", "M", "L", "w", "d", "D", "E", "e", "c", "t", "T"]
    },
    a: {
      priority: 80,
      parse: function(string, token, match2, _options) {
        switch (token) {
          case "a":
          case "aa":
          case "aaa":
            return match2.dayPeriod(string, {
              width: "abbreviated",
              context: "formatting"
            }) || match2.dayPeriod(string, {
              width: "narrow",
              context: "formatting"
            });
          case "aaaaa":
            return match2.dayPeriod(string, {
              width: "narrow",
              context: "formatting"
            });
          case "aaaa":
          default:
            return match2.dayPeriod(string, {
              width: "wide",
              context: "formatting"
            }) || match2.dayPeriod(string, {
              width: "abbreviated",
              context: "formatting"
            }) || match2.dayPeriod(string, {
              width: "narrow",
              context: "formatting"
            });
        }
      },
      set: function(date, _flags, value, _options) {
        date.setUTCHours(dayPeriodEnumToHours(value), 0, 0, 0);
        return date;
      },
      incompatibleTokens: ["b", "B", "H", "K", "k", "t", "T"]
    },
    b: {
      priority: 80,
      parse: function(string, token, match2, _options) {
        switch (token) {
          case "b":
          case "bb":
          case "bbb":
            return match2.dayPeriod(string, {
              width: "abbreviated",
              context: "formatting"
            }) || match2.dayPeriod(string, {
              width: "narrow",
              context: "formatting"
            });
          case "bbbbb":
            return match2.dayPeriod(string, {
              width: "narrow",
              context: "formatting"
            });
          case "bbbb":
          default:
            return match2.dayPeriod(string, {
              width: "wide",
              context: "formatting"
            }) || match2.dayPeriod(string, {
              width: "abbreviated",
              context: "formatting"
            }) || match2.dayPeriod(string, {
              width: "narrow",
              context: "formatting"
            });
        }
      },
      set: function(date, _flags, value, _options) {
        date.setUTCHours(dayPeriodEnumToHours(value), 0, 0, 0);
        return date;
      },
      incompatibleTokens: ["a", "B", "H", "K", "k", "t", "T"]
    },
    B: {
      priority: 80,
      parse: function(string, token, match2, _options) {
        switch (token) {
          case "B":
          case "BB":
          case "BBB":
            return match2.dayPeriod(string, {
              width: "abbreviated",
              context: "formatting"
            }) || match2.dayPeriod(string, {
              width: "narrow",
              context: "formatting"
            });
          case "BBBBB":
            return match2.dayPeriod(string, {
              width: "narrow",
              context: "formatting"
            });
          case "BBBB":
          default:
            return match2.dayPeriod(string, {
              width: "wide",
              context: "formatting"
            }) || match2.dayPeriod(string, {
              width: "abbreviated",
              context: "formatting"
            }) || match2.dayPeriod(string, {
              width: "narrow",
              context: "formatting"
            });
        }
      },
      set: function(date, _flags, value, _options) {
        date.setUTCHours(dayPeriodEnumToHours(value), 0, 0, 0);
        return date;
      },
      incompatibleTokens: ["a", "b", "t", "T"]
    },
    h: {
      priority: 70,
      parse: function(string, token, match2, _options) {
        switch (token) {
          case "h":
            return parseNumericPattern(numericPatterns.hour12h, string);
          case "ho":
            return match2.ordinalNumber(string, {
              unit: "hour"
            });
          default:
            return parseNDigits(token.length, string);
        }
      },
      validate: function(_date, value, _options) {
        return value >= 1 && value <= 12;
      },
      set: function(date, _flags, value, _options) {
        var isPM = date.getUTCHours() >= 12;
        if (isPM && value < 12) {
          date.setUTCHours(value + 12, 0, 0, 0);
        } else if (!isPM && value === 12) {
          date.setUTCHours(0, 0, 0, 0);
        } else {
          date.setUTCHours(value, 0, 0, 0);
        }
        return date;
      },
      incompatibleTokens: ["H", "K", "k", "t", "T"]
    },
    H: {
      priority: 70,
      parse: function(string, token, match2, _options) {
        switch (token) {
          case "H":
            return parseNumericPattern(numericPatterns.hour23h, string);
          case "Ho":
            return match2.ordinalNumber(string, {
              unit: "hour"
            });
          default:
            return parseNDigits(token.length, string);
        }
      },
      validate: function(_date, value, _options) {
        return value >= 0 && value <= 23;
      },
      set: function(date, _flags, value, _options) {
        date.setUTCHours(value, 0, 0, 0);
        return date;
      },
      incompatibleTokens: ["a", "b", "h", "K", "k", "t", "T"]
    },
    K: {
      priority: 70,
      parse: function(string, token, match2, _options) {
        switch (token) {
          case "K":
            return parseNumericPattern(numericPatterns.hour11h, string);
          case "Ko":
            return match2.ordinalNumber(string, {
              unit: "hour"
            });
          default:
            return parseNDigits(token.length, string);
        }
      },
      validate: function(_date, value, _options) {
        return value >= 0 && value <= 11;
      },
      set: function(date, _flags, value, _options) {
        var isPM = date.getUTCHours() >= 12;
        if (isPM && value < 12) {
          date.setUTCHours(value + 12, 0, 0, 0);
        } else {
          date.setUTCHours(value, 0, 0, 0);
        }
        return date;
      },
      incompatibleTokens: ["a", "b", "h", "H", "k", "t", "T"]
    },
    k: {
      priority: 70,
      parse: function(string, token, match2, _options) {
        switch (token) {
          case "k":
            return parseNumericPattern(numericPatterns.hour24h, string);
          case "ko":
            return match2.ordinalNumber(string, {
              unit: "hour"
            });
          default:
            return parseNDigits(token.length, string);
        }
      },
      validate: function(_date, value, _options) {
        return value >= 1 && value <= 24;
      },
      set: function(date, _flags, value, _options) {
        var hours = value <= 24 ? value % 24 : value;
        date.setUTCHours(hours, 0, 0, 0);
        return date;
      },
      incompatibleTokens: ["a", "b", "h", "H", "K", "t", "T"]
    },
    m: {
      priority: 60,
      parse: function(string, token, match2, _options) {
        switch (token) {
          case "m":
            return parseNumericPattern(numericPatterns.minute, string);
          case "mo":
            return match2.ordinalNumber(string, {
              unit: "minute"
            });
          default:
            return parseNDigits(token.length, string);
        }
      },
      validate: function(_date, value, _options) {
        return value >= 0 && value <= 59;
      },
      set: function(date, _flags, value, _options) {
        date.setUTCMinutes(value, 0, 0);
        return date;
      },
      incompatibleTokens: ["t", "T"]
    },
    s: {
      priority: 50,
      parse: function(string, token, match2, _options) {
        switch (token) {
          case "s":
            return parseNumericPattern(numericPatterns.second, string);
          case "so":
            return match2.ordinalNumber(string, {
              unit: "second"
            });
          default:
            return parseNDigits(token.length, string);
        }
      },
      validate: function(_date, value, _options) {
        return value >= 0 && value <= 59;
      },
      set: function(date, _flags, value, _options) {
        date.setUTCSeconds(value, 0);
        return date;
      },
      incompatibleTokens: ["t", "T"]
    },
    S: {
      priority: 30,
      parse: function(string, token, _match, _options) {
        var valueCallback = function(value) {
          return Math.floor(value * Math.pow(10, -token.length + 3));
        };
        return parseNDigits(token.length, string, valueCallback);
      },
      set: function(date, _flags, value, _options) {
        date.setUTCMilliseconds(value);
        return date;
      },
      incompatibleTokens: ["t", "T"]
    },
    X: {
      priority: 10,
      parse: function(string, token, _match, _options) {
        switch (token) {
          case "X":
            return parseTimezonePattern(timezonePatterns.basicOptionalMinutes, string);
          case "XX":
            return parseTimezonePattern(timezonePatterns.basic, string);
          case "XXXX":
            return parseTimezonePattern(timezonePatterns.basicOptionalSeconds, string);
          case "XXXXX":
            return parseTimezonePattern(timezonePatterns.extendedOptionalSeconds, string);
          case "XXX":
          default:
            return parseTimezonePattern(timezonePatterns.extended, string);
        }
      },
      set: function(date, flags, value, _options) {
        if (flags.timestampIsSet) {
          return date;
        }
        return new Date(date.getTime() - value);
      },
      incompatibleTokens: ["t", "T", "x"]
    },
    x: {
      priority: 10,
      parse: function(string, token, _match, _options) {
        switch (token) {
          case "x":
            return parseTimezonePattern(timezonePatterns.basicOptionalMinutes, string);
          case "xx":
            return parseTimezonePattern(timezonePatterns.basic, string);
          case "xxxx":
            return parseTimezonePattern(timezonePatterns.basicOptionalSeconds, string);
          case "xxxxx":
            return parseTimezonePattern(timezonePatterns.extendedOptionalSeconds, string);
          case "xxx":
          default:
            return parseTimezonePattern(timezonePatterns.extended, string);
        }
      },
      set: function(date, flags, value, _options) {
        if (flags.timestampIsSet) {
          return date;
        }
        return new Date(date.getTime() - value);
      },
      incompatibleTokens: ["t", "T", "X"]
    },
    t: {
      priority: 40,
      parse: function(string, _token, _match, _options) {
        return parseAnyDigitsSigned(string);
      },
      set: function(_date, _flags, value, _options) {
        return [new Date(value * 1e3), {
          timestampIsSet: true
        }];
      },
      incompatibleTokens: "*"
    },
    T: {
      priority: 20,
      parse: function(string, _token, _match, _options) {
        return parseAnyDigitsSigned(string);
      },
      set: function(_date, _flags, value, _options) {
        return [new Date(value), {
          timestampIsSet: true
        }];
      },
      incompatibleTokens: "*"
    }
  };
  var parsers_default = parsers;

  // ../../node_modules/date-fns/esm/parse/index.js
  var TIMEZONE_UNIT_PRIORITY = 10;
  var formattingTokensRegExp2 = /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g;
  var longFormattingTokensRegExp2 = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g;
  var escapedStringRegExp2 = /^'([^]*?)'?$/;
  var doubleQuoteRegExp2 = /''/g;
  var notWhitespaceRegExp = /\S/;
  var unescapedLatinCharacterRegExp2 = /[a-zA-Z]/;
  function parse2(dirtyDateString, dirtyFormatString, dirtyReferenceDate, dirtyOptions) {
    requiredArgs(3, arguments);
    var dateString = String(dirtyDateString);
    var formatString = String(dirtyFormatString);
    var options = dirtyOptions || {};
    var locale2 = options.locale || en_US_default;
    if (!locale2.match) {
      throw new RangeError("locale must contain match property");
    }
    var localeFirstWeekContainsDate = locale2.options && locale2.options.firstWeekContainsDate;
    var defaultFirstWeekContainsDate = localeFirstWeekContainsDate == null ? 1 : toInteger(localeFirstWeekContainsDate);
    var firstWeekContainsDate = options.firstWeekContainsDate == null ? defaultFirstWeekContainsDate : toInteger(options.firstWeekContainsDate);
    if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) {
      throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");
    }
    var localeWeekStartsOn = locale2.options && locale2.options.weekStartsOn;
    var defaultWeekStartsOn = localeWeekStartsOn == null ? 0 : toInteger(localeWeekStartsOn);
    var weekStartsOn = options.weekStartsOn == null ? defaultWeekStartsOn : toInteger(options.weekStartsOn);
    if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
      throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");
    }
    if (formatString === "") {
      if (dateString === "") {
        return toDate(dirtyReferenceDate);
      } else {
        return new Date(NaN);
      }
    }
    var subFnOptions = {
      firstWeekContainsDate,
      weekStartsOn,
      locale: locale2
    };
    var setters = [{
      priority: TIMEZONE_UNIT_PRIORITY,
      subPriority: -1,
      set: dateToSystemTimezone,
      index: 0
    }];
    var i2;
    var tokens = formatString.match(longFormattingTokensRegExp2).map(function(substring) {
      var firstCharacter2 = substring[0];
      if (firstCharacter2 === "p" || firstCharacter2 === "P") {
        var longFormatter = longFormatters_default[firstCharacter2];
        return longFormatter(substring, locale2.formatLong, subFnOptions);
      }
      return substring;
    }).join("").match(formattingTokensRegExp2);
    var usedTokens = [];
    for (i2 = 0; i2 < tokens.length; i2++) {
      var token = tokens[i2];
      if (!options.useAdditionalWeekYearTokens && isProtectedWeekYearToken(token)) {
        throwProtectedError(token, formatString, dirtyDateString);
      }
      if (!options.useAdditionalDayOfYearTokens && isProtectedDayOfYearToken(token)) {
        throwProtectedError(token, formatString, dirtyDateString);
      }
      var firstCharacter = token[0];
      var parser = parsers_default[firstCharacter];
      if (parser) {
        var incompatibleTokens = parser.incompatibleTokens;
        if (Array.isArray(incompatibleTokens)) {
          var incompatibleToken = void 0;
          for (var _i2 = 0; _i2 < usedTokens.length; _i2++) {
            var usedToken = usedTokens[_i2].token;
            if (incompatibleTokens.indexOf(usedToken) !== -1 || usedToken === firstCharacter) {
              incompatibleToken = usedTokens[_i2];
              break;
            }
          }
          if (incompatibleToken) {
            throw new RangeError("The format string mustn't contain `".concat(incompatibleToken.fullToken, "` and `").concat(token, "` at the same time"));
          }
        } else if (parser.incompatibleTokens === "*" && usedTokens.length) {
          throw new RangeError("The format string mustn't contain `".concat(token, "` and any other token at the same time"));
        }
        usedTokens.push({
          token: firstCharacter,
          fullToken: token
        });
        var parseResult = parser.parse(dateString, token, locale2.match, subFnOptions);
        if (!parseResult) {
          return new Date(NaN);
        }
        setters.push({
          priority: parser.priority,
          subPriority: parser.subPriority || 0,
          set: parser.set,
          validate: parser.validate,
          value: parseResult.value,
          index: setters.length
        });
        dateString = parseResult.rest;
      } else {
        if (firstCharacter.match(unescapedLatinCharacterRegExp2)) {
          throw new RangeError("Format string contains an unescaped latin alphabet character `" + firstCharacter + "`");
        }
        if (token === "''") {
          token = "'";
        } else if (firstCharacter === "'") {
          token = cleanEscapedString2(token);
        }
        if (dateString.indexOf(token) === 0) {
          dateString = dateString.slice(token.length);
        } else {
          return new Date(NaN);
        }
      }
    }
    if (dateString.length > 0 && notWhitespaceRegExp.test(dateString)) {
      return new Date(NaN);
    }
    var uniquePrioritySetters = setters.map(function(setter2) {
      return setter2.priority;
    }).sort(function(a2, b2) {
      return b2 - a2;
    }).filter(function(priority, index, array) {
      return array.indexOf(priority) === index;
    }).map(function(priority) {
      return setters.filter(function(setter2) {
        return setter2.priority === priority;
      }).sort(function(a2, b2) {
        return b2.subPriority - a2.subPriority;
      });
    }).map(function(setterArray) {
      return setterArray[0];
    });
    var date = toDate(dirtyReferenceDate);
    if (isNaN(date)) {
      return new Date(NaN);
    }
    var utcDate = subMilliseconds(date, getTimezoneOffsetInMilliseconds(date));
    var flags = {};
    for (i2 = 0; i2 < uniquePrioritySetters.length; i2++) {
      var setter = uniquePrioritySetters[i2];
      if (setter.validate && !setter.validate(utcDate, setter.value, subFnOptions)) {
        return new Date(NaN);
      }
      var result = setter.set(utcDate, flags, setter.value, subFnOptions);
      if (result[0]) {
        utcDate = result[0];
        assign(flags, result[1]);
      } else {
        utcDate = result;
      }
    }
    return utcDate;
  }
  function dateToSystemTimezone(date, flags) {
    if (flags.timestampIsSet) {
      return date;
    }
    var convertedDate = new Date(0);
    convertedDate.setFullYear(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());
    convertedDate.setHours(date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds());
    return convertedDate;
  }
  function cleanEscapedString2(input) {
    return input.match(escapedStringRegExp2)[1].replace(doubleQuoteRegExp2, "'");
  }

  // ../../node_modules/date-fns/esm/startOfHour/index.js
  function startOfHour(dirtyDate) {
    requiredArgs(1, arguments);
    var date = toDate(dirtyDate);
    date.setMinutes(0, 0, 0);
    return date;
  }

  // ../../node_modules/date-fns/esm/startOfSecond/index.js
  function startOfSecond(dirtyDate) {
    requiredArgs(1, arguments);
    var date = toDate(dirtyDate);
    date.setMilliseconds(0);
    return date;
  }

  // ../../node_modules/date-fns/esm/parseISO/index.js
  var MILLISECONDS_IN_HOUR4 = 36e5;
  var MILLISECONDS_IN_MINUTE4 = 6e4;
  var DEFAULT_ADDITIONAL_DIGITS = 2;
  var patterns = {
    dateTimeDelimiter: /[T ]/,
    timeZoneDelimiter: /[Z ]/i,
    timezone: /([Z+-].*)$/
  };
  var dateRegex = /^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/;
  var timeRegex = /^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/;
  var timezoneRegex = /^([+-])(\d{2})(?::?(\d{2}))?$/;
  function parseISO(argument, dirtyOptions) {
    requiredArgs(1, arguments);
    var options = dirtyOptions || {};
    var additionalDigits = options.additionalDigits == null ? DEFAULT_ADDITIONAL_DIGITS : toInteger(options.additionalDigits);
    if (additionalDigits !== 2 && additionalDigits !== 1 && additionalDigits !== 0) {
      throw new RangeError("additionalDigits must be 0, 1 or 2");
    }
    if (!(typeof argument === "string" || Object.prototype.toString.call(argument) === "[object String]")) {
      return new Date(NaN);
    }
    var dateStrings = splitDateString(argument);
    var date;
    if (dateStrings.date) {
      var parseYearResult = parseYear(dateStrings.date, additionalDigits);
      date = parseDate(parseYearResult.restDateString, parseYearResult.year);
    }
    if (isNaN(date) || !date) {
      return new Date(NaN);
    }
    var timestamp = date.getTime();
    var time = 0;
    var offset2;
    if (dateStrings.time) {
      time = parseTime(dateStrings.time);
      if (isNaN(time) || time === null) {
        return new Date(NaN);
      }
    }
    if (dateStrings.timezone) {
      offset2 = parseTimezone(dateStrings.timezone);
      if (isNaN(offset2)) {
        return new Date(NaN);
      }
    } else {
      var dirtyDate = new Date(timestamp + time);
      var result = new Date(0);
      result.setFullYear(dirtyDate.getUTCFullYear(), dirtyDate.getUTCMonth(), dirtyDate.getUTCDate());
      result.setHours(dirtyDate.getUTCHours(), dirtyDate.getUTCMinutes(), dirtyDate.getUTCSeconds(), dirtyDate.getUTCMilliseconds());
      return result;
    }
    return new Date(timestamp + time + offset2);
  }
  function splitDateString(dateString) {
    var dateStrings = {};
    var array = dateString.split(patterns.dateTimeDelimiter);
    var timeString;
    if (array.length > 2) {
      return dateStrings;
    }
    if (/:/.test(array[0])) {
      dateStrings.date = null;
      timeString = array[0];
    } else {
      dateStrings.date = array[0];
      timeString = array[1];
      if (patterns.timeZoneDelimiter.test(dateStrings.date)) {
        dateStrings.date = dateString.split(patterns.timeZoneDelimiter)[0];
        timeString = dateString.substr(dateStrings.date.length, dateString.length);
      }
    }
    if (timeString) {
      var token = patterns.timezone.exec(timeString);
      if (token) {
        dateStrings.time = timeString.replace(token[1], "");
        dateStrings.timezone = token[1];
      } else {
        dateStrings.time = timeString;
      }
    }
    return dateStrings;
  }
  function parseYear(dateString, additionalDigits) {
    var regex = new RegExp("^(?:(\\d{4}|[+-]\\d{" + (4 + additionalDigits) + "})|(\\d{2}|[+-]\\d{" + (2 + additionalDigits) + "})$)");
    var captures = dateString.match(regex);
    if (!captures)
      return {
        year: null
      };
    var year = captures[1] && parseInt(captures[1]);
    var century = captures[2] && parseInt(captures[2]);
    return {
      year: century == null ? year : century * 100,
      restDateString: dateString.slice((captures[1] || captures[2]).length)
    };
  }
  function parseDate(dateString, year) {
    if (year === null)
      return null;
    var captures = dateString.match(dateRegex);
    if (!captures)
      return null;
    var isWeekDate = !!captures[4];
    var dayOfYear = parseDateUnit(captures[1]);
    var month = parseDateUnit(captures[2]) - 1;
    var day = parseDateUnit(captures[3]);
    var week = parseDateUnit(captures[4]);
    var dayOfWeek = parseDateUnit(captures[5]) - 1;
    if (isWeekDate) {
      if (!validateWeekDate(year, week, dayOfWeek)) {
        return new Date(NaN);
      }
      return dayOfISOWeekYear(year, week, dayOfWeek);
    } else {
      var date = new Date(0);
      if (!validateDate(year, month, day) || !validateDayOfYearDate(year, dayOfYear)) {
        return new Date(NaN);
      }
      date.setUTCFullYear(year, month, Math.max(dayOfYear, day));
      return date;
    }
  }
  function parseDateUnit(value) {
    return value ? parseInt(value) : 1;
  }
  function parseTime(timeString) {
    var captures = timeString.match(timeRegex);
    if (!captures)
      return null;
    var hours = parseTimeUnit(captures[1]);
    var minutes = parseTimeUnit(captures[2]);
    var seconds = parseTimeUnit(captures[3]);
    if (!validateTime(hours, minutes, seconds)) {
      return NaN;
    }
    return hours * MILLISECONDS_IN_HOUR4 + minutes * MILLISECONDS_IN_MINUTE4 + seconds * 1e3;
  }
  function parseTimeUnit(value) {
    return value && parseFloat(value.replace(",", ".")) || 0;
  }
  function parseTimezone(timezoneString) {
    if (timezoneString === "Z")
      return 0;
    var captures = timezoneString.match(timezoneRegex);
    if (!captures)
      return 0;
    var sign2 = captures[1] === "+" ? -1 : 1;
    var hours = parseInt(captures[2]);
    var minutes = captures[3] && parseInt(captures[3]) || 0;
    if (!validateTimezone(hours, minutes)) {
      return NaN;
    }
    return sign2 * (hours * MILLISECONDS_IN_HOUR4 + minutes * MILLISECONDS_IN_MINUTE4);
  }
  function dayOfISOWeekYear(isoWeekYear, week, day) {
    var date = new Date(0);
    date.setUTCFullYear(isoWeekYear, 0, 4);
    var fourthOfJanuaryDay = date.getUTCDay() || 7;
    var diff = (week - 1) * 7 + day + 1 - fourthOfJanuaryDay;
    date.setUTCDate(date.getUTCDate() + diff);
    return date;
  }
  var daysInMonths = [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  function isLeapYearIndex2(year) {
    return year % 400 === 0 || year % 4 === 0 && year % 100;
  }
  function validateDate(year, month, date) {
    return month >= 0 && month <= 11 && date >= 1 && date <= (daysInMonths[month] || (isLeapYearIndex2(year) ? 29 : 28));
  }
  function validateDayOfYearDate(year, dayOfYear) {
    return dayOfYear >= 1 && dayOfYear <= (isLeapYearIndex2(year) ? 366 : 365);
  }
  function validateWeekDate(_year, week, day) {
    return week >= 1 && week <= 53 && day >= 0 && day <= 6;
  }
  function validateTime(hours, minutes, seconds) {
    if (hours === 24) {
      return minutes === 0 && seconds === 0;
    }
    return seconds >= 0 && seconds < 60 && minutes >= 0 && minutes < 60 && hours >= 0 && hours < 25;
  }
  function validateTimezone(_hours, minutes) {
    return minutes >= 0 && minutes <= 59;
  }

  // ../../node_modules/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.esm.js
  var FORMATS = {
    datetime: "MMM d, yyyy, h:mm:ss aaaa",
    millisecond: "h:mm:ss.SSS aaaa",
    second: "h:mm:ss aaaa",
    minute: "h:mm aaaa",
    hour: "ha",
    day: "MMM d",
    week: "PP",
    month: "MMM yyyy",
    quarter: "qqq - yyyy",
    year: "yyyy"
  };
  adapters._date.override({
    _id: "date-fns",
    formats: function() {
      return FORMATS;
    },
    parse: function(value, fmt) {
      if (value === null || typeof value === "undefined") {
        return null;
      }
      const type = typeof value;
      if (type === "number" || value instanceof Date) {
        value = toDate(value);
      } else if (type === "string") {
        if (typeof fmt === "string") {
          value = parse2(value, fmt, new Date(), this.options);
        } else {
          value = parseISO(value, this.options);
        }
      }
      return isValid(value) ? value.getTime() : null;
    },
    format: function(time, fmt) {
      return format2(time, fmt, this.options);
    },
    add: function(time, amount, unit) {
      switch (unit) {
        case "millisecond":
          return addMilliseconds(time, amount);
        case "second":
          return addSeconds(time, amount);
        case "minute":
          return addMinutes(time, amount);
        case "hour":
          return addHours(time, amount);
        case "day":
          return addDays(time, amount);
        case "week":
          return addWeeks(time, amount);
        case "month":
          return addMonths(time, amount);
        case "quarter":
          return addQuarters(time, amount);
        case "year":
          return addYears(time, amount);
        default:
          return time;
      }
    },
    diff: function(max2, min2, unit) {
      switch (unit) {
        case "millisecond":
          return differenceInMilliseconds(max2, min2);
        case "second":
          return differenceInSeconds(max2, min2);
        case "minute":
          return differenceInMinutes(max2, min2);
        case "hour":
          return differenceInHours(max2, min2);
        case "day":
          return differenceInDays(max2, min2);
        case "week":
          return differenceInWeeks(max2, min2);
        case "month":
          return differenceInMonths(max2, min2);
        case "quarter":
          return differenceInQuarters(max2, min2);
        case "year":
          return differenceInYears(max2, min2);
        default:
          return 0;
      }
    },
    startOf: function(time, unit, weekday) {
      switch (unit) {
        case "second":
          return startOfSecond(time);
        case "minute":
          return startOfMinute(time);
        case "hour":
          return startOfHour(time);
        case "day":
          return startOfDay(time);
        case "week":
          return startOfWeek(time);
        case "isoWeek":
          return startOfWeek(time, { weekStartsOn: +weekday });
        case "month":
          return startOfMonth(time);
        case "quarter":
          return startOfQuarter(time);
        case "year":
          return startOfYear(time);
        default:
          return time;
      }
    },
    endOf: function(time, unit) {
      switch (unit) {
        case "second":
          return endOfSecond(time);
        case "minute":
          return endOfMinute(time);
        case "hour":
          return endOfHour(time);
        case "day":
          return endOfDay(time);
        case "week":
          return endOfWeek(time);
        case "month":
          return endOfMonth(time);
        case "quarter":
          return endOfQuarter(time);
        case "year":
          return endOfYear(time);
        default:
          return time;
      }
    }
  });

  // ../../node_modules/chartkick/chart.js/chart.esm.js
  import_chartkick.default.use(auto_esm_default);

  // theme.js
  (function() {
    "use strict";
    var typeOf = function(x2) {
      var t3 = typeof x2;
      if (x2 === null) {
        return "null";
      } else if (t3 === "object" && (Array.prototype.isPrototypeOf(x2) || x2.constructor && x2.constructor.name === "Array")) {
        return "array";
      } else if (t3 === "object" && (String.prototype.isPrototypeOf(x2) || x2.constructor && x2.constructor.name === "String")) {
        return "string";
      } else {
        return t3;
      }
    };
    var isType$1 = function(type2) {
      return function(value2) {
        return typeOf(value2) === type2;
      };
    };
    var isSimpleType = function(type2) {
      return function(value2) {
        return typeof value2 === type2;
      };
    };
    var eq$1 = function(t3) {
      return function(a2) {
        return t3 === a2;
      };
    };
    var isString = isType$1("string");
    var isObject2 = isType$1("object");
    var isArray2 = isType$1("array");
    var isNull = eq$1(null);
    var isBoolean = isSimpleType("boolean");
    var isUndefined = eq$1(void 0);
    var isNullable = function(a2) {
      return a2 === null || a2 === void 0;
    };
    var isNonNullable = function(a2) {
      return !isNullable(a2);
    };
    var isFunction2 = isSimpleType("function");
    var isNumber2 = isSimpleType("number");
    var isArrayOf = function(value2, pred) {
      if (isArray2(value2)) {
        for (var i2 = 0, len = value2.length; i2 < len; ++i2) {
          if (!pred(value2[i2])) {
            return false;
          }
        }
        return true;
      }
      return false;
    };
    var noop3 = function() {
    };
    var noarg = function(f2) {
      return function() {
        return f2();
      };
    };
    var compose = function(fa, fb) {
      return function() {
        var args = [];
        for (var _i2 = 0; _i2 < arguments.length; _i2++) {
          args[_i2] = arguments[_i2];
        }
        return fa(fb.apply(null, args));
      };
    };
    var compose1 = function(fbc, fab) {
      return function(a2) {
        return fbc(fab(a2));
      };
    };
    var constant$1 = function(value2) {
      return function() {
        return value2;
      };
    };
    var identity$1 = function(x2) {
      return x2;
    };
    var tripleEquals = function(a2, b3) {
      return a2 === b3;
    };
    function curry(fn3) {
      var initialArgs = [];
      for (var _i2 = 1; _i2 < arguments.length; _i2++) {
        initialArgs[_i2 - 1] = arguments[_i2];
      }
      return function() {
        var restArgs = [];
        for (var _i3 = 0; _i3 < arguments.length; _i3++) {
          restArgs[_i3] = arguments[_i3];
        }
        var all2 = initialArgs.concat(restArgs);
        return fn3.apply(null, all2);
      };
    }
    var not = function(f2) {
      return function(t3) {
        return !f2(t3);
      };
    };
    var die = function(msg) {
      return function() {
        throw new Error(msg);
      };
    };
    var never = constant$1(false);
    var always = constant$1(true);
    var global$g = tinymce.util.Tools.resolve("tinymce.ThemeManager");
    var __assign = function() {
      __assign = Object.assign || function __assign2(t3) {
        for (var s2, i2 = 1, n2 = arguments.length; i2 < n2; i2++) {
          s2 = arguments[i2];
          for (var p2 in s2)
            if (Object.prototype.hasOwnProperty.call(s2, p2))
              t3[p2] = s2[p2];
        }
        return t3;
      };
      return __assign.apply(this, arguments);
    };
    function __rest(s2, e2) {
      var t3 = {};
      for (var p2 in s2)
        if (Object.prototype.hasOwnProperty.call(s2, p2) && e2.indexOf(p2) < 0)
          t3[p2] = s2[p2];
      if (s2 != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i2 = 0, p2 = Object.getOwnPropertySymbols(s2); i2 < p2.length; i2++) {
          if (e2.indexOf(p2[i2]) < 0 && Object.prototype.propertyIsEnumerable.call(s2, p2[i2]))
            t3[p2[i2]] = s2[p2[i2]];
        }
      return t3;
    }
    function __spreadArray(to2, from2, pack) {
      if (pack || arguments.length === 2)
        for (var i2 = 0, l3 = from2.length, ar; i2 < l3; i2++) {
          if (ar || !(i2 in from2)) {
            if (!ar)
              ar = Array.prototype.slice.call(from2, 0, i2);
            ar[i2] = from2[i2];
          }
        }
      return to2.concat(ar || Array.prototype.slice.call(from2));
    }
    var none = function() {
      return NONE;
    };
    var NONE = function() {
      var call = function(thunk2) {
        return thunk2();
      };
      var id2 = identity$1;
      var me2 = {
        fold: function(n2, _s) {
          return n2();
        },
        isSome: never,
        isNone: always,
        getOr: id2,
        getOrThunk: call,
        getOrDie: function(msg) {
          throw new Error(msg || "error: getOrDie called on none.");
        },
        getOrNull: constant$1(null),
        getOrUndefined: constant$1(void 0),
        or: id2,
        orThunk: call,
        map: none,
        each: noop3,
        bind: none,
        exists: never,
        forall: always,
        filter: function() {
          return none();
        },
        toArray: function() {
          return [];
        },
        toString: constant$1("none()")
      };
      return me2;
    }();
    var some = function(a2) {
      var constant_a = constant$1(a2);
      var self2 = function() {
        return me2;
      };
      var bind2 = function(f2) {
        return f2(a2);
      };
      var me2 = {
        fold: function(n2, s2) {
          return s2(a2);
        },
        isSome: always,
        isNone: never,
        getOr: constant_a,
        getOrThunk: constant_a,
        getOrDie: constant_a,
        getOrNull: constant_a,
        getOrUndefined: constant_a,
        or: self2,
        orThunk: self2,
        map: function(f2) {
          return some(f2(a2));
        },
        each: function(f2) {
          f2(a2);
        },
        bind: bind2,
        exists: bind2,
        forall: bind2,
        filter: function(f2) {
          return f2(a2) ? me2 : NONE;
        },
        toArray: function() {
          return [a2];
        },
        toString: function() {
          return "some(" + a2 + ")";
        }
      };
      return me2;
    };
    var from$1 = function(value2) {
      return value2 === null || value2 === void 0 ? NONE : some(value2);
    };
    var Optional = {
      some,
      none,
      from: from$1
    };
    var nativeSlice = Array.prototype.slice;
    var nativeIndexOf = Array.prototype.indexOf;
    var nativePush = Array.prototype.push;
    var rawIndexOf = function(ts, t3) {
      return nativeIndexOf.call(ts, t3);
    };
    var indexOf2 = function(xs, x2) {
      var r3 = rawIndexOf(xs, x2);
      return r3 === -1 ? Optional.none() : Optional.some(r3);
    };
    var contains$2 = function(xs, x2) {
      return rawIndexOf(xs, x2) > -1;
    };
    var exists = function(xs, pred) {
      for (var i2 = 0, len = xs.length; i2 < len; i2++) {
        var x2 = xs[i2];
        if (pred(x2, i2)) {
          return true;
        }
      }
      return false;
    };
    var range$2 = function(num, f2) {
      var r3 = [];
      for (var i2 = 0; i2 < num; i2++) {
        r3.push(f2(i2));
      }
      return r3;
    };
    var chunk$1 = function(array, size) {
      var r3 = [];
      for (var i2 = 0; i2 < array.length; i2 += size) {
        var s2 = nativeSlice.call(array, i2, i2 + size);
        r3.push(s2);
      }
      return r3;
    };
    var map$2 = function(xs, f2) {
      var len = xs.length;
      var r3 = new Array(len);
      for (var i2 = 0; i2 < len; i2++) {
        var x2 = xs[i2];
        r3[i2] = f2(x2, i2);
      }
      return r3;
    };
    var each$1 = function(xs, f2) {
      for (var i2 = 0, len = xs.length; i2 < len; i2++) {
        var x2 = xs[i2];
        f2(x2, i2);
      }
    };
    var eachr = function(xs, f2) {
      for (var i2 = xs.length - 1; i2 >= 0; i2--) {
        var x2 = xs[i2];
        f2(x2, i2);
      }
    };
    var partition$3 = function(xs, pred) {
      var pass = [];
      var fail = [];
      for (var i2 = 0, len = xs.length; i2 < len; i2++) {
        var x2 = xs[i2];
        var arr = pred(x2, i2) ? pass : fail;
        arr.push(x2);
      }
      return {
        pass,
        fail
      };
    };
    var filter$2 = function(xs, pred) {
      var r3 = [];
      for (var i2 = 0, len = xs.length; i2 < len; i2++) {
        var x2 = xs[i2];
        if (pred(x2, i2)) {
          r3.push(x2);
        }
      }
      return r3;
    };
    var foldr = function(xs, f2, acc) {
      eachr(xs, function(x2, i2) {
        acc = f2(acc, x2, i2);
      });
      return acc;
    };
    var foldl = function(xs, f2, acc) {
      each$1(xs, function(x2, i2) {
        acc = f2(acc, x2, i2);
      });
      return acc;
    };
    var findUntil = function(xs, pred, until) {
      for (var i2 = 0, len = xs.length; i2 < len; i2++) {
        var x2 = xs[i2];
        if (pred(x2, i2)) {
          return Optional.some(x2);
        } else if (until(x2, i2)) {
          break;
        }
      }
      return Optional.none();
    };
    var find$5 = function(xs, pred) {
      return findUntil(xs, pred, never);
    };
    var findIndex$1 = function(xs, pred) {
      for (var i2 = 0, len = xs.length; i2 < len; i2++) {
        var x2 = xs[i2];
        if (pred(x2, i2)) {
          return Optional.some(i2);
        }
      }
      return Optional.none();
    };
    var flatten = function(xs) {
      var r3 = [];
      for (var i2 = 0, len = xs.length; i2 < len; ++i2) {
        if (!isArray2(xs[i2])) {
          throw new Error("Arr.flatten item " + i2 + " was not an array, input: " + xs);
        }
        nativePush.apply(r3, xs[i2]);
      }
      return r3;
    };
    var bind$3 = function(xs, f2) {
      return flatten(map$2(xs, f2));
    };
    var forall = function(xs, pred) {
      for (var i2 = 0, len = xs.length; i2 < len; ++i2) {
        var x2 = xs[i2];
        if (pred(x2, i2) !== true) {
          return false;
        }
      }
      return true;
    };
    var reverse = function(xs) {
      var r3 = nativeSlice.call(xs, 0);
      r3.reverse();
      return r3;
    };
    var difference = function(a1, a2) {
      return filter$2(a1, function(x2) {
        return !contains$2(a2, x2);
      });
    };
    var mapToObject = function(xs, f2) {
      var r3 = {};
      for (var i2 = 0, len = xs.length; i2 < len; i2++) {
        var x2 = xs[i2];
        r3[String(x2)] = f2(x2, i2);
      }
      return r3;
    };
    var pure$2 = function(x2) {
      return [x2];
    };
    var sort = function(xs, comparator) {
      var copy = nativeSlice.call(xs, 0);
      copy.sort(comparator);
      return copy;
    };
    var get$f = function(xs, i2) {
      return i2 >= 0 && i2 < xs.length ? Optional.some(xs[i2]) : Optional.none();
    };
    var head = function(xs) {
      return get$f(xs, 0);
    };
    var last$2 = function(xs) {
      return get$f(xs, xs.length - 1);
    };
    var from = isFunction2(Array.from) ? Array.from : function(x2) {
      return nativeSlice.call(x2);
    };
    var findMap = function(arr, f2) {
      for (var i2 = 0; i2 < arr.length; i2++) {
        var r3 = f2(arr[i2], i2);
        if (r3.isSome()) {
          return r3;
        }
      }
      return Optional.none();
    };
    var keys = Object.keys;
    var hasOwnProperty = Object.hasOwnProperty;
    var each2 = function(obj, f2) {
      var props = keys(obj);
      for (var k2 = 0, len = props.length; k2 < len; k2++) {
        var i2 = props[k2];
        var x2 = obj[i2];
        f2(x2, i2);
      }
    };
    var map$12 = function(obj, f2) {
      return tupleMap(obj, function(x2, i2) {
        return {
          k: i2,
          v: f2(x2, i2)
        };
      });
    };
    var tupleMap = function(obj, f2) {
      var r3 = {};
      each2(obj, function(x2, i2) {
        var tuple = f2(x2, i2);
        r3[tuple.k] = tuple.v;
      });
      return r3;
    };
    var objAcc = function(r3) {
      return function(x2, i2) {
        r3[i2] = x2;
      };
    };
    var internalFilter = function(obj, pred, onTrue, onFalse) {
      var r3 = {};
      each2(obj, function(x2, i2) {
        (pred(x2, i2) ? onTrue : onFalse)(x2, i2);
      });
      return r3;
    };
    var filter$1 = function(obj, pred) {
      var t3 = {};
      internalFilter(obj, pred, objAcc(t3), noop3);
      return t3;
    };
    var mapToArray = function(obj, f2) {
      var r3 = [];
      each2(obj, function(value2, name2) {
        r3.push(f2(value2, name2));
      });
      return r3;
    };
    var find$4 = function(obj, pred) {
      var props = keys(obj);
      for (var k2 = 0, len = props.length; k2 < len; k2++) {
        var i2 = props[k2];
        var x2 = obj[i2];
        if (pred(x2, i2, obj)) {
          return Optional.some(x2);
        }
      }
      return Optional.none();
    };
    var values = function(obj) {
      return mapToArray(obj, identity$1);
    };
    var get$e = function(obj, key) {
      return has$2(obj, key) ? Optional.from(obj[key]) : Optional.none();
    };
    var has$2 = function(obj, key) {
      return hasOwnProperty.call(obj, key);
    };
    var hasNonNullableKey = function(obj, key) {
      return has$2(obj, key) && obj[key] !== void 0 && obj[key] !== null;
    };
    var is$1 = function(lhs, rhs, comparator) {
      if (comparator === void 0) {
        comparator = tripleEquals;
      }
      return lhs.exists(function(left3) {
        return comparator(left3, rhs);
      });
    };
    var equals = function(lhs, rhs, comparator) {
      if (comparator === void 0) {
        comparator = tripleEquals;
      }
      return lift2(lhs, rhs, comparator).getOr(lhs.isNone() && rhs.isNone());
    };
    var cat = function(arr) {
      var r3 = [];
      var push = function(x2) {
        r3.push(x2);
      };
      for (var i2 = 0; i2 < arr.length; i2++) {
        arr[i2].each(push);
      }
      return r3;
    };
    var sequence = function(arr) {
      var r3 = [];
      for (var i2 = 0; i2 < arr.length; i2++) {
        var x2 = arr[i2];
        if (x2.isSome()) {
          r3.push(x2.getOrDie());
        } else {
          return Optional.none();
        }
      }
      return Optional.some(r3);
    };
    var lift2 = function(oa, ob, f2) {
      return oa.isSome() && ob.isSome() ? Optional.some(f2(oa.getOrDie(), ob.getOrDie())) : Optional.none();
    };
    var lift3 = function(oa, ob, oc, f2) {
      return oa.isSome() && ob.isSome() && oc.isSome() ? Optional.some(f2(oa.getOrDie(), ob.getOrDie(), oc.getOrDie())) : Optional.none();
    };
    var mapFrom = function(a2, f2) {
      return a2 !== void 0 && a2 !== null ? Optional.some(f2(a2)) : Optional.none();
    };
    var someIf = function(b3, a2) {
      return b3 ? Optional.some(a2) : Optional.none();
    };
    var addToEnd = function(str, suffix2) {
      return str + suffix2;
    };
    var removeFromStart = function(str, numChars) {
      return str.substring(numChars);
    };
    var checkRange = function(str, substr, start4) {
      return substr === "" || str.length >= substr.length && str.substr(start4, start4 + substr.length) === substr;
    };
    var removeLeading = function(str, prefix2) {
      return startsWith(str, prefix2) ? removeFromStart(str, prefix2.length) : str;
    };
    var ensureTrailing = function(str, suffix2) {
      return endsWith(str, suffix2) ? str : addToEnd(str, suffix2);
    };
    var contains$1 = function(str, substr) {
      return str.indexOf(substr) !== -1;
    };
    var startsWith = function(str, prefix2) {
      return checkRange(str, prefix2, 0);
    };
    var endsWith = function(str, suffix2) {
      return checkRange(str, suffix2, str.length - suffix2.length);
    };
    var blank = function(r3) {
      return function(s2) {
        return s2.replace(r3, "");
      };
    };
    var trim$1 = blank(/^\s+|\s+$/g);
    var isNotEmpty = function(s2) {
      return s2.length > 0;
    };
    var isEmpty = function(s2) {
      return !isNotEmpty(s2);
    };
    var isSupported$1 = function(dom2) {
      return dom2.style !== void 0 && isFunction2(dom2.style.getPropertyValue);
    };
    var fromHtml$2 = function(html, scope) {
      var doc = scope || document;
      var div = doc.createElement("div");
      div.innerHTML = html;
      if (!div.hasChildNodes() || div.childNodes.length > 1) {
        console.error("HTML does not have a single root node", html);
        throw new Error("HTML must have a single root node");
      }
      return fromDom(div.childNodes[0]);
    };
    var fromTag = function(tag, scope) {
      var doc = scope || document;
      var node = doc.createElement(tag);
      return fromDom(node);
    };
    var fromText = function(text2, scope) {
      var doc = scope || document;
      var node = doc.createTextNode(text2);
      return fromDom(node);
    };
    var fromDom = function(node) {
      if (node === null || node === void 0) {
        throw new Error("Node cannot be null or undefined");
      }
      return { dom: node };
    };
    var fromPoint = function(docElm, x2, y2) {
      return Optional.from(docElm.dom.elementFromPoint(x2, y2)).map(fromDom);
    };
    var SugarElement = {
      fromHtml: fromHtml$2,
      fromTag,
      fromText,
      fromDom,
      fromPoint
    };
    typeof window !== "undefined" ? window : Function("return this;")();
    var DOCUMENT = 9;
    var DOCUMENT_FRAGMENT = 11;
    var ELEMENT = 1;
    var TEXT = 3;
    var name$2 = function(element2) {
      var r3 = element2.dom.nodeName;
      return r3.toLowerCase();
    };
    var type = function(element2) {
      return element2.dom.nodeType;
    };
    var isType = function(t3) {
      return function(element2) {
        return type(element2) === t3;
      };
    };
    var isElement$2 = isType(ELEMENT);
    var isText$1 = isType(TEXT);
    var isDocument = isType(DOCUMENT);
    var isDocumentFragment = isType(DOCUMENT_FRAGMENT);
    var cached = function(f2) {
      var called = false;
      var r3;
      return function() {
        var args = [];
        for (var _i2 = 0; _i2 < arguments.length; _i2++) {
          args[_i2] = arguments[_i2];
        }
        if (!called) {
          called = true;
          r3 = f2.apply(null, args);
        }
        return r3;
      };
    };
    var DeviceType = function(os, browser, userAgent, mediaMatch2) {
      var isiPad = os.isiOS() && /ipad/i.test(userAgent) === true;
      var isiPhone = os.isiOS() && !isiPad;
      var isMobile = os.isiOS() || os.isAndroid();
      var isTouch2 = isMobile || mediaMatch2("(pointer:coarse)");
      var isTablet = isiPad || !isiPhone && isMobile && mediaMatch2("(min-device-width:768px)");
      var isPhone = isiPhone || isMobile && !isTablet;
      var iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false;
      var isDesktop = !isPhone && !isTablet && !iOSwebview;
      return {
        isiPad: constant$1(isiPad),
        isiPhone: constant$1(isiPhone),
        isTablet: constant$1(isTablet),
        isPhone: constant$1(isPhone),
        isTouch: constant$1(isTouch2),
        isAndroid: os.isAndroid,
        isiOS: os.isiOS,
        isWebView: constant$1(iOSwebview),
        isDesktop: constant$1(isDesktop)
      };
    };
    var firstMatch = function(regexes, s2) {
      for (var i2 = 0; i2 < regexes.length; i2++) {
        var x2 = regexes[i2];
        if (x2.test(s2)) {
          return x2;
        }
      }
      return void 0;
    };
    var find$3 = function(regexes, agent) {
      var r3 = firstMatch(regexes, agent);
      if (!r3) {
        return {
          major: 0,
          minor: 0
        };
      }
      var group2 = function(i2) {
        return Number(agent.replace(r3, "$" + i2));
      };
      return nu$d(group2(1), group2(2));
    };
    var detect$4 = function(versionRegexes, agent) {
      var cleanedAgent = String(agent).toLowerCase();
      if (versionRegexes.length === 0) {
        return unknown$3();
      }
      return find$3(versionRegexes, cleanedAgent);
    };
    var unknown$3 = function() {
      return nu$d(0, 0);
    };
    var nu$d = function(major, minor) {
      return {
        major,
        minor
      };
    };
    var Version = {
      nu: nu$d,
      detect: detect$4,
      unknown: unknown$3
    };
    var detectBrowser$1 = function(browsers2, userAgentData) {
      return findMap(userAgentData.brands, function(uaBrand) {
        var lcBrand = uaBrand.brand.toLowerCase();
        return find$5(browsers2, function(browser) {
          var _a2;
          return lcBrand === ((_a2 = browser.brand) === null || _a2 === void 0 ? void 0 : _a2.toLowerCase());
        }).map(function(info) {
          return {
            current: info.name,
            version: Version.nu(parseInt(uaBrand.version, 10), 0)
          };
        });
      });
    };
    var detect$3 = function(candidates, userAgent) {
      var agent = String(userAgent).toLowerCase();
      return find$5(candidates, function(candidate) {
        return candidate.search(agent);
      });
    };
    var detectBrowser = function(browsers2, userAgent) {
      return detect$3(browsers2, userAgent).map(function(browser) {
        var version2 = Version.detect(browser.versionRegexes, userAgent);
        return {
          current: browser.name,
          version: version2
        };
      });
    };
    var detectOs = function(oses2, userAgent) {
      return detect$3(oses2, userAgent).map(function(os) {
        var version2 = Version.detect(os.versionRegexes, userAgent);
        return {
          current: os.name,
          version: version2
        };
      });
    };
    var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/;
    var checkContains = function(target) {
      return function(uastring) {
        return contains$1(uastring, target);
      };
    };
    var browsers = [
      {
        name: "Edge",
        versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],
        search: function(uastring) {
          return contains$1(uastring, "edge/") && contains$1(uastring, "chrome") && contains$1(uastring, "safari") && contains$1(uastring, "applewebkit");
        }
      },
      {
        name: "Chrome",
        brand: "Chromium",
        versionRegexes: [
          /.*?chrome\/([0-9]+)\.([0-9]+).*/,
          normalVersionRegex
        ],
        search: function(uastring) {
          return contains$1(uastring, "chrome") && !contains$1(uastring, "chromeframe");
        }
      },
      {
        name: "IE",
        versionRegexes: [
          /.*?msie\ ?([0-9]+)\.([0-9]+).*/,
          /.*?rv:([0-9]+)\.([0-9]+).*/
        ],
        search: function(uastring) {
          return contains$1(uastring, "msie") || contains$1(uastring, "trident");
        }
      },
      {
        name: "Opera",
        versionRegexes: [
          normalVersionRegex,
          /.*?opera\/([0-9]+)\.([0-9]+).*/
        ],
        search: checkContains("opera")
      },
      {
        name: "Firefox",
        versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],
        search: checkContains("firefox")
      },
      {
        name: "Safari",
        versionRegexes: [
          normalVersionRegex,
          /.*?cpu os ([0-9]+)_([0-9]+).*/
        ],
        search: function(uastring) {
          return (contains$1(uastring, "safari") || contains$1(uastring, "mobile/")) && contains$1(uastring, "applewebkit");
        }
      }
    ];
    var oses = [
      {
        name: "Windows",
        search: checkContains("win"),
        versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]
      },
      {
        name: "iOS",
        search: function(uastring) {
          return contains$1(uastring, "iphone") || contains$1(uastring, "ipad");
        },
        versionRegexes: [
          /.*?version\/\ ?([0-9]+)\.([0-9]+).*/,
          /.*cpu os ([0-9]+)_([0-9]+).*/,
          /.*cpu iphone os ([0-9]+)_([0-9]+).*/
        ]
      },
      {
        name: "Android",
        search: checkContains("android"),
        versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/]
      },
      {
        name: "OSX",
        search: checkContains("mac os x"),
        versionRegexes: [/.*?mac\ os\ x\ ?([0-9]+)_([0-9]+).*/]
      },
      {
        name: "Linux",
        search: checkContains("linux"),
        versionRegexes: []
      },
      {
        name: "Solaris",
        search: checkContains("sunos"),
        versionRegexes: []
      },
      {
        name: "FreeBSD",
        search: checkContains("freebsd"),
        versionRegexes: []
      },
      {
        name: "ChromeOS",
        search: checkContains("cros"),
        versionRegexes: [/.*?chrome\/([0-9]+)\.([0-9]+).*/]
      }
    ];
    var PlatformInfo = {
      browsers: constant$1(browsers),
      oses: constant$1(oses)
    };
    var edge = "Edge";
    var chrome = "Chrome";
    var ie2 = "IE";
    var opera = "Opera";
    var firefox = "Firefox";
    var safari = "Safari";
    var unknown$2 = function() {
      return nu$c({
        current: void 0,
        version: Version.unknown()
      });
    };
    var nu$c = function(info) {
      var current = info.current;
      var version2 = info.version;
      var isBrowser = function(name2) {
        return function() {
          return current === name2;
        };
      };
      return {
        current,
        version: version2,
        isEdge: isBrowser(edge),
        isChrome: isBrowser(chrome),
        isIE: isBrowser(ie2),
        isOpera: isBrowser(opera),
        isFirefox: isBrowser(firefox),
        isSafari: isBrowser(safari)
      };
    };
    var Browser = {
      unknown: unknown$2,
      nu: nu$c,
      edge: constant$1(edge),
      chrome: constant$1(chrome),
      ie: constant$1(ie2),
      opera: constant$1(opera),
      firefox: constant$1(firefox),
      safari: constant$1(safari)
    };
    var windows = "Windows";
    var ios = "iOS";
    var android = "Android";
    var linux = "Linux";
    var osx = "OSX";
    var solaris = "Solaris";
    var freebsd = "FreeBSD";
    var chromeos = "ChromeOS";
    var unknown$1 = function() {
      return nu$b({
        current: void 0,
        version: Version.unknown()
      });
    };
    var nu$b = function(info) {
      var current = info.current;
      var version2 = info.version;
      var isOS = function(name2) {
        return function() {
          return current === name2;
        };
      };
      return {
        current,
        version: version2,
        isWindows: isOS(windows),
        isiOS: isOS(ios),
        isAndroid: isOS(android),
        isOSX: isOS(osx),
        isLinux: isOS(linux),
        isSolaris: isOS(solaris),
        isFreeBSD: isOS(freebsd),
        isChromeOS: isOS(chromeos)
      };
    };
    var OperatingSystem = {
      unknown: unknown$1,
      nu: nu$b,
      windows: constant$1(windows),
      ios: constant$1(ios),
      android: constant$1(android),
      linux: constant$1(linux),
      osx: constant$1(osx),
      solaris: constant$1(solaris),
      freebsd: constant$1(freebsd),
      chromeos: constant$1(chromeos)
    };
    var detect$2 = function(userAgent, userAgentDataOpt, mediaMatch2) {
      var browsers2 = PlatformInfo.browsers();
      var oses2 = PlatformInfo.oses();
      var browser = userAgentDataOpt.bind(function(userAgentData) {
        return detectBrowser$1(browsers2, userAgentData);
      }).orThunk(function() {
        return detectBrowser(browsers2, userAgent);
      }).fold(Browser.unknown, Browser.nu);
      var os = detectOs(oses2, userAgent).fold(OperatingSystem.unknown, OperatingSystem.nu);
      var deviceType = DeviceType(os, browser, userAgent, mediaMatch2);
      return {
        browser,
        os,
        deviceType
      };
    };
    var PlatformDetection = { detect: detect$2 };
    var mediaMatch = function(query2) {
      return window.matchMedia(query2).matches;
    };
    var platform = cached(function() {
      return PlatformDetection.detect(navigator.userAgent, Optional.from(navigator.userAgentData), mediaMatch);
    });
    var detect$1 = function() {
      return platform();
    };
    var compareDocumentPosition = function(a2, b3, match2) {
      return (a2.compareDocumentPosition(b3) & match2) !== 0;
    };
    var documentPositionContainedBy = function(a2, b3) {
      return compareDocumentPosition(a2, b3, Node.DOCUMENT_POSITION_CONTAINED_BY);
    };
    var is = function(element2, selector) {
      var dom2 = element2.dom;
      if (dom2.nodeType !== ELEMENT) {
        return false;
      } else {
        var elem = dom2;
        if (elem.matches !== void 0) {
          return elem.matches(selector);
        } else if (elem.msMatchesSelector !== void 0) {
          return elem.msMatchesSelector(selector);
        } else if (elem.webkitMatchesSelector !== void 0) {
          return elem.webkitMatchesSelector(selector);
        } else if (elem.mozMatchesSelector !== void 0) {
          return elem.mozMatchesSelector(selector);
        } else {
          throw new Error("Browser lacks native selectors");
        }
      }
    };
    var bypassSelector = function(dom2) {
      return dom2.nodeType !== ELEMENT && dom2.nodeType !== DOCUMENT && dom2.nodeType !== DOCUMENT_FRAGMENT || dom2.childElementCount === 0;
    };
    var all$3 = function(selector, scope) {
      var base2 = scope === void 0 ? document : scope.dom;
      return bypassSelector(base2) ? [] : map$2(base2.querySelectorAll(selector), SugarElement.fromDom);
    };
    var one = function(selector, scope) {
      var base2 = scope === void 0 ? document : scope.dom;
      return bypassSelector(base2) ? Optional.none() : Optional.from(base2.querySelector(selector)).map(SugarElement.fromDom);
    };
    var eq2 = function(e1, e2) {
      return e1.dom === e2.dom;
    };
    var regularContains = function(e1, e2) {
      var d1 = e1.dom;
      var d2 = e2.dom;
      return d1 === d2 ? false : d1.contains(d2);
    };
    var ieContains = function(e1, e2) {
      return documentPositionContainedBy(e1.dom, e2.dom);
    };
    var contains2 = function(e1, e2) {
      return detect$1().browser.isIE() ? ieContains(e1, e2) : regularContains(e1, e2);
    };
    var owner$4 = function(element2) {
      return SugarElement.fromDom(element2.dom.ownerDocument);
    };
    var documentOrOwner = function(dos) {
      return isDocument(dos) ? dos : owner$4(dos);
    };
    var documentElement = function(element2) {
      return SugarElement.fromDom(documentOrOwner(element2).dom.documentElement);
    };
    var defaultView = function(element2) {
      return SugarElement.fromDom(documentOrOwner(element2).dom.defaultView);
    };
    var parent = function(element2) {
      return Optional.from(element2.dom.parentNode).map(SugarElement.fromDom);
    };
    var parentNode = function(element2) {
      return parent(element2);
    };
    var offsetParent = function(element2) {
      return Optional.from(element2.dom.offsetParent).map(SugarElement.fromDom);
    };
    var nextSibling = function(element2) {
      return Optional.from(element2.dom.nextSibling).map(SugarElement.fromDom);
    };
    var children = function(element2) {
      return map$2(element2.dom.childNodes, SugarElement.fromDom);
    };
    var child$2 = function(element2, index) {
      var cs = element2.dom.childNodes;
      return Optional.from(cs[index]).map(SugarElement.fromDom);
    };
    var firstChild = function(element2) {
      return child$2(element2, 0);
    };
    var spot = function(element2, offset3) {
      return {
        element: element2,
        offset: offset3
      };
    };
    var leaf = function(element2, offset3) {
      var cs = children(element2);
      return cs.length > 0 && offset3 < cs.length ? spot(cs[offset3], 0) : spot(element2, offset3);
    };
    var isShadowRoot2 = function(dos) {
      return isDocumentFragment(dos) && isNonNullable(dos.dom.host);
    };
    var supported = isFunction2(Element.prototype.attachShadow) && isFunction2(Node.prototype.getRootNode);
    var isSupported = constant$1(supported);
    var getRootNode = supported ? function(e2) {
      return SugarElement.fromDom(e2.dom.getRootNode());
    } : documentOrOwner;
    var getContentContainer = function(dos) {
      return isShadowRoot2(dos) ? dos : SugarElement.fromDom(documentOrOwner(dos).dom.body);
    };
    var isInShadowRoot = function(e2) {
      return getShadowRoot(e2).isSome();
    };
    var getShadowRoot = function(e2) {
      var r3 = getRootNode(e2);
      return isShadowRoot2(r3) ? Optional.some(r3) : Optional.none();
    };
    var getShadowHost = function(e2) {
      return SugarElement.fromDom(e2.dom.host);
    };
    var getOriginalEventTarget = function(event) {
      if (isSupported() && isNonNullable(event.target)) {
        var el = SugarElement.fromDom(event.target);
        if (isElement$2(el) && isOpenShadowHost(el)) {
          if (event.composed && event.composedPath) {
            var composedPath = event.composedPath();
            if (composedPath) {
              return head(composedPath);
            }
          }
        }
      }
      return Optional.from(event.target);
    };
    var isOpenShadowHost = function(element2) {
      return isNonNullable(element2.dom.shadowRoot);
    };
    var inBody = function(element2) {
      var dom2 = isText$1(element2) ? element2.dom.parentNode : element2.dom;
      if (dom2 === void 0 || dom2 === null || dom2.ownerDocument === null) {
        return false;
      }
      var doc = dom2.ownerDocument;
      return getShadowRoot(SugarElement.fromDom(dom2)).fold(function() {
        return doc.body.contains(dom2);
      }, compose1(inBody, getShadowHost));
    };
    var body = function() {
      return getBody(SugarElement.fromDom(document));
    };
    var getBody = function(doc) {
      var b3 = doc.dom.body;
      if (b3 === null || b3 === void 0) {
        throw new Error("Body is not available yet");
      }
      return SugarElement.fromDom(b3);
    };
    var rawSet = function(dom2, key, value2) {
      if (isString(value2) || isBoolean(value2) || isNumber2(value2)) {
        dom2.setAttribute(key, value2 + "");
      } else {
        console.error("Invalid call to Attribute.set. Key ", key, ":: Value ", value2, ":: Element ", dom2);
        throw new Error("Attribute value was not simple");
      }
    };
    var set$8 = function(element2, key, value2) {
      rawSet(element2.dom, key, value2);
    };
    var setAll$1 = function(element2, attrs) {
      var dom2 = element2.dom;
      each2(attrs, function(v2, k2) {
        rawSet(dom2, k2, v2);
      });
    };
    var get$d = function(element2, key) {
      var v2 = element2.dom.getAttribute(key);
      return v2 === null ? void 0 : v2;
    };
    var getOpt = function(element2, key) {
      return Optional.from(get$d(element2, key));
    };
    var has$1 = function(element2, key) {
      var dom2 = element2.dom;
      return dom2 && dom2.hasAttribute ? dom2.hasAttribute(key) : false;
    };
    var remove$7 = function(element2, key) {
      element2.dom.removeAttribute(key);
    };
    var internalSet = function(dom2, property, value2) {
      if (!isString(value2)) {
        console.error("Invalid call to CSS.set. Property ", property, ":: Value ", value2, ":: Element ", dom2);
        throw new Error("CSS value must be a string: " + value2);
      }
      if (isSupported$1(dom2)) {
        dom2.style.setProperty(property, value2);
      }
    };
    var internalRemove = function(dom2, property) {
      if (isSupported$1(dom2)) {
        dom2.style.removeProperty(property);
      }
    };
    var set$7 = function(element2, property, value2) {
      var dom2 = element2.dom;
      internalSet(dom2, property, value2);
    };
    var setAll = function(element2, css) {
      var dom2 = element2.dom;
      each2(css, function(v2, k2) {
        internalSet(dom2, k2, v2);
      });
    };
    var setOptions = function(element2, css) {
      var dom2 = element2.dom;
      each2(css, function(v2, k2) {
        v2.fold(function() {
          internalRemove(dom2, k2);
        }, function(value2) {
          internalSet(dom2, k2, value2);
        });
      });
    };
    var get$c = function(element2, property) {
      var dom2 = element2.dom;
      var styles = window.getComputedStyle(dom2);
      var r3 = styles.getPropertyValue(property);
      return r3 === "" && !inBody(element2) ? getUnsafeProperty(dom2, property) : r3;
    };
    var getUnsafeProperty = function(dom2, property) {
      return isSupported$1(dom2) ? dom2.style.getPropertyValue(property) : "";
    };
    var getRaw = function(element2, property) {
      var dom2 = element2.dom;
      var raw = getUnsafeProperty(dom2, property);
      return Optional.from(raw).filter(function(r3) {
        return r3.length > 0;
      });
    };
    var getAllRaw = function(element2) {
      var css = {};
      var dom2 = element2.dom;
      if (isSupported$1(dom2)) {
        for (var i2 = 0; i2 < dom2.style.length; i2++) {
          var ruleName = dom2.style.item(i2);
          css[ruleName] = dom2.style[ruleName];
        }
      }
      return css;
    };
    var isValidValue = function(tag, property, value2) {
      var element2 = SugarElement.fromTag(tag);
      set$7(element2, property, value2);
      var style = getRaw(element2, property);
      return style.isSome();
    };
    var remove$6 = function(element2, property) {
      var dom2 = element2.dom;
      internalRemove(dom2, property);
      if (is$1(getOpt(element2, "style").map(trim$1), "")) {
        remove$7(element2, "style");
      }
    };
    var reflow2 = function(e2) {
      return e2.dom.offsetWidth;
    };
    var Dimension = function(name2, getOffset2) {
      var set3 = function(element2, h3) {
        if (!isNumber2(h3) && !h3.match(/^[0-9]+$/)) {
          throw new Error(name2 + ".set accepts only positive integer values. Value was " + h3);
        }
        var dom2 = element2.dom;
        if (isSupported$1(dom2)) {
          dom2.style[name2] = h3 + "px";
        }
      };
      var get2 = function(element2) {
        var r3 = getOffset2(element2);
        if (r3 <= 0 || r3 === null) {
          var css = get$c(element2, name2);
          return parseFloat(css) || 0;
        }
        return r3;
      };
      var getOuter2 = get2;
      var aggregate = function(element2, properties2) {
        return foldl(properties2, function(acc, property) {
          var val = get$c(element2, property);
          var value2 = val === void 0 ? 0 : parseInt(val, 10);
          return isNaN(value2) ? acc : acc + value2;
        }, 0);
      };
      var max3 = function(element2, value2, properties2) {
        var cumulativeInclusions = aggregate(element2, properties2);
        var absoluteMax = value2 > cumulativeInclusions ? value2 - cumulativeInclusions : 0;
        return absoluteMax;
      };
      return {
        set: set3,
        get: get2,
        getOuter: getOuter2,
        aggregate,
        max: max3
      };
    };
    var api$3 = Dimension("height", function(element2) {
      var dom2 = element2.dom;
      return inBody(element2) ? dom2.getBoundingClientRect().height : dom2.offsetHeight;
    });
    var get$b = function(element2) {
      return api$3.get(element2);
    };
    var getOuter$2 = function(element2) {
      return api$3.getOuter(element2);
    };
    var setMax$1 = function(element2, value2) {
      var inclusions = [
        "margin-top",
        "border-top-width",
        "padding-top",
        "padding-bottom",
        "border-bottom-width",
        "margin-bottom"
      ];
      var absMax = api$3.max(element2, value2, inclusions);
      set$7(element2, "max-height", absMax + "px");
    };
    var r$1 = function(left3, top3) {
      var translate2 = function(x2, y2) {
        return r$1(left3 + x2, top3 + y2);
      };
      return {
        left: left3,
        top: top3,
        translate: translate2
      };
    };
    var SugarPosition = r$1;
    var boxPosition = function(dom2) {
      var box2 = dom2.getBoundingClientRect();
      return SugarPosition(box2.left, box2.top);
    };
    var firstDefinedOrZero = function(a2, b3) {
      if (a2 !== void 0) {
        return a2;
      } else {
        return b3 !== void 0 ? b3 : 0;
      }
    };
    var absolute$3 = function(element2) {
      var doc = element2.dom.ownerDocument;
      var body2 = doc.body;
      var win2 = doc.defaultView;
      var html = doc.documentElement;
      if (body2 === element2.dom) {
        return SugarPosition(body2.offsetLeft, body2.offsetTop);
      }
      var scrollTop = firstDefinedOrZero(win2 === null || win2 === void 0 ? void 0 : win2.pageYOffset, html.scrollTop);
      var scrollLeft = firstDefinedOrZero(win2 === null || win2 === void 0 ? void 0 : win2.pageXOffset, html.scrollLeft);
      var clientTop = firstDefinedOrZero(html.clientTop, body2.clientTop);
      var clientLeft = firstDefinedOrZero(html.clientLeft, body2.clientLeft);
      return viewport$1(element2).translate(scrollLeft - clientLeft, scrollTop - clientTop);
    };
    var viewport$1 = function(element2) {
      var dom2 = element2.dom;
      var doc = dom2.ownerDocument;
      var body2 = doc.body;
      if (body2 === dom2) {
        return SugarPosition(body2.offsetLeft, body2.offsetTop);
      }
      if (!inBody(element2)) {
        return SugarPosition(0, 0);
      }
      return boxPosition(dom2);
    };
    var api$2 = Dimension("width", function(element2) {
      return element2.dom.offsetWidth;
    });
    var set$6 = function(element2, h3) {
      return api$2.set(element2, h3);
    };
    var get$a = function(element2) {
      return api$2.get(element2);
    };
    var getOuter$1 = function(element2) {
      return api$2.getOuter(element2);
    };
    var setMax = function(element2, value2) {
      var inclusions = [
        "margin-left",
        "border-left-width",
        "padding-left",
        "padding-right",
        "border-right-width",
        "margin-right"
      ];
      var absMax = api$2.max(element2, value2, inclusions);
      set$7(element2, "max-width", absMax + "px");
    };
    var mkEvent = function(target, x2, y2, stop2, prevent, kill, raw) {
      return {
        target,
        x: x2,
        y: y2,
        stop: stop2,
        prevent,
        kill,
        raw
      };
    };
    var fromRawEvent$1 = function(rawEvent) {
      var target = SugarElement.fromDom(getOriginalEventTarget(rawEvent).getOr(rawEvent.target));
      var stop2 = function() {
        return rawEvent.stopPropagation();
      };
      var prevent = function() {
        return rawEvent.preventDefault();
      };
      var kill = compose(prevent, stop2);
      return mkEvent(target, rawEvent.clientX, rawEvent.clientY, stop2, prevent, kill, rawEvent);
    };
    var handle = function(filter2, handler) {
      return function(rawEvent) {
        if (filter2(rawEvent)) {
          handler(fromRawEvent$1(rawEvent));
        }
      };
    };
    var binder = function(element2, event, filter2, handler, useCapture) {
      var wrapped = handle(filter2, handler);
      element2.dom.addEventListener(event, wrapped, useCapture);
      return { unbind: curry(unbind, element2, event, wrapped, useCapture) };
    };
    var bind$2 = function(element2, event, filter2, handler) {
      return binder(element2, event, filter2, handler, false);
    };
    var capture$1 = function(element2, event, filter2, handler) {
      return binder(element2, event, filter2, handler, true);
    };
    var unbind = function(element2, event, handler, useCapture) {
      element2.dom.removeEventListener(event, handler, useCapture);
    };
    var before$2 = function(marker, element2) {
      var parent$1 = parent(marker);
      parent$1.each(function(v2) {
        v2.dom.insertBefore(element2.dom, marker.dom);
      });
    };
    var after$2 = function(marker, element2) {
      var sibling = nextSibling(marker);
      sibling.fold(function() {
        var parent$1 = parent(marker);
        parent$1.each(function(v2) {
          append$2(v2, element2);
        });
      }, function(v2) {
        before$2(v2, element2);
      });
    };
    var prepend$1 = function(parent2, element2) {
      var firstChild$1 = firstChild(parent2);
      firstChild$1.fold(function() {
        append$2(parent2, element2);
      }, function(v2) {
        parent2.dom.insertBefore(element2.dom, v2.dom);
      });
    };
    var append$2 = function(parent2, element2) {
      parent2.dom.appendChild(element2.dom);
    };
    var appendAt = function(parent2, element2, index) {
      child$2(parent2, index).fold(function() {
        append$2(parent2, element2);
      }, function(v2) {
        before$2(v2, element2);
      });
    };
    var before$1 = function(marker, elements2) {
      each$1(elements2, function(x2) {
        before$2(marker, x2);
      });
    };
    var append$1 = function(parent2, elements2) {
      each$1(elements2, function(x2) {
        append$2(parent2, x2);
      });
    };
    var empty = function(element2) {
      element2.dom.textContent = "";
      each$1(children(element2), function(rogue) {
        remove$5(rogue);
      });
    };
    var remove$5 = function(element2) {
      var dom2 = element2.dom;
      if (dom2.parentNode !== null) {
        dom2.parentNode.removeChild(dom2);
      }
    };
    var unwrap = function(wrapper) {
      var children$1 = children(wrapper);
      if (children$1.length > 0) {
        before$1(wrapper, children$1);
      }
      remove$5(wrapper);
    };
    var get$9 = function(_DOC) {
      var doc = _DOC !== void 0 ? _DOC.dom : document;
      var x2 = doc.body.scrollLeft || doc.documentElement.scrollLeft;
      var y2 = doc.body.scrollTop || doc.documentElement.scrollTop;
      return SugarPosition(x2, y2);
    };
    var to = function(x2, y2, _DOC) {
      var doc = _DOC !== void 0 ? _DOC.dom : document;
      var win2 = doc.defaultView;
      if (win2) {
        win2.scrollTo(x2, y2);
      }
    };
    var get$8 = function(_win) {
      var win2 = _win === void 0 ? window : _win;
      if (detect$1().browser.isFirefox()) {
        return Optional.none();
      } else {
        return Optional.from(win2["visualViewport"]);
      }
    };
    var bounds$1 = function(x2, y2, width2, height2) {
      return {
        x: x2,
        y: y2,
        width: width2,
        height: height2,
        right: x2 + width2,
        bottom: y2 + height2
      };
    };
    var getBounds$3 = function(_win) {
      var win2 = _win === void 0 ? window : _win;
      var doc = win2.document;
      var scroll = get$9(SugarElement.fromDom(doc));
      return get$8(win2).fold(function() {
        var html = win2.document.documentElement;
        var width2 = html.clientWidth;
        var height2 = html.clientHeight;
        return bounds$1(scroll.left, scroll.top, width2, height2);
      }, function(visualViewport) {
        return bounds$1(Math.max(visualViewport.pageLeft, scroll.left), Math.max(visualViewport.pageTop, scroll.top), visualViewport.width, visualViewport.height);
      });
    };
    var walkUp = function(navigation, doc) {
      var frame = navigation.view(doc);
      return frame.fold(constant$1([]), function(f2) {
        var parent2 = navigation.owner(f2);
        var rest = walkUp(navigation, parent2);
        return [f2].concat(rest);
      });
    };
    var pathTo = function(element2, navigation) {
      var d2 = navigation.owner(element2);
      var paths = walkUp(navigation, d2);
      return Optional.some(paths);
    };
    var view = function(doc) {
      var _a2;
      var element2 = doc.dom === document ? Optional.none() : Optional.from((_a2 = doc.dom.defaultView) === null || _a2 === void 0 ? void 0 : _a2.frameElement);
      return element2.map(SugarElement.fromDom);
    };
    var owner$3 = function(element2) {
      return owner$4(element2);
    };
    var Navigation = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      view,
      owner: owner$3
    });
    var find$2 = function(element2) {
      var doc = SugarElement.fromDom(document);
      var scroll = get$9(doc);
      var path2 = pathTo(element2, Navigation);
      return path2.fold(curry(absolute$3, element2), function(frames) {
        var offset3 = viewport$1(element2);
        var r3 = foldr(frames, function(b3, a2) {
          var loc = viewport$1(a2);
          return {
            left: b3.left + loc.left,
            top: b3.top + loc.top
          };
        }, {
          left: 0,
          top: 0
        });
        return SugarPosition(r3.left + offset3.left + scroll.left, r3.top + offset3.top + scroll.top);
      });
    };
    var pointed = function(point2, width2, height2) {
      return {
        point: point2,
        width: width2,
        height: height2
      };
    };
    var rect = function(x2, y2, width2, height2) {
      return {
        x: x2,
        y: y2,
        width: width2,
        height: height2
      };
    };
    var bounds = function(x2, y2, width2, height2) {
      return {
        x: x2,
        y: y2,
        width: width2,
        height: height2,
        right: x2 + width2,
        bottom: y2 + height2
      };
    };
    var box$1 = function(element2) {
      var xy = absolute$3(element2);
      var w2 = getOuter$1(element2);
      var h3 = getOuter$2(element2);
      return bounds(xy.left, xy.top, w2, h3);
    };
    var absolute$2 = function(element2) {
      var position2 = find$2(element2);
      var width2 = getOuter$1(element2);
      var height2 = getOuter$2(element2);
      return bounds(position2.left, position2.top, width2, height2);
    };
    var win = function() {
      return getBounds$3(window);
    };
    var value$3 = function(o2) {
      var or = function(_opt) {
        return value$3(o2);
      };
      var orThunk = function(_f) {
        return value$3(o2);
      };
      var map4 = function(f2) {
        return value$3(f2(o2));
      };
      var mapError2 = function(_f) {
        return value$3(o2);
      };
      var each3 = function(f2) {
        f2(o2);
      };
      var bind2 = function(f2) {
        return f2(o2);
      };
      var fold2 = function(_2, onValue) {
        return onValue(o2);
      };
      var exists2 = function(f2) {
        return f2(o2);
      };
      var forall2 = function(f2) {
        return f2(o2);
      };
      var toOptional = function() {
        return Optional.some(o2);
      };
      return {
        isValue: always,
        isError: never,
        getOr: constant$1(o2),
        getOrThunk: constant$1(o2),
        getOrDie: constant$1(o2),
        or,
        orThunk,
        fold: fold2,
        map: map4,
        mapError: mapError2,
        each: each3,
        bind: bind2,
        exists: exists2,
        forall: forall2,
        toOptional
      };
    };
    var error$1 = function(message) {
      var getOrThunk = function(f2) {
        return f2();
      };
      var getOrDie2 = function() {
        return die(String(message))();
      };
      var or = identity$1;
      var orThunk = function(f2) {
        return f2();
      };
      var map4 = function(_f) {
        return error$1(message);
      };
      var mapError2 = function(f2) {
        return error$1(f2(message));
      };
      var bind2 = function(_f) {
        return error$1(message);
      };
      var fold2 = function(onError, _2) {
        return onError(message);
      };
      return {
        isValue: never,
        isError: always,
        getOr: identity$1,
        getOrThunk,
        getOrDie: getOrDie2,
        or,
        orThunk,
        fold: fold2,
        map: map4,
        mapError: mapError2,
        each: noop3,
        bind: bind2,
        exists: never,
        forall: always,
        toOptional: Optional.none
      };
    };
    var fromOption = function(opt, err) {
      return opt.fold(function() {
        return error$1(err);
      }, value$3);
    };
    var Result = {
      value: value$3,
      error: error$1,
      fromOption
    };
    var SimpleResultType;
    (function(SimpleResultType2) {
      SimpleResultType2[SimpleResultType2["Error"] = 0] = "Error";
      SimpleResultType2[SimpleResultType2["Value"] = 1] = "Value";
    })(SimpleResultType || (SimpleResultType = {}));
    var fold$1 = function(res, onError, onValue) {
      return res.stype === SimpleResultType.Error ? onError(res.serror) : onValue(res.svalue);
    };
    var partition$2 = function(results) {
      var values2 = [];
      var errors = [];
      each$1(results, function(obj) {
        fold$1(obj, function(err) {
          return errors.push(err);
        }, function(val) {
          return values2.push(val);
        });
      });
      return {
        values: values2,
        errors
      };
    };
    var mapError = function(res, f2) {
      if (res.stype === SimpleResultType.Error) {
        return {
          stype: SimpleResultType.Error,
          serror: f2(res.serror)
        };
      } else {
        return res;
      }
    };
    var map3 = function(res, f2) {
      if (res.stype === SimpleResultType.Value) {
        return {
          stype: SimpleResultType.Value,
          svalue: f2(res.svalue)
        };
      } else {
        return res;
      }
    };
    var bind$1 = function(res, f2) {
      if (res.stype === SimpleResultType.Value) {
        return f2(res.svalue);
      } else {
        return res;
      }
    };
    var bindError = function(res, f2) {
      if (res.stype === SimpleResultType.Error) {
        return f2(res.serror);
      } else {
        return res;
      }
    };
    var svalue = function(v2) {
      return {
        stype: SimpleResultType.Value,
        svalue: v2
      };
    };
    var serror = function(e2) {
      return {
        stype: SimpleResultType.Error,
        serror: e2
      };
    };
    var toResult$1 = function(res) {
      return fold$1(res, Result.error, Result.value);
    };
    var fromResult$1 = function(res) {
      return res.fold(serror, svalue);
    };
    var SimpleResult = {
      fromResult: fromResult$1,
      toResult: toResult$1,
      svalue,
      partition: partition$2,
      serror,
      bind: bind$1,
      bindError,
      map: map3,
      mapError,
      fold: fold$1
    };
    var field$2 = function(key, newKey, presence, prop) {
      return {
        tag: "field",
        key,
        newKey,
        presence,
        prop
      };
    };
    var customField$1 = function(newKey, instantiator) {
      return {
        tag: "custom",
        newKey,
        instantiator
      };
    };
    var fold = function(value2, ifField, ifCustom) {
      switch (value2.tag) {
        case "field":
          return ifField(value2.key, value2.newKey, value2.presence, value2.prop);
        case "custom":
          return ifCustom(value2.newKey, value2.instantiator);
      }
    };
    var shallow$1 = function(old, nu2) {
      return nu2;
    };
    var deep = function(old, nu2) {
      var bothObjects = isObject2(old) && isObject2(nu2);
      return bothObjects ? deepMerge(old, nu2) : nu2;
    };
    var baseMerge = function(merger) {
      return function() {
        var objects = [];
        for (var _i2 = 0; _i2 < arguments.length; _i2++) {
          objects[_i2] = arguments[_i2];
        }
        if (objects.length === 0) {
          throw new Error("Can't merge zero objects");
        }
        var ret = {};
        for (var j2 = 0; j2 < objects.length; j2++) {
          var curObject = objects[j2];
          for (var key in curObject) {
            if (has$2(curObject, key)) {
              ret[key] = merger(ret[key], curObject[key]);
            }
          }
        }
        return ret;
      };
    };
    var deepMerge = baseMerge(deep);
    var merge$1 = baseMerge(shallow$1);
    var required$2 = function() {
      return {
        tag: "required",
        process: {}
      };
    };
    var defaultedThunk = function(fallbackThunk) {
      return {
        tag: "defaultedThunk",
        process: fallbackThunk
      };
    };
    var defaulted$1 = function(fallback2) {
      return defaultedThunk(constant$1(fallback2));
    };
    var asOption = function() {
      return {
        tag: "option",
        process: {}
      };
    };
    var mergeWithThunk = function(baseThunk) {
      return {
        tag: "mergeWithThunk",
        process: baseThunk
      };
    };
    var mergeWith = function(base2) {
      return mergeWithThunk(constant$1(base2));
    };
    var mergeValues$1 = function(values2, base2) {
      return values2.length > 0 ? SimpleResult.svalue(deepMerge(base2, merge$1.apply(void 0, values2))) : SimpleResult.svalue(base2);
    };
    var mergeErrors$1 = function(errors) {
      return compose(SimpleResult.serror, flatten)(errors);
    };
    var consolidateObj = function(objects, base2) {
      var partition2 = SimpleResult.partition(objects);
      return partition2.errors.length > 0 ? mergeErrors$1(partition2.errors) : mergeValues$1(partition2.values, base2);
    };
    var consolidateArr = function(objects) {
      var partitions = SimpleResult.partition(objects);
      return partitions.errors.length > 0 ? mergeErrors$1(partitions.errors) : SimpleResult.svalue(partitions.values);
    };
    var ResultCombine = {
      consolidateObj,
      consolidateArr
    };
    var formatObj = function(input2) {
      return isObject2(input2) && keys(input2).length > 100 ? " removed due to size" : JSON.stringify(input2, null, 2);
    };
    var formatErrors = function(errors) {
      var es = errors.length > 10 ? errors.slice(0, 10).concat([{
        path: [],
        getErrorInfo: constant$1("... (only showing first ten failures)")
      }]) : errors;
      return map$2(es, function(e2) {
        return "Failed path: (" + e2.path.join(" > ") + ")\n" + e2.getErrorInfo();
      });
    };
    var nu$a = function(path2, getErrorInfo) {
      return SimpleResult.serror([{
        path: path2,
        getErrorInfo
      }]);
    };
    var missingRequired = function(path2, key, obj) {
      return nu$a(path2, function() {
        return 'Could not find valid *required* value for "' + key + '" in ' + formatObj(obj);
      });
    };
    var missingKey = function(path2, key) {
      return nu$a(path2, function() {
        return 'Choice schema did not contain choice key: "' + key + '"';
      });
    };
    var missingBranch = function(path2, branches, branch) {
      return nu$a(path2, function() {
        return 'The chosen schema: "' + branch + '" did not exist in branches: ' + formatObj(branches);
      });
    };
    var unsupportedFields = function(path2, unsupported) {
      return nu$a(path2, function() {
        return "There are unsupported fields: [" + unsupported.join(", ") + "] specified";
      });
    };
    var custom = function(path2, err) {
      return nu$a(path2, constant$1(err));
    };
    var value$2 = function(validator) {
      var extract2 = function(path2, val) {
        return SimpleResult.bindError(validator(val), function(err) {
          return custom(path2, err);
        });
      };
      var toString2 = constant$1("val");
      return {
        extract: extract2,
        toString: toString2
      };
    };
    var anyValue$1 = value$2(SimpleResult.svalue);
    var requiredAccess = function(path2, obj, key, bundle) {
      return get$e(obj, key).fold(function() {
        return missingRequired(path2, key, obj);
      }, bundle);
    };
    var fallbackAccess = function(obj, key, fallback2, bundle) {
      var v2 = get$e(obj, key).getOrThunk(function() {
        return fallback2(obj);
      });
      return bundle(v2);
    };
    var optionAccess = function(obj, key, bundle) {
      return bundle(get$e(obj, key));
    };
    var optionDefaultedAccess = function(obj, key, fallback2, bundle) {
      var opt = get$e(obj, key).map(function(val) {
        return val === true ? fallback2(obj) : val;
      });
      return bundle(opt);
    };
    var extractField = function(field2, path2, obj, key, prop) {
      var bundle = function(av) {
        return prop.extract(path2.concat([key]), av);
      };
      var bundleAsOption = function(optValue) {
        return optValue.fold(function() {
          return SimpleResult.svalue(Optional.none());
        }, function(ov) {
          var result = prop.extract(path2.concat([key]), ov);
          return SimpleResult.map(result, Optional.some);
        });
      };
      switch (field2.tag) {
        case "required":
          return requiredAccess(path2, obj, key, bundle);
        case "defaultedThunk":
          return fallbackAccess(obj, key, field2.process, bundle);
        case "option":
          return optionAccess(obj, key, bundleAsOption);
        case "defaultedOptionThunk":
          return optionDefaultedAccess(obj, key, field2.process, bundleAsOption);
        case "mergeWithThunk": {
          return fallbackAccess(obj, key, constant$1({}), function(v2) {
            var result = deepMerge(field2.process(obj), v2);
            return bundle(result);
          });
        }
      }
    };
    var extractFields = function(path2, obj, fields) {
      var success = {};
      var errors = [];
      for (var _i2 = 0, fields_1 = fields; _i2 < fields_1.length; _i2++) {
        var field2 = fields_1[_i2];
        fold(field2, function(key, newKey, presence, prop) {
          var result = extractField(presence, path2, obj, key, prop);
          SimpleResult.fold(result, function(err) {
            errors.push.apply(errors, err);
          }, function(res) {
            success[newKey] = res;
          });
        }, function(newKey, instantiator) {
          success[newKey] = instantiator(obj);
        });
      }
      return errors.length > 0 ? SimpleResult.serror(errors) : SimpleResult.svalue(success);
    };
    var valueThunk = function(getDelegate) {
      var extract2 = function(path2, val) {
        return getDelegate().extract(path2, val);
      };
      var toString2 = function() {
        return getDelegate().toString();
      };
      return {
        extract: extract2,
        toString: toString2
      };
    };
    var getSetKeys = function(obj) {
      return keys(filter$1(obj, isNonNullable));
    };
    var objOfOnly = function(fields) {
      var delegate = objOf(fields);
      var fieldNames = foldr(fields, function(acc, value2) {
        return fold(value2, function(key) {
          var _a2;
          return deepMerge(acc, (_a2 = {}, _a2[key] = true, _a2));
        }, constant$1(acc));
      }, {});
      var extract2 = function(path2, o2) {
        var keys2 = isBoolean(o2) ? [] : getSetKeys(o2);
        var extra = filter$2(keys2, function(k2) {
          return !hasNonNullableKey(fieldNames, k2);
        });
        return extra.length === 0 ? delegate.extract(path2, o2) : unsupportedFields(path2, extra);
      };
      return {
        extract: extract2,
        toString: delegate.toString
      };
    };
    var objOf = function(values2) {
      var extract2 = function(path2, o2) {
        return extractFields(path2, o2, values2);
      };
      var toString2 = function() {
        var fieldStrings = map$2(values2, function(value2) {
          return fold(value2, function(key, _okey, _presence, prop) {
            return key + " -> " + prop.toString();
          }, function(newKey, _instantiator) {
            return "state(" + newKey + ")";
          });
        });
        return "obj{\n" + fieldStrings.join("\n") + "}";
      };
      return {
        extract: extract2,
        toString: toString2
      };
    };
    var arrOf = function(prop) {
      var extract2 = function(path2, array) {
        var results = map$2(array, function(a2, i2) {
          return prop.extract(path2.concat(["[" + i2 + "]"]), a2);
        });
        return ResultCombine.consolidateArr(results);
      };
      var toString2 = function() {
        return "array(" + prop.toString() + ")";
      };
      return {
        extract: extract2,
        toString: toString2
      };
    };
    var oneOf = function(props) {
      var extract2 = function(path2, val) {
        var errors = [];
        for (var _i2 = 0, props_1 = props; _i2 < props_1.length; _i2++) {
          var prop = props_1[_i2];
          var res = prop.extract(path2, val);
          if (res.stype === SimpleResultType.Value) {
            return res;
          }
          errors.push(res);
        }
        return ResultCombine.consolidateArr(errors);
      };
      var toString2 = function() {
        return "oneOf(" + map$2(props, function(prop) {
          return prop.toString();
        }).join(", ") + ")";
      };
      return {
        extract: extract2,
        toString: toString2
      };
    };
    var setOf$1 = function(validator, prop) {
      var validateKeys = function(path2, keys2) {
        return arrOf(value$2(validator)).extract(path2, keys2);
      };
      var extract2 = function(path2, o2) {
        var keys$1 = keys(o2);
        var validatedKeys = validateKeys(path2, keys$1);
        return SimpleResult.bind(validatedKeys, function(validKeys) {
          var schema2 = map$2(validKeys, function(vk) {
            return field$2(vk, vk, required$2(), prop);
          });
          return objOf(schema2).extract(path2, o2);
        });
      };
      var toString2 = function() {
        return "setOf(" + prop.toString() + ")";
      };
      return {
        extract: extract2,
        toString: toString2
      };
    };
    var thunk = function(_desc, processor) {
      var getP = cached(processor);
      var extract2 = function(path2, val) {
        return getP().extract(path2, val);
      };
      var toString2 = function() {
        return getP().toString();
      };
      return {
        extract: extract2,
        toString: toString2
      };
    };
    var arrOfObj = compose(arrOf, objOf);
    var anyValue = constant$1(anyValue$1);
    var typedValue = function(validator, expectedType) {
      return value$2(function(a2) {
        var actualType = typeof a2;
        return validator(a2) ? SimpleResult.svalue(a2) : SimpleResult.serror("Expected type: " + expectedType + " but got: " + actualType);
      });
    };
    var number = typedValue(isNumber2, "number");
    var string = typedValue(isString, "string");
    var boolean = typedValue(isBoolean, "boolean");
    var functionProcessor = typedValue(isFunction2, "function");
    var isPostMessageable = function(val) {
      if (Object(val) !== val) {
        return true;
      }
      switch ({}.toString.call(val).slice(8, -1)) {
        case "Boolean":
        case "Number":
        case "String":
        case "Date":
        case "RegExp":
        case "Blob":
        case "FileList":
        case "ImageData":
        case "ImageBitmap":
        case "ArrayBuffer":
          return true;
        case "Array":
        case "Object":
          return Object.keys(val).every(function(prop) {
            return isPostMessageable(val[prop]);
          });
        default:
          return false;
      }
    };
    var postMessageable = value$2(function(a2) {
      if (isPostMessageable(a2)) {
        return SimpleResult.svalue(a2);
      } else {
        return SimpleResult.serror("Expected value to be acceptable for sending via postMessage");
      }
    });
    var chooseFrom = function(path2, input2, branches, ch) {
      var fields = get$e(branches, ch);
      return fields.fold(function() {
        return missingBranch(path2, branches, ch);
      }, function(vp) {
        return vp.extract(path2.concat(["branch: " + ch]), input2);
      });
    };
    var choose$2 = function(key, branches) {
      var extract2 = function(path2, input2) {
        var choice = get$e(input2, key);
        return choice.fold(function() {
          return missingKey(path2, key);
        }, function(chosen) {
          return chooseFrom(path2, input2, branches, chosen);
        });
      };
      var toString2 = function() {
        return "chooseOn(" + key + "). Possible values: " + keys(branches);
      };
      return {
        extract: extract2,
        toString: toString2
      };
    };
    var arrOfVal = function() {
      return arrOf(anyValue$1);
    };
    var valueOf = function(validator) {
      return value$2(function(v2) {
        return validator(v2).fold(SimpleResult.serror, SimpleResult.svalue);
      });
    };
    var setOf = function(validator, prop) {
      return setOf$1(function(v2) {
        return SimpleResult.fromResult(validator(v2));
      }, prop);
    };
    var extractValue = function(label, prop, obj) {
      var res = prop.extract([label], obj);
      return SimpleResult.mapError(res, function(errs) {
        return {
          input: obj,
          errors: errs
        };
      });
    };
    var asRaw = function(label, prop, obj) {
      return SimpleResult.toResult(extractValue(label, prop, obj));
    };
    var getOrDie = function(extraction) {
      return extraction.fold(function(errInfo) {
        throw new Error(formatError(errInfo));
      }, identity$1);
    };
    var asRawOrDie$1 = function(label, prop, obj) {
      return getOrDie(asRaw(label, prop, obj));
    };
    var formatError = function(errInfo) {
      return "Errors: \n" + formatErrors(errInfo.errors).join("\n") + "\n\nInput object: " + formatObj(errInfo.input);
    };
    var choose$1 = function(key, branches) {
      return choose$2(key, map$12(branches, objOf));
    };
    var thunkOf = function(desc, schema2) {
      return thunk(desc, schema2);
    };
    var field$1 = field$2;
    var customField = customField$1;
    var validateEnum = function(values2) {
      return valueOf(function(value2) {
        return contains$2(values2, value2) ? Result.value(value2) : Result.error('Unsupported value: "' + value2 + '", choose one of "' + values2.join(", ") + '".');
      });
    };
    var required$1 = function(key) {
      return field$1(key, key, required$2(), anyValue());
    };
    var requiredOf = function(key, schema2) {
      return field$1(key, key, required$2(), schema2);
    };
    var requiredNumber = function(key) {
      return requiredOf(key, number);
    };
    var requiredString = function(key) {
      return requiredOf(key, string);
    };
    var requiredStringEnum = function(key, values2) {
      return field$1(key, key, required$2(), validateEnum(values2));
    };
    var requiredBoolean = function(key) {
      return requiredOf(key, boolean);
    };
    var requiredFunction = function(key) {
      return requiredOf(key, functionProcessor);
    };
    var forbid = function(key, message) {
      return field$1(key, key, asOption(), value$2(function(_v) {
        return SimpleResult.serror("The field: " + key + " is forbidden. " + message);
      }));
    };
    var requiredObjOf = function(key, objSchema) {
      return field$1(key, key, required$2(), objOf(objSchema));
    };
    var requiredArrayOfObj = function(key, objFields) {
      return field$1(key, key, required$2(), arrOfObj(objFields));
    };
    var requiredArrayOf = function(key, schema2) {
      return field$1(key, key, required$2(), arrOf(schema2));
    };
    var option = function(key) {
      return field$1(key, key, asOption(), anyValue());
    };
    var optionOf = function(key, schema2) {
      return field$1(key, key, asOption(), schema2);
    };
    var optionNumber = function(key) {
      return optionOf(key, number);
    };
    var optionString = function(key) {
      return optionOf(key, string);
    };
    var optionFunction = function(key) {
      return optionOf(key, functionProcessor);
    };
    var optionArrayOf = function(key, schema2) {
      return optionOf(key, arrOf(schema2));
    };
    var optionObjOf = function(key, objSchema) {
      return optionOf(key, objOf(objSchema));
    };
    var optionObjOfOnly = function(key, objSchema) {
      return optionOf(key, objOfOnly(objSchema));
    };
    var defaulted = function(key, fallback2) {
      return field$1(key, key, defaulted$1(fallback2), anyValue());
    };
    var defaultedOf = function(key, fallback2, schema2) {
      return field$1(key, key, defaulted$1(fallback2), schema2);
    };
    var defaultedNumber = function(key, fallback2) {
      return defaultedOf(key, fallback2, number);
    };
    var defaultedString = function(key, fallback2) {
      return defaultedOf(key, fallback2, string);
    };
    var defaultedStringEnum = function(key, fallback2, values2) {
      return defaultedOf(key, fallback2, validateEnum(values2));
    };
    var defaultedBoolean = function(key, fallback2) {
      return defaultedOf(key, fallback2, boolean);
    };
    var defaultedFunction = function(key, fallback2) {
      return defaultedOf(key, fallback2, functionProcessor);
    };
    var defaultedPostMsg = function(key, fallback2) {
      return defaultedOf(key, fallback2, postMessageable);
    };
    var defaultedArrayOf = function(key, fallback2, schema2) {
      return defaultedOf(key, fallback2, arrOf(schema2));
    };
    var defaultedObjOf = function(key, fallback2, objSchema) {
      return defaultedOf(key, fallback2, objOf(objSchema));
    };
    var Cell = function(initial) {
      var value2 = initial;
      var get2 = function() {
        return value2;
      };
      var set3 = function(v2) {
        value2 = v2;
      };
      return {
        get: get2,
        set: set3
      };
    };
    var generate$7 = function(cases) {
      if (!isArray2(cases)) {
        throw new Error("cases must be an array");
      }
      if (cases.length === 0) {
        throw new Error("there must be at least one case");
      }
      var constructors = [];
      var adt2 = {};
      each$1(cases, function(acase, count2) {
        var keys$1 = keys(acase);
        if (keys$1.length !== 1) {
          throw new Error("one and only one name per case");
        }
        var key = keys$1[0];
        var value2 = acase[key];
        if (adt2[key] !== void 0) {
          throw new Error("duplicate key detected:" + key);
        } else if (key === "cata") {
          throw new Error("cannot have a case named cata (sorry)");
        } else if (!isArray2(value2)) {
          throw new Error("case arguments must be an array");
        }
        constructors.push(key);
        adt2[key] = function() {
          var args = [];
          for (var _i2 = 0; _i2 < arguments.length; _i2++) {
            args[_i2] = arguments[_i2];
          }
          var argLength = args.length;
          if (argLength !== value2.length) {
            throw new Error("Wrong number of arguments to case " + key + ". Expected " + value2.length + " (" + value2 + "), got " + argLength);
          }
          var match2 = function(branches) {
            var branchKeys = keys(branches);
            if (constructors.length !== branchKeys.length) {
              throw new Error("Wrong number of arguments to match. Expected: " + constructors.join(",") + "\nActual: " + branchKeys.join(","));
            }
            var allReqd = forall(constructors, function(reqKey) {
              return contains$2(branchKeys, reqKey);
            });
            if (!allReqd) {
              throw new Error("Not all branches were specified when using match. Specified: " + branchKeys.join(", ") + "\nRequired: " + constructors.join(", "));
            }
            return branches[key].apply(null, args);
          };
          return {
            fold: function() {
              var foldArgs = [];
              for (var _i3 = 0; _i3 < arguments.length; _i3++) {
                foldArgs[_i3] = arguments[_i3];
              }
              if (foldArgs.length !== cases.length) {
                throw new Error("Wrong number of arguments to fold. Expected " + cases.length + ", got " + foldArgs.length);
              }
              var target = foldArgs[count2];
              return target.apply(null, args);
            },
            match: match2,
            log: function(label) {
              console.log(label, {
                constructors,
                constructor: key,
                params: args
              });
            }
          };
        };
      });
      return adt2;
    };
    var Adt = { generate: generate$7 };
    Adt.generate([
      {
        bothErrors: [
          "error1",
          "error2"
        ]
      },
      {
        firstError: [
          "error1",
          "value2"
        ]
      },
      {
        secondError: [
          "value1",
          "error2"
        ]
      },
      {
        bothValues: [
          "value1",
          "value2"
        ]
      }
    ]);
    var partition$1 = function(results) {
      var errors = [];
      var values2 = [];
      each$1(results, function(result) {
        result.fold(function(err) {
          errors.push(err);
        }, function(value2) {
          values2.push(value2);
        });
      });
      return {
        errors,
        values: values2
      };
    };
    var exclude$1 = function(obj, fields) {
      var r3 = {};
      each2(obj, function(v2, k2) {
        if (!contains$2(fields, k2)) {
          r3[k2] = v2;
        }
      });
      return r3;
    };
    var wrap$2 = function(key, value2) {
      var _a2;
      return _a2 = {}, _a2[key] = value2, _a2;
    };
    var wrapAll$1 = function(keyvalues) {
      var r3 = {};
      each$1(keyvalues, function(kv) {
        r3[kv.key] = kv.value;
      });
      return r3;
    };
    var exclude = function(obj, fields) {
      return exclude$1(obj, fields);
    };
    var wrap$1 = function(key, value2) {
      return wrap$2(key, value2);
    };
    var wrapAll = function(keyvalues) {
      return wrapAll$1(keyvalues);
    };
    var mergeValues = function(values2, base2) {
      return values2.length === 0 ? Result.value(base2) : Result.value(deepMerge(base2, merge$1.apply(void 0, values2)));
    };
    var mergeErrors = function(errors) {
      return Result.error(flatten(errors));
    };
    var consolidate = function(objs, base2) {
      var partitions = partition$1(objs);
      return partitions.errors.length > 0 ? mergeErrors(partitions.errors) : mergeValues(partitions.values, base2);
    };
    var ensureIsRoot = function(isRoot) {
      return isFunction2(isRoot) ? isRoot : never;
    };
    var ancestor$2 = function(scope, transform2, isRoot) {
      var element2 = scope.dom;
      var stop2 = ensureIsRoot(isRoot);
      while (element2.parentNode) {
        element2 = element2.parentNode;
        var el = SugarElement.fromDom(element2);
        var transformed = transform2(el);
        if (transformed.isSome()) {
          return transformed;
        } else if (stop2(el)) {
          break;
        }
      }
      return Optional.none();
    };
    var closest$4 = function(scope, transform2, isRoot) {
      var current = transform2(scope);
      var stop2 = ensureIsRoot(isRoot);
      return current.orThunk(function() {
        return stop2(scope) ? Optional.none() : ancestor$2(scope, transform2, stop2);
      });
    };
    var isSource = function(component, simulatedEvent) {
      return eq2(component.element, simulatedEvent.event.target);
    };
    var defaultEventHandler = {
      can: always,
      abort: never,
      run: noop3
    };
    var nu$9 = function(parts2) {
      if (!hasNonNullableKey(parts2, "can") && !hasNonNullableKey(parts2, "abort") && !hasNonNullableKey(parts2, "run")) {
        throw new Error("EventHandler defined by: " + JSON.stringify(parts2, null, 2) + " does not have can, abort, or run!");
      }
      return __assign(__assign({}, defaultEventHandler), parts2);
    };
    var all$2 = function(handlers2, f2) {
      return function() {
        var args = [];
        for (var _i2 = 0; _i2 < arguments.length; _i2++) {
          args[_i2] = arguments[_i2];
        }
        return foldl(handlers2, function(acc, handler) {
          return acc && f2(handler).apply(void 0, args);
        }, true);
      };
    };
    var any = function(handlers2, f2) {
      return function() {
        var args = [];
        for (var _i2 = 0; _i2 < arguments.length; _i2++) {
          args[_i2] = arguments[_i2];
        }
        return foldl(handlers2, function(acc, handler) {
          return acc || f2(handler).apply(void 0, args);
        }, false);
      };
    };
    var read$2 = function(handler) {
      return isFunction2(handler) ? {
        can: always,
        abort: never,
        run: handler
      } : handler;
    };
    var fuse$1 = function(handlers2) {
      var can2 = all$2(handlers2, function(handler) {
        return handler.can;
      });
      var abort2 = any(handlers2, function(handler) {
        return handler.abort;
      });
      var run2 = function() {
        var args = [];
        for (var _i2 = 0; _i2 < arguments.length; _i2++) {
          args[_i2] = arguments[_i2];
        }
        each$1(handlers2, function(handler) {
          handler.run.apply(void 0, args);
        });
      };
      return {
        can: can2,
        abort: abort2,
        run: run2
      };
    };
    var constant = constant$1;
    var touchstart = constant("touchstart");
    var touchmove = constant("touchmove");
    var touchend = constant("touchend");
    var touchcancel = constant("touchcancel");
    var mousedown = constant("mousedown");
    var mousemove = constant("mousemove");
    var mouseout = constant("mouseout");
    var mouseup = constant("mouseup");
    var mouseover = constant("mouseover");
    var focusin = constant("focusin");
    var focusout = constant("focusout");
    var keydown = constant("keydown");
    var keyup = constant("keyup");
    var input = constant("input");
    var change = constant("change");
    var click = constant("click");
    var transitioncancel = constant("transitioncancel");
    var transitionend = constant("transitionend");
    var transitionstart = constant("transitionstart");
    var selectstart = constant("selectstart");
    var prefixName = function(name2) {
      return constant$1("alloy." + name2);
    };
    var alloy = { tap: prefixName("tap") };
    var focus$4 = prefixName("focus");
    var postBlur = prefixName("blur.post");
    var postPaste = prefixName("paste.post");
    var receive = prefixName("receive");
    var execute$5 = prefixName("execute");
    var focusItem = prefixName("focus.item");
    var tap = alloy.tap;
    var longpress = prefixName("longpress");
    var sandboxClose = prefixName("sandbox.close");
    var typeaheadCancel = prefixName("typeahead.cancel");
    var systemInit = prefixName("system.init");
    var documentTouchmove = prefixName("system.touchmove");
    var documentTouchend = prefixName("system.touchend");
    var windowScroll = prefixName("system.scroll");
    var windowResize = prefixName("system.resize");
    var attachedToDom = prefixName("system.attached");
    var detachedFromDom = prefixName("system.detached");
    var dismissRequested = prefixName("system.dismissRequested");
    var repositionRequested = prefixName("system.repositionRequested");
    var focusShifted = prefixName("focusmanager.shifted");
    var slotVisibility = prefixName("slotcontainer.visibility");
    var changeTab = prefixName("change.tab");
    var dismissTab = prefixName("dismiss.tab");
    var highlight$1 = prefixName("highlight");
    var dehighlight$1 = prefixName("dehighlight");
    var emit = function(component, event) {
      dispatchWith(component, component.element, event, {});
    };
    var emitWith = function(component, event, properties2) {
      dispatchWith(component, component.element, event, properties2);
    };
    var emitExecute = function(component) {
      emit(component, execute$5());
    };
    var dispatch2 = function(component, target, event) {
      dispatchWith(component, target, event, {});
    };
    var dispatchWith = function(component, target, event, properties2) {
      var data = __assign({ target }, properties2);
      component.getSystem().triggerEvent(event, target, data);
    };
    var dispatchEvent3 = function(component, target, event, simulatedEvent) {
      component.getSystem().triggerEvent(event, target, simulatedEvent.event);
    };
    var derive$2 = function(configs) {
      return wrapAll(configs);
    };
    var abort = function(name2, predicate) {
      return {
        key: name2,
        value: nu$9({ abort: predicate })
      };
    };
    var can = function(name2, predicate) {
      return {
        key: name2,
        value: nu$9({ can: predicate })
      };
    };
    var preventDefault = function(name2) {
      return {
        key: name2,
        value: nu$9({
          run: function(component, simulatedEvent) {
            simulatedEvent.event.prevent();
          }
        })
      };
    };
    var run$1 = function(name2, handler) {
      return {
        key: name2,
        value: nu$9({ run: handler })
      };
    };
    var runActionExtra = function(name2, action, extra) {
      return {
        key: name2,
        value: nu$9({
          run: function(component, simulatedEvent) {
            action.apply(void 0, [
              component,
              simulatedEvent
            ].concat(extra));
          }
        })
      };
    };
    var runOnName = function(name2) {
      return function(handler) {
        return run$1(name2, handler);
      };
    };
    var runOnSourceName = function(name2) {
      return function(handler) {
        return {
          key: name2,
          value: nu$9({
            run: function(component, simulatedEvent) {
              if (isSource(component, simulatedEvent)) {
                handler(component, simulatedEvent);
              }
            }
          })
        };
      };
    };
    var redirectToUid = function(name2, uid2) {
      return run$1(name2, function(component, simulatedEvent) {
        component.getSystem().getByUid(uid2).each(function(redirectee) {
          dispatchEvent3(redirectee, redirectee.element, name2, simulatedEvent);
        });
      });
    };
    var redirectToPart = function(name2, detail, partName) {
      var uid2 = detail.partUids[partName];
      return redirectToUid(name2, uid2);
    };
    var runWithTarget = function(name2, f2) {
      return run$1(name2, function(component, simulatedEvent) {
        var ev = simulatedEvent.event;
        var target = component.getSystem().getByDom(ev.target).getOrThunk(function() {
          var closest2 = closest$4(ev.target, function(el) {
            return component.getSystem().getByDom(el).toOptional();
          }, never);
          return closest2.getOr(component);
        });
        f2(component, target, simulatedEvent);
      });
    };
    var cutter = function(name2) {
      return run$1(name2, function(component, simulatedEvent) {
        simulatedEvent.cut();
      });
    };
    var stopper = function(name2) {
      return run$1(name2, function(component, simulatedEvent) {
        simulatedEvent.stop();
      });
    };
    var runOnSource = function(name2, f2) {
      return runOnSourceName(name2)(f2);
    };
    var runOnAttached = runOnSourceName(attachedToDom());
    var runOnDetached = runOnSourceName(detachedFromDom());
    var runOnInit = runOnSourceName(systemInit());
    var runOnExecute$1 = runOnName(execute$5());
    var fromHtml$1 = function(html, scope) {
      var doc = scope || document;
      var div = doc.createElement("div");
      div.innerHTML = html;
      return children(SugarElement.fromDom(div));
    };
    var get$7 = function(element2) {
      return element2.dom.innerHTML;
    };
    var set$5 = function(element2, content) {
      var owner2 = owner$4(element2);
      var docDom = owner2.dom;
      var fragment = SugarElement.fromDom(docDom.createDocumentFragment());
      var contentElements = fromHtml$1(content, docDom);
      append$1(fragment, contentElements);
      empty(element2);
      append$2(element2, fragment);
    };
    var getOuter = function(element2) {
      var container = SugarElement.fromTag("div");
      var clone3 = SugarElement.fromDom(element2.dom.cloneNode(true));
      append$2(container, clone3);
      return get$7(container);
    };
    var clone$12 = function(original2, isDeep) {
      return SugarElement.fromDom(original2.dom.cloneNode(isDeep));
    };
    var shallow = function(original2) {
      return clone$12(original2, false);
    };
    var getHtml = function(element2) {
      if (isShadowRoot2(element2)) {
        return "#shadow-root";
      } else {
        var clone3 = shallow(element2);
        return getOuter(clone3);
      }
    };
    var element = function(elem) {
      return getHtml(elem);
    };
    var isRecursive = function(component, originator, target) {
      return eq2(originator, component.element) && !eq2(originator, target);
    };
    var events$i = derive$2([can(focus$4(), function(component, simulatedEvent) {
      var event = simulatedEvent.event;
      var originator = event.originator;
      var target = event.target;
      if (isRecursive(component, originator, target)) {
        console.warn(focus$4() + " did not get interpreted by the desired target. \nOriginator: " + element(originator) + "\nTarget: " + element(target) + "\nCheck the " + focus$4() + " event handlers");
        return false;
      } else {
        return true;
      }
    })]);
    var DefaultEvents = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      events: events$i
    });
    var unique = 0;
    var generate$6 = function(prefix2) {
      var date = new Date();
      var time = date.getTime();
      var random = Math.floor(Math.random() * 1e9);
      unique++;
      return prefix2 + "_" + random + unique + String(time);
    };
    var prefix$1 = constant$1("alloy-id-");
    var idAttr$1 = constant$1("data-alloy-id");
    var prefix = prefix$1();
    var idAttr = idAttr$1();
    var write2 = function(label, elem) {
      var id2 = generate$6(prefix + label);
      writeOnly(elem, id2);
      return id2;
    };
    var writeOnly = function(elem, uid2) {
      Object.defineProperty(elem.dom, idAttr, {
        value: uid2,
        writable: true
      });
    };
    var read$1 = function(elem) {
      var id2 = isElement$2(elem) ? elem.dom[idAttr] : null;
      return Optional.from(id2);
    };
    var generate$5 = function(prefix2) {
      return generate$6(prefix2);
    };
    var make$8 = identity$1;
    var NoContextApi = function(getComp) {
      var getMessage = function(event) {
        return "The component must be in a context to execute: " + event + (getComp ? "\n" + element(getComp().element) + " is not in context." : "");
      };
      var fail = function(event) {
        return function() {
          throw new Error(getMessage(event));
        };
      };
      var warn = function(event) {
        return function() {
          console.warn(getMessage(event));
        };
      };
      return {
        debugInfo: constant$1("fake"),
        triggerEvent: warn("triggerEvent"),
        triggerFocus: warn("triggerFocus"),
        triggerEscape: warn("triggerEscape"),
        broadcast: warn("broadcast"),
        broadcastOn: warn("broadcastOn"),
        broadcastEvent: warn("broadcastEvent"),
        build: fail("build"),
        addToWorld: fail("addToWorld"),
        removeFromWorld: fail("removeFromWorld"),
        addToGui: fail("addToGui"),
        removeFromGui: fail("removeFromGui"),
        getByUid: fail("getByUid"),
        getByDom: fail("getByDom"),
        isConnected: never
      };
    };
    var singleton$1 = NoContextApi();
    var markAsBehaviourApi = function(f2, apiName, apiFunction) {
      var delegate = apiFunction.toString();
      var endIndex = delegate.indexOf(")") + 1;
      var openBracketIndex = delegate.indexOf("(");
      var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
      f2.toFunctionAnnotation = function() {
        return {
          name: apiName,
          parameters: cleanParameters(parameters.slice(0, 1).concat(parameters.slice(3)))
        };
      };
      return f2;
    };
    var cleanParameters = function(parameters) {
      return map$2(parameters, function(p2) {
        return endsWith(p2, "/*") ? p2.substring(0, p2.length - "/*".length) : p2;
      });
    };
    var markAsExtraApi = function(f2, extraName) {
      var delegate = f2.toString();
      var endIndex = delegate.indexOf(")") + 1;
      var openBracketIndex = delegate.indexOf("(");
      var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
      f2.toFunctionAnnotation = function() {
        return {
          name: extraName,
          parameters: cleanParameters(parameters)
        };
      };
      return f2;
    };
    var markAsSketchApi = function(f2, apiFunction) {
      var delegate = apiFunction.toString();
      var endIndex = delegate.indexOf(")") + 1;
      var openBracketIndex = delegate.indexOf("(");
      var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
      f2.toFunctionAnnotation = function() {
        return {
          name: "OVERRIDE",
          parameters: cleanParameters(parameters.slice(1))
        };
      };
      return f2;
    };
    var premadeTag = generate$6("alloy-premade");
    var premade$1 = function(comp) {
      return wrap$1(premadeTag, comp);
    };
    var getPremade = function(spec) {
      return get$e(spec, premadeTag);
    };
    var makeApi = function(f2) {
      return markAsSketchApi(function(component) {
        var rest = [];
        for (var _i2 = 1; _i2 < arguments.length; _i2++) {
          rest[_i2 - 1] = arguments[_i2];
        }
        return f2.apply(void 0, __spreadArray([
          component.getApis(),
          component
        ], rest, false));
      }, f2);
    };
    var NoState = {
      init: function() {
        return nu$8({ readState: constant$1("No State required") });
      }
    };
    var nu$8 = function(spec) {
      return spec;
    };
    var generateFrom$1 = function(spec, all2) {
      var schema2 = map$2(all2, function(a2) {
        return optionObjOf(a2.name(), [
          required$1("config"),
          defaulted("state", NoState)
        ]);
      });
      var validated = asRaw("component.behaviours", objOf(schema2), spec.behaviours).fold(function(errInfo) {
        throw new Error(formatError(errInfo) + "\nComplete spec:\n" + JSON.stringify(spec, null, 2));
      }, identity$1);
      return {
        list: all2,
        data: map$12(validated, function(optBlobThunk) {
          var output2 = optBlobThunk.map(function(blob) {
            return {
              config: blob.config,
              state: blob.state.init(blob.config)
            };
          });
          return constant$1(output2);
        })
      };
    };
    var getBehaviours$3 = function(bData) {
      return bData.list;
    };
    var getData$2 = function(bData) {
      return bData.data;
    };
    var byInnerKey = function(data, tuple) {
      var r3 = {};
      each2(data, function(detail, key) {
        each2(detail, function(value2, indexKey) {
          var chain = get$e(r3, indexKey).getOr([]);
          r3[indexKey] = chain.concat([tuple(key, value2)]);
        });
      });
      return r3;
    };
    var nu$7 = function(s2) {
      return {
        classes: isUndefined(s2.classes) ? [] : s2.classes,
        attributes: isUndefined(s2.attributes) ? {} : s2.attributes,
        styles: isUndefined(s2.styles) ? {} : s2.styles
      };
    };
    var merge2 = function(defnA, mod) {
      return __assign(__assign({}, defnA), {
        attributes: __assign(__assign({}, defnA.attributes), mod.attributes),
        styles: __assign(__assign({}, defnA.styles), mod.styles),
        classes: defnA.classes.concat(mod.classes)
      });
    };
    var combine$2 = function(info, baseMod, behaviours2, base2) {
      var modsByBehaviour = __assign({}, baseMod);
      each$1(behaviours2, function(behaviour) {
        modsByBehaviour[behaviour.name()] = behaviour.exhibit(info, base2);
      });
      var byAspect = byInnerKey(modsByBehaviour, function(name2, modification) {
        return {
          name: name2,
          modification
        };
      });
      var combineObjects = function(objects) {
        return foldr(objects, function(b3, a2) {
          return __assign(__assign({}, a2.modification), b3);
        }, {});
      };
      var combinedClasses = foldr(byAspect.classes, function(b3, a2) {
        return a2.modification.concat(b3);
      }, []);
      var combinedAttributes = combineObjects(byAspect.attributes);
      var combinedStyles = combineObjects(byAspect.styles);
      return nu$7({
        classes: combinedClasses,
        attributes: combinedAttributes,
        styles: combinedStyles
      });
    };
    var sortKeys = function(label, keyName, array, order2) {
      try {
        var sorted = sort(array, function(a2, b3) {
          var aKey = a2[keyName];
          var bKey = b3[keyName];
          var aIndex = order2.indexOf(aKey);
          var bIndex = order2.indexOf(bKey);
          if (aIndex === -1) {
            throw new Error("The ordering for " + label + " does not have an entry for " + aKey + ".\nOrder specified: " + JSON.stringify(order2, null, 2));
          }
          if (bIndex === -1) {
            throw new Error("The ordering for " + label + " does not have an entry for " + bKey + ".\nOrder specified: " + JSON.stringify(order2, null, 2));
          }
          if (aIndex < bIndex) {
            return -1;
          } else if (bIndex < aIndex) {
            return 1;
          } else {
            return 0;
          }
        });
        return Result.value(sorted);
      } catch (err) {
        return Result.error([err]);
      }
    };
    var uncurried = function(handler, purpose) {
      return {
        handler,
        purpose
      };
    };
    var curried = function(handler, purpose) {
      return {
        cHandler: handler,
        purpose
      };
    };
    var curryArgs = function(descHandler, extraArgs) {
      return curried(curry.apply(void 0, [descHandler.handler].concat(extraArgs)), descHandler.purpose);
    };
    var getCurried = function(descHandler) {
      return descHandler.cHandler;
    };
    var behaviourTuple = function(name2, handler) {
      return {
        name: name2,
        handler
      };
    };
    var nameToHandlers = function(behaviours2, info) {
      var r3 = {};
      each$1(behaviours2, function(behaviour) {
        r3[behaviour.name()] = behaviour.handlers(info);
      });
      return r3;
    };
    var groupByEvents = function(info, behaviours2, base2) {
      var behaviourEvents = __assign(__assign({}, base2), nameToHandlers(behaviours2, info));
      return byInnerKey(behaviourEvents, behaviourTuple);
    };
    var combine$1 = function(info, eventOrder, behaviours2, base2) {
      var byEventName = groupByEvents(info, behaviours2, base2);
      return combineGroups(byEventName, eventOrder);
    };
    var assemble = function(rawHandler) {
      var handler = read$2(rawHandler);
      return function(component, simulatedEvent) {
        var rest = [];
        for (var _i2 = 2; _i2 < arguments.length; _i2++) {
          rest[_i2 - 2] = arguments[_i2];
        }
        var args = [
          component,
          simulatedEvent
        ].concat(rest);
        if (handler.abort.apply(void 0, args)) {
          simulatedEvent.stop();
        } else if (handler.can.apply(void 0, args)) {
          handler.run.apply(void 0, args);
        }
      };
    };
    var missingOrderError = function(eventName, tuples) {
      return Result.error(["The event (" + eventName + ') has more than one behaviour that listens to it.\nWhen this occurs, you must specify an event ordering for the behaviours in your spec (e.g. [ "listing", "toggling" ]).\nThe behaviours that can trigger it are: ' + JSON.stringify(map$2(tuples, function(c2) {
        return c2.name;
      }), null, 2)]);
    };
    var fuse = function(tuples, eventOrder, eventName) {
      var order2 = eventOrder[eventName];
      if (!order2) {
        return missingOrderError(eventName, tuples);
      } else {
        return sortKeys("Event: " + eventName, "name", tuples, order2).map(function(sortedTuples) {
          var handlers2 = map$2(sortedTuples, function(tuple) {
            return tuple.handler;
          });
          return fuse$1(handlers2);
        });
      }
    };
    var combineGroups = function(byEventName, eventOrder) {
      var r3 = mapToArray(byEventName, function(tuples, eventName) {
        var combined = tuples.length === 1 ? Result.value(tuples[0].handler) : fuse(tuples, eventOrder, eventName);
        return combined.map(function(handler) {
          var assembled = assemble(handler);
          var purpose = tuples.length > 1 ? filter$2(eventOrder[eventName], function(o2) {
            return exists(tuples, function(t3) {
              return t3.name === o2;
            });
          }).join(" > ") : tuples[0].name;
          return wrap$1(eventName, uncurried(assembled, purpose));
        });
      });
      return consolidate(r3, {});
    };
    var _a$2;
    var baseBehaviour = "alloy.base.behaviour";
    var schema$z = objOf([
      field$1("dom", "dom", required$2(), objOf([
        required$1("tag"),
        defaulted("styles", {}),
        defaulted("classes", []),
        defaulted("attributes", {}),
        option("value"),
        option("innerHtml")
      ])),
      required$1("components"),
      required$1("uid"),
      defaulted("events", {}),
      defaulted("apis", {}),
      field$1("eventOrder", "eventOrder", mergeWith((_a$2 = {}, _a$2[execute$5()] = [
        "disabling",
        baseBehaviour,
        "toggling",
        "typeaheadevents"
      ], _a$2[focus$4()] = [
        baseBehaviour,
        "focusing",
        "keying"
      ], _a$2[systemInit()] = [
        baseBehaviour,
        "disabling",
        "toggling",
        "representing"
      ], _a$2[input()] = [
        baseBehaviour,
        "representing",
        "streaming",
        "invalidating"
      ], _a$2[detachedFromDom()] = [
        baseBehaviour,
        "representing",
        "item-events",
        "tooltipping"
      ], _a$2[mousedown()] = [
        "focusing",
        baseBehaviour,
        "item-type-events"
      ], _a$2[touchstart()] = [
        "focusing",
        baseBehaviour,
        "item-type-events"
      ], _a$2[mouseover()] = [
        "item-type-events",
        "tooltipping"
      ], _a$2[receive()] = [
        "receiving",
        "reflecting",
        "tooltipping"
      ], _a$2)), anyValue()),
      option("domModification")
    ]);
    var toInfo = function(spec) {
      return asRaw("custom.definition", schema$z, spec);
    };
    var toDefinition = function(detail) {
      return __assign(__assign({}, detail.dom), {
        uid: detail.uid,
        domChildren: map$2(detail.components, function(comp) {
          return comp.element;
        })
      });
    };
    var toModification = function(detail) {
      return detail.domModification.fold(function() {
        return nu$7({});
      }, nu$7);
    };
    var toEvents = function(info) {
      return info.events;
    };
    var read2 = function(element2, attr) {
      var value2 = get$d(element2, attr);
      return value2 === void 0 || value2 === "" ? [] : value2.split(" ");
    };
    var add$4 = function(element2, attr, id2) {
      var old = read2(element2, attr);
      var nu2 = old.concat([id2]);
      set$8(element2, attr, nu2.join(" "));
      return true;
    };
    var remove$4 = function(element2, attr, id2) {
      var nu2 = filter$2(read2(element2, attr), function(v2) {
        return v2 !== id2;
      });
      if (nu2.length > 0) {
        set$8(element2, attr, nu2.join(" "));
      } else {
        remove$7(element2, attr);
      }
      return false;
    };
    var supports = function(element2) {
      return element2.dom.classList !== void 0;
    };
    var get$6 = function(element2) {
      return read2(element2, "class");
    };
    var add$3 = function(element2, clazz) {
      return add$4(element2, "class", clazz);
    };
    var remove$3 = function(element2, clazz) {
      return remove$4(element2, "class", clazz);
    };
    var add$2 = function(element2, clazz) {
      if (supports(element2)) {
        element2.dom.classList.add(clazz);
      } else {
        add$3(element2, clazz);
      }
    };
    var cleanClass = function(element2) {
      var classList = supports(element2) ? element2.dom.classList : get$6(element2);
      if (classList.length === 0) {
        remove$7(element2, "class");
      }
    };
    var remove$2 = function(element2, clazz) {
      if (supports(element2)) {
        var classList = element2.dom.classList;
        classList.remove(clazz);
      } else {
        remove$3(element2, clazz);
      }
      cleanClass(element2);
    };
    var has = function(element2, clazz) {
      return supports(element2) && element2.dom.classList.contains(clazz);
    };
    var add$1 = function(element2, classes2) {
      each$1(classes2, function(x2) {
        add$2(element2, x2);
      });
    };
    var remove$1 = function(element2, classes2) {
      each$1(classes2, function(x2) {
        remove$2(element2, x2);
      });
    };
    var hasAll = function(element2, classes2) {
      return forall(classes2, function(clazz) {
        return has(element2, clazz);
      });
    };
    var get$5 = function(element2) {
      return element2.dom.value;
    };
    var set$4 = function(element2, value2) {
      if (value2 === void 0) {
        throw new Error("Value.set was undefined");
      }
      element2.dom.value = value2;
    };
    var renderToDom = function(definition) {
      var subject = SugarElement.fromTag(definition.tag);
      setAll$1(subject, definition.attributes);
      add$1(subject, definition.classes);
      setAll(subject, definition.styles);
      definition.innerHtml.each(function(html) {
        return set$5(subject, html);
      });
      var children2 = definition.domChildren;
      append$1(subject, children2);
      definition.value.each(function(value2) {
        set$4(subject, value2);
      });
      if (!definition.uid) {
        debugger;
      }
      writeOnly(subject, definition.uid);
      return subject;
    };
    var getBehaviours$2 = function(spec) {
      var behaviours2 = get$e(spec, "behaviours").getOr({});
      return bind$3(keys(behaviours2), function(name2) {
        var behaviour = behaviours2[name2];
        return isNonNullable(behaviour) ? [behaviour.me] : [];
      });
    };
    var generateFrom = function(spec, all2) {
      return generateFrom$1(spec, all2);
    };
    var generate$4 = function(spec) {
      var all2 = getBehaviours$2(spec);
      return generateFrom(spec, all2);
    };
    var getDomDefinition = function(info, bList, bData) {
      var definition = toDefinition(info);
      var infoModification = toModification(info);
      var baseModification = { "alloy.base.modification": infoModification };
      var modification = bList.length > 0 ? combine$2(bData, baseModification, bList, definition) : infoModification;
      return merge2(definition, modification);
    };
    var getEvents = function(info, bList, bData) {
      var baseEvents = { "alloy.base.behaviour": toEvents(info) };
      return combine$1(bData, info.eventOrder, bList, baseEvents).getOrDie();
    };
    var build$2 = function(spec) {
      var getMe = function() {
        return me2;
      };
      var systemApi = Cell(singleton$1);
      var info = getOrDie(toInfo(spec));
      var bBlob = generate$4(spec);
      var bList = getBehaviours$3(bBlob);
      var bData = getData$2(bBlob);
      var modDefinition = getDomDefinition(info, bList, bData);
      var item2 = renderToDom(modDefinition);
      var events2 = getEvents(info, bList, bData);
      var subcomponents = Cell(info.components);
      var connect = function(newApi) {
        systemApi.set(newApi);
      };
      var disconnect = function() {
        systemApi.set(NoContextApi(getMe));
      };
      var syncComponents = function() {
        var children$1 = children(item2);
        var subs2 = bind$3(children$1, function(child2) {
          return systemApi.get().getByDom(child2).fold(function() {
            return [];
          }, pure$2);
        });
        subcomponents.set(subs2);
      };
      var config2 = function(behaviour) {
        var b3 = bData;
        var f2 = isFunction2(b3[behaviour.name()]) ? b3[behaviour.name()] : function() {
          throw new Error("Could not find " + behaviour.name() + " in " + JSON.stringify(spec, null, 2));
        };
        return f2();
      };
      var hasConfigured = function(behaviour) {
        return isFunction2(bData[behaviour.name()]);
      };
      var getApis = function() {
        return info.apis;
      };
      var readState = function(behaviourName) {
        return bData[behaviourName]().map(function(b3) {
          return b3.state.readState();
        }).getOr("not enabled");
      };
      var me2 = {
        uid: spec.uid,
        getSystem: systemApi.get,
        config: config2,
        hasConfigured,
        spec,
        readState,
        getApis,
        connect,
        disconnect,
        element: item2,
        syncComponents,
        components: subcomponents.get,
        events: events2
      };
      return me2;
    };
    var buildSubcomponents = function(spec) {
      var components2 = get$e(spec, "components").getOr([]);
      return map$2(components2, build$1);
    };
    var buildFromSpec = function(userSpec) {
      var _a2 = make$8(userSpec), specEvents = _a2.events, spec = __rest(_a2, ["events"]);
      var components2 = buildSubcomponents(spec);
      var completeSpec = __assign(__assign({}, spec), {
        events: __assign(__assign({}, DefaultEvents), specEvents),
        components: components2
      });
      return Result.value(build$2(completeSpec));
    };
    var text = function(textContent) {
      var element2 = SugarElement.fromText(textContent);
      return external$2({ element: element2 });
    };
    var external$2 = function(spec) {
      var extSpec = asRawOrDie$1("external.component", objOfOnly([
        required$1("element"),
        option("uid")
      ]), spec);
      var systemApi = Cell(NoContextApi());
      var connect = function(newApi) {
        systemApi.set(newApi);
      };
      var disconnect = function() {
        systemApi.set(NoContextApi(function() {
          return me2;
        }));
      };
      var uid2 = extSpec.uid.getOrThunk(function() {
        return generate$5("external");
      });
      writeOnly(extSpec.element, uid2);
      var me2 = {
        uid: uid2,
        getSystem: systemApi.get,
        config: Optional.none,
        hasConfigured: never,
        connect,
        disconnect,
        getApis: function() {
          return {};
        },
        element: extSpec.element,
        spec,
        readState: constant$1("No state"),
        syncComponents: noop3,
        components: constant$1([]),
        events: {}
      };
      return premade$1(me2);
    };
    var uids = generate$5;
    var isSketchSpec$1 = function(spec) {
      return has$2(spec, "uid");
    };
    var build$1 = function(spec) {
      return getPremade(spec).getOrThunk(function() {
        var userSpecWithUid = isSketchSpec$1(spec) ? spec : __assign({ uid: uids("") }, spec);
        return buildFromSpec(userSpecWithUid).getOrDie();
      });
    };
    var premade = premade$1;
    function ClosestOrAncestor(is2, ancestor2, scope, a2, isRoot) {
      if (is2(scope, a2)) {
        return Optional.some(scope);
      } else if (isFunction2(isRoot) && isRoot(scope)) {
        return Optional.none();
      } else {
        return ancestor2(scope, a2, isRoot);
      }
    }
    var ancestor$1 = function(scope, predicate, isRoot) {
      var element2 = scope.dom;
      var stop2 = isFunction2(isRoot) ? isRoot : never;
      while (element2.parentNode) {
        element2 = element2.parentNode;
        var el = SugarElement.fromDom(element2);
        if (predicate(el)) {
          return Optional.some(el);
        } else if (stop2(el)) {
          break;
        }
      }
      return Optional.none();
    };
    var closest$3 = function(scope, predicate, isRoot) {
      var is2 = function(s2, test) {
        return test(s2);
      };
      return ClosestOrAncestor(is2, ancestor$1, scope, predicate, isRoot);
    };
    var child$1 = function(scope, predicate) {
      var pred = function(node) {
        return predicate(SugarElement.fromDom(node));
      };
      var result = find$5(scope.dom.childNodes, pred);
      return result.map(SugarElement.fromDom);
    };
    var descendant$1 = function(scope, predicate) {
      var descend = function(node) {
        for (var i2 = 0; i2 < node.childNodes.length; i2++) {
          var child_1 = SugarElement.fromDom(node.childNodes[i2]);
          if (predicate(child_1)) {
            return Optional.some(child_1);
          }
          var res = descend(node.childNodes[i2]);
          if (res.isSome()) {
            return res;
          }
        }
        return Optional.none();
      };
      return descend(scope.dom);
    };
    var closest$2 = function(scope, predicate, isRoot) {
      return closest$3(scope, predicate, isRoot).isSome();
    };
    var ancestor = function(scope, selector, isRoot) {
      return ancestor$1(scope, function(e2) {
        return is(e2, selector);
      }, isRoot);
    };
    var child = function(scope, selector) {
      return child$1(scope, function(e2) {
        return is(e2, selector);
      });
    };
    var descendant = function(scope, selector) {
      return one(selector, scope);
    };
    var closest$1 = function(scope, selector, isRoot) {
      var is$12 = function(element2, selector2) {
        return is(element2, selector2);
      };
      return ClosestOrAncestor(is$12, ancestor, scope, selector, isRoot);
    };
    var find$1 = function(queryElem) {
      var dependent = closest$3(queryElem, function(elem) {
        if (!isElement$2(elem)) {
          return false;
        }
        var id2 = get$d(elem, "id");
        return id2 !== void 0 && id2.indexOf("aria-owns") > -1;
      });
      return dependent.bind(function(dep) {
        var id2 = get$d(dep, "id");
        var dos = getRootNode(dep);
        return descendant(dos, '[aria-owns="' + id2 + '"]');
      });
    };
    var manager = function() {
      var ariaId = generate$6("aria-owns");
      var link = function(elem) {
        set$8(elem, "aria-owns", ariaId);
      };
      var unlink = function(elem) {
        remove$7(elem, "aria-owns");
      };
      return {
        id: ariaId,
        link,
        unlink
      };
    };
    var isAriaPartOf = function(component, queryElem) {
      return find$1(queryElem).exists(function(owner2) {
        return isPartOf$1(component, owner2);
      });
    };
    var isPartOf$1 = function(component, queryElem) {
      return closest$2(queryElem, function(el) {
        return eq2(el, component.element);
      }, never) || isAriaPartOf(component, queryElem);
    };
    var unknown = "unknown";
    var EventConfiguration;
    (function(EventConfiguration2) {
      EventConfiguration2[EventConfiguration2["STOP"] = 0] = "STOP";
      EventConfiguration2[EventConfiguration2["NORMAL"] = 1] = "NORMAL";
      EventConfiguration2[EventConfiguration2["LOGGING"] = 2] = "LOGGING";
    })(EventConfiguration || (EventConfiguration = {}));
    var eventConfig = Cell({});
    var makeEventLogger = function(eventName, initialTarget) {
      var sequence2 = [];
      var startTime = new Date().getTime();
      return {
        logEventCut: function(_name, target, purpose) {
          sequence2.push({
            outcome: "cut",
            target,
            purpose
          });
        },
        logEventStopped: function(_name, target, purpose) {
          sequence2.push({
            outcome: "stopped",
            target,
            purpose
          });
        },
        logNoParent: function(_name, target, purpose) {
          sequence2.push({
            outcome: "no-parent",
            target,
            purpose
          });
        },
        logEventNoHandlers: function(_name, target) {
          sequence2.push({
            outcome: "no-handlers-left",
            target
          });
        },
        logEventResponse: function(_name, target, purpose) {
          sequence2.push({
            outcome: "response",
            purpose,
            target
          });
        },
        write: function() {
          var finishTime = new Date().getTime();
          if (contains$2([
            "mousemove",
            "mouseover",
            "mouseout",
            systemInit()
          ], eventName)) {
            return;
          }
          console.log(eventName, {
            event: eventName,
            time: finishTime - startTime,
            target: initialTarget.dom,
            sequence: map$2(sequence2, function(s2) {
              if (!contains$2([
                "cut",
                "stopped",
                "response"
              ], s2.outcome)) {
                return s2.outcome;
              } else {
                return "{" + s2.purpose + "} " + s2.outcome + " at (" + element(s2.target) + ")";
              }
            })
          });
        }
      };
    };
    var processEvent = function(eventName, initialTarget, f2) {
      var status = get$e(eventConfig.get(), eventName).orThunk(function() {
        var patterns2 = keys(eventConfig.get());
        return findMap(patterns2, function(p2) {
          return eventName.indexOf(p2) > -1 ? Optional.some(eventConfig.get()[p2]) : Optional.none();
        });
      }).getOr(EventConfiguration.NORMAL);
      switch (status) {
        case EventConfiguration.NORMAL:
          return f2(noLogger());
        case EventConfiguration.LOGGING: {
          var logger = makeEventLogger(eventName, initialTarget);
          var output2 = f2(logger);
          logger.write();
          return output2;
        }
        case EventConfiguration.STOP:
          return true;
      }
    };
    var path = [
      "alloy/data/Fields",
      "alloy/debugging/Debugging"
    ];
    var getTrace = function() {
      var err = new Error();
      if (err.stack !== void 0) {
        var lines = err.stack.split("\n");
        return find$5(lines, function(line) {
          return line.indexOf("alloy") > 0 && !exists(path, function(p2) {
            return line.indexOf(p2) > -1;
          });
        }).getOr(unknown);
      } else {
        return unknown;
      }
    };
    var ignoreEvent = {
      logEventCut: noop3,
      logEventStopped: noop3,
      logNoParent: noop3,
      logEventNoHandlers: noop3,
      logEventResponse: noop3,
      write: noop3
    };
    var monitorEvent = function(eventName, initialTarget, f2) {
      return processEvent(eventName, initialTarget, f2);
    };
    var noLogger = constant$1(ignoreEvent);
    var menuFields = constant$1([
      required$1("menu"),
      required$1("selectedMenu")
    ]);
    var itemFields = constant$1([
      required$1("item"),
      required$1("selectedItem")
    ]);
    constant$1(objOf(itemFields().concat(menuFields())));
    var itemSchema$3 = constant$1(objOf(itemFields()));
    var _initSize = requiredObjOf("initSize", [
      required$1("numColumns"),
      required$1("numRows")
    ]);
    var itemMarkers = function() {
      return requiredOf("markers", itemSchema$3());
    };
    var tieredMenuMarkers = function() {
      return requiredObjOf("markers", [required$1("backgroundMenu")].concat(menuFields()).concat(itemFields()));
    };
    var markers$1 = function(required2) {
      return requiredObjOf("markers", map$2(required2, required$1));
    };
    var onPresenceHandler = function(label, fieldName, presence) {
      getTrace();
      return field$1(fieldName, fieldName, presence, valueOf(function(f2) {
        return Result.value(function() {
          var args = [];
          for (var _i2 = 0; _i2 < arguments.length; _i2++) {
            args[_i2] = arguments[_i2];
          }
          return f2.apply(void 0, args);
        });
      }));
    };
    var onHandler = function(fieldName) {
      return onPresenceHandler("onHandler", fieldName, defaulted$1(noop3));
    };
    var onKeyboardHandler = function(fieldName) {
      return onPresenceHandler("onKeyboardHandler", fieldName, defaulted$1(Optional.none));
    };
    var onStrictHandler = function(fieldName) {
      return onPresenceHandler("onHandler", fieldName, required$2());
    };
    var onStrictKeyboardHandler = function(fieldName) {
      return onPresenceHandler("onKeyboardHandler", fieldName, required$2());
    };
    var output$1 = function(name2, value2) {
      return customField(name2, constant$1(value2));
    };
    var snapshot = function(name2) {
      return customField(name2, identity$1);
    };
    var initSize = constant$1(_initSize);
    var nu$6 = function(x2, y2, bubble, direction, placement2, boundsRestriction2, labelPrefix2, alwaysFit) {
      if (alwaysFit === void 0) {
        alwaysFit = false;
      }
      return {
        x: x2,
        y: y2,
        bubble,
        direction,
        placement: placement2,
        restriction: boundsRestriction2,
        label: labelPrefix2 + "-" + placement2,
        alwaysFit
      };
    };
    var adt$a = Adt.generate([
      { southeast: [] },
      { southwest: [] },
      { northeast: [] },
      { northwest: [] },
      { south: [] },
      { north: [] },
      { east: [] },
      { west: [] }
    ]);
    var cata$2 = function(subject, southeast2, southwest2, northeast2, northwest2, south2, north2, east2, west2) {
      return subject.fold(southeast2, southwest2, northeast2, northwest2, south2, north2, east2, west2);
    };
    var cataVertical = function(subject, south2, middle, north2) {
      return subject.fold(south2, south2, north2, north2, south2, north2, middle, middle);
    };
    var cataHorizontal = function(subject, east2, middle, west2) {
      return subject.fold(east2, west2, east2, west2, middle, middle, east2, west2);
    };
    var southeast$3 = adt$a.southeast;
    var southwest$3 = adt$a.southwest;
    var northeast$3 = adt$a.northeast;
    var northwest$3 = adt$a.northwest;
    var south$3 = adt$a.south;
    var north$3 = adt$a.north;
    var east$3 = adt$a.east;
    var west$3 = adt$a.west;
    var cycleBy = function(value2, delta, min3, max3) {
      var r3 = value2 + delta;
      if (r3 > max3) {
        return min3;
      } else if (r3 < min3) {
        return max3;
      } else {
        return r3;
      }
    };
    var clamp$1 = function(value2, min3, max3) {
      return Math.min(Math.max(value2, min3), max3);
    };
    var getRestriction = function(anchor2, restriction) {
      switch (restriction) {
        case 1:
          return anchor2.x;
        case 0:
          return anchor2.x + anchor2.width;
        case 2:
          return anchor2.y;
        case 3:
          return anchor2.y + anchor2.height;
      }
    };
    var boundsRestriction = function(anchor2, restrictions) {
      return mapToObject([
        "left",
        "right",
        "top",
        "bottom"
      ], function(dir) {
        return get$e(restrictions, dir).map(function(restriction) {
          return getRestriction(anchor2, restriction);
        });
      });
    };
    var adjustBounds = function(bounds$12, restriction, bubbleOffset) {
      var applyRestriction = function(dir, current) {
        return restriction[dir].map(function(pos) {
          var isVerticalAxis = dir === "top" || dir === "bottom";
          var offset3 = isVerticalAxis ? bubbleOffset.top : bubbleOffset.left;
          var comparator = dir === "left" || dir === "top" ? Math.max : Math.min;
          var newPos = comparator(pos, current) + offset3;
          return isVerticalAxis ? clamp$1(newPos, bounds$12.y, bounds$12.bottom) : clamp$1(newPos, bounds$12.x, bounds$12.right);
        }).getOr(current);
      };
      var adjustedLeft = applyRestriction("left", bounds$12.x);
      var adjustedTop = applyRestriction("top", bounds$12.y);
      var adjustedRight = applyRestriction("right", bounds$12.right);
      var adjustedBottom = applyRestriction("bottom", bounds$12.bottom);
      return bounds(adjustedLeft, adjustedTop, adjustedRight - adjustedLeft, adjustedBottom - adjustedTop);
    };
    var labelPrefix$2 = "layout";
    var eastX$1 = function(anchor2) {
      return anchor2.x;
    };
    var middleX$1 = function(anchor2, element2) {
      return anchor2.x + anchor2.width / 2 - element2.width / 2;
    };
    var westX$1 = function(anchor2, element2) {
      return anchor2.x + anchor2.width - element2.width;
    };
    var northY$2 = function(anchor2, element2) {
      return anchor2.y - element2.height;
    };
    var southY$2 = function(anchor2) {
      return anchor2.y + anchor2.height;
    };
    var centreY$1 = function(anchor2, element2) {
      return anchor2.y + anchor2.height / 2 - element2.height / 2;
    };
    var eastEdgeX$1 = function(anchor2) {
      return anchor2.x + anchor2.width;
    };
    var westEdgeX$1 = function(anchor2, element2) {
      return anchor2.x - element2.width;
    };
    var southeast$2 = function(anchor2, element2, bubbles) {
      return nu$6(eastX$1(anchor2), southY$2(anchor2), bubbles.southeast(), southeast$3(), "southeast", boundsRestriction(anchor2, {
        left: 1,
        top: 3
      }), labelPrefix$2);
    };
    var southwest$2 = function(anchor2, element2, bubbles) {
      return nu$6(westX$1(anchor2, element2), southY$2(anchor2), bubbles.southwest(), southwest$3(), "southwest", boundsRestriction(anchor2, {
        right: 0,
        top: 3
      }), labelPrefix$2);
    };
    var northeast$2 = function(anchor2, element2, bubbles) {
      return nu$6(eastX$1(anchor2), northY$2(anchor2, element2), bubbles.northeast(), northeast$3(), "northeast", boundsRestriction(anchor2, {
        left: 1,
        bottom: 2
      }), labelPrefix$2);
    };
    var northwest$2 = function(anchor2, element2, bubbles) {
      return nu$6(westX$1(anchor2, element2), northY$2(anchor2, element2), bubbles.northwest(), northwest$3(), "northwest", boundsRestriction(anchor2, {
        right: 0,
        bottom: 2
      }), labelPrefix$2);
    };
    var north$2 = function(anchor2, element2, bubbles) {
      return nu$6(middleX$1(anchor2, element2), northY$2(anchor2, element2), bubbles.north(), north$3(), "north", boundsRestriction(anchor2, { bottom: 2 }), labelPrefix$2);
    };
    var south$2 = function(anchor2, element2, bubbles) {
      return nu$6(middleX$1(anchor2, element2), southY$2(anchor2), bubbles.south(), south$3(), "south", boundsRestriction(anchor2, { top: 3 }), labelPrefix$2);
    };
    var east$2 = function(anchor2, element2, bubbles) {
      return nu$6(eastEdgeX$1(anchor2), centreY$1(anchor2, element2), bubbles.east(), east$3(), "east", boundsRestriction(anchor2, { left: 0 }), labelPrefix$2);
    };
    var west$2 = function(anchor2, element2, bubbles) {
      return nu$6(westEdgeX$1(anchor2, element2), centreY$1(anchor2, element2), bubbles.west(), west$3(), "west", boundsRestriction(anchor2, { right: 1 }), labelPrefix$2);
    };
    var all$1 = function() {
      return [
        southeast$2,
        southwest$2,
        northeast$2,
        northwest$2,
        south$2,
        north$2,
        east$2,
        west$2
      ];
    };
    var allRtl$1 = function() {
      return [
        southwest$2,
        southeast$2,
        northwest$2,
        northeast$2,
        south$2,
        north$2,
        east$2,
        west$2
      ];
    };
    var aboveOrBelow = function() {
      return [
        northeast$2,
        northwest$2,
        southeast$2,
        southwest$2,
        north$2,
        south$2
      ];
    };
    var aboveOrBelowRtl = function() {
      return [
        northwest$2,
        northeast$2,
        southwest$2,
        southeast$2,
        north$2,
        south$2
      ];
    };
    var belowOrAbove = function() {
      return [
        southeast$2,
        southwest$2,
        northeast$2,
        northwest$2,
        south$2,
        north$2
      ];
    };
    var belowOrAboveRtl = function() {
      return [
        southwest$2,
        southeast$2,
        northwest$2,
        northeast$2,
        south$2,
        north$2
      ];
    };
    var chooseChannels = function(channels, message) {
      return message.universal ? channels : filter$2(channels, function(ch) {
        return contains$2(message.channels, ch);
      });
    };
    var events$h = function(receiveConfig) {
      return derive$2([run$1(receive(), function(component, message) {
        var channelMap = receiveConfig.channels;
        var channels = keys(channelMap);
        var receivingData = message;
        var targetChannels = chooseChannels(channels, receivingData);
        each$1(targetChannels, function(ch) {
          var channelInfo = channelMap[ch];
          var channelSchema = channelInfo.schema;
          var data = asRawOrDie$1("channel[" + ch + "] data\nReceiver: " + element(component.element), channelSchema, receivingData.data);
          channelInfo.onReceive(component, data);
        });
      })]);
    };
    var ActiveReceiving = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      events: events$h
    });
    var ReceivingSchema = [requiredOf("channels", setOf(Result.value, objOfOnly([
      onStrictHandler("onReceive"),
      defaulted("schema", anyValue())
    ])))];
    var executeEvent = function(bConfig, bState, executor) {
      return runOnExecute$1(function(component) {
        executor(component, bConfig, bState);
      });
    };
    var loadEvent = function(bConfig, bState, f2) {
      return runOnInit(function(component, _simulatedEvent) {
        f2(component, bConfig, bState);
      });
    };
    var create$8 = function(schema2, name2, active2, apis, extra, state) {
      var configSchema = objOfOnly(schema2);
      var schemaSchema = optionObjOf(name2, [optionObjOfOnly("config", schema2)]);
      return doCreate(configSchema, schemaSchema, name2, active2, apis, extra, state);
    };
    var createModes$1 = function(modes, name2, active2, apis, extra, state) {
      var configSchema = modes;
      var schemaSchema = optionObjOf(name2, [optionOf("config", modes)]);
      return doCreate(configSchema, schemaSchema, name2, active2, apis, extra, state);
    };
    var wrapApi = function(bName, apiFunction, apiName) {
      var f2 = function(component) {
        var rest = [];
        for (var _i2 = 1; _i2 < arguments.length; _i2++) {
          rest[_i2 - 1] = arguments[_i2];
        }
        var args = [component].concat(rest);
        return component.config({ name: constant$1(bName) }).fold(function() {
          throw new Error("We could not find any behaviour configuration for: " + bName + ". Using API: " + apiName);
        }, function(info) {
          var rest2 = Array.prototype.slice.call(args, 1);
          return apiFunction.apply(void 0, [
            component,
            info.config,
            info.state
          ].concat(rest2));
        });
      };
      return markAsBehaviourApi(f2, apiName, apiFunction);
    };
    var revokeBehaviour = function(name2) {
      return {
        key: name2,
        value: void 0
      };
    };
    var doCreate = function(configSchema, schemaSchema, name2, active2, apis, extra, state) {
      var getConfig2 = function(info) {
        return hasNonNullableKey(info, name2) ? info[name2]() : Optional.none();
      };
      var wrappedApis = map$12(apis, function(apiF, apiName) {
        return wrapApi(name2, apiF, apiName);
      });
      var wrappedExtra = map$12(extra, function(extraF, extraName) {
        return markAsExtraApi(extraF, extraName);
      });
      var me2 = __assign(__assign(__assign({}, wrappedExtra), wrappedApis), {
        revoke: curry(revokeBehaviour, name2),
        config: function(spec) {
          var prepared = asRawOrDie$1(name2 + "-config", configSchema, spec);
          return {
            key: name2,
            value: {
              config: prepared,
              me: me2,
              configAsRaw: cached(function() {
                return asRawOrDie$1(name2 + "-config", configSchema, spec);
              }),
              initialConfig: spec,
              state
            }
          };
        },
        schema: constant$1(schemaSchema),
        exhibit: function(info, base2) {
          return lift2(getConfig2(info), get$e(active2, "exhibit"), function(behaviourInfo, exhibitor) {
            return exhibitor(base2, behaviourInfo.config, behaviourInfo.state);
          }).getOrThunk(function() {
            return nu$7({});
          });
        },
        name: constant$1(name2),
        handlers: function(info) {
          return getConfig2(info).map(function(behaviourInfo) {
            var getEvents2 = get$e(active2, "events").getOr(function() {
              return {};
            });
            return getEvents2(behaviourInfo.config, behaviourInfo.state);
          }).getOr({});
        }
      });
      return me2;
    };
    var derive$1 = function(capabilities) {
      return wrapAll(capabilities);
    };
    var simpleSchema = objOfOnly([
      required$1("fields"),
      required$1("name"),
      defaulted("active", {}),
      defaulted("apis", {}),
      defaulted("state", NoState),
      defaulted("extra", {})
    ]);
    var create$7 = function(data) {
      var value2 = asRawOrDie$1("Creating behaviour: " + data.name, simpleSchema, data);
      return create$8(value2.fields, value2.name, value2.active, value2.apis, value2.extra, value2.state);
    };
    var modeSchema = objOfOnly([
      required$1("branchKey"),
      required$1("branches"),
      required$1("name"),
      defaulted("active", {}),
      defaulted("apis", {}),
      defaulted("state", NoState),
      defaulted("extra", {})
    ]);
    var createModes = function(data) {
      var value2 = asRawOrDie$1("Creating behaviour: " + data.name, modeSchema, data);
      return createModes$1(choose$1(value2.branchKey, value2.branches), value2.name, value2.active, value2.apis, value2.extra, value2.state);
    };
    var revoke = constant$1(void 0);
    var Receiving = create$7({
      fields: ReceivingSchema,
      name: "receiving",
      active: ActiveReceiving
    });
    var exhibit$6 = function(base2, posConfig) {
      return nu$7({
        classes: [],
        styles: posConfig.useFixed() ? {} : { position: "relative" }
      });
    };
    var ActivePosition = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      exhibit: exhibit$6
    });
    var getDocument = function() {
      return SugarElement.fromDom(document);
    };
    var focus$3 = function(element2) {
      return element2.dom.focus();
    };
    var blur$1 = function(element2) {
      return element2.dom.blur();
    };
    var hasFocus = function(element2) {
      var root = getRootNode(element2).dom;
      return element2.dom === root.activeElement;
    };
    var active = function(root) {
      if (root === void 0) {
        root = getDocument();
      }
      return Optional.from(root.dom.activeElement).map(SugarElement.fromDom);
    };
    var search = function(element2) {
      return active(getRootNode(element2)).filter(function(e2) {
        return element2.dom.contains(e2.dom);
      });
    };
    var preserve$1 = function(f2, container) {
      var dos = getRootNode(container);
      var refocus = active(dos).bind(function(focused) {
        var hasFocus2 = function(elem) {
          return eq2(focused, elem);
        };
        return hasFocus2(container) ? Optional.some(container) : descendant$1(container, hasFocus2);
      });
      var result = f2(container);
      refocus.each(function(oldFocus) {
        active(dos).filter(function(newFocus) {
          return eq2(newFocus, oldFocus);
        }).fold(function() {
          focus$3(oldFocus);
        }, noop3);
      });
      return result;
    };
    var NuPositionCss = function(position2, left3, top3, right3, bottom3) {
      var toPx = function(num) {
        return num + "px";
      };
      return {
        position: position2,
        left: left3.map(toPx),
        top: top3.map(toPx),
        right: right3.map(toPx),
        bottom: bottom3.map(toPx)
      };
    };
    var toOptions = function(position2) {
      return __assign(__assign({}, position2), { position: Optional.some(position2.position) });
    };
    var applyPositionCss = function(element2, position2) {
      setOptions(element2, toOptions(position2));
    };
    var adt$9 = Adt.generate([
      { none: [] },
      {
        relative: [
          "x",
          "y",
          "width",
          "height"
        ]
      },
      {
        fixed: [
          "x",
          "y",
          "width",
          "height"
        ]
      }
    ]);
    var positionWithDirection = function(posName, decision, x2, y2, width2, height2) {
      var decisionRect = decision.rect;
      var decisionX = decisionRect.x - x2;
      var decisionY = decisionRect.y - y2;
      var decisionWidth = decisionRect.width;
      var decisionHeight = decisionRect.height;
      var decisionRight = width2 - (decisionX + decisionWidth);
      var decisionBottom = height2 - (decisionY + decisionHeight);
      var left3 = Optional.some(decisionX);
      var top3 = Optional.some(decisionY);
      var right3 = Optional.some(decisionRight);
      var bottom3 = Optional.some(decisionBottom);
      var none2 = Optional.none();
      return cata$2(decision.direction, function() {
        return NuPositionCss(posName, left3, top3, none2, none2);
      }, function() {
        return NuPositionCss(posName, none2, top3, right3, none2);
      }, function() {
        return NuPositionCss(posName, left3, none2, none2, bottom3);
      }, function() {
        return NuPositionCss(posName, none2, none2, right3, bottom3);
      }, function() {
        return NuPositionCss(posName, left3, top3, none2, none2);
      }, function() {
        return NuPositionCss(posName, left3, none2, none2, bottom3);
      }, function() {
        return NuPositionCss(posName, left3, top3, none2, none2);
      }, function() {
        return NuPositionCss(posName, none2, top3, right3, none2);
      });
    };
    var reposition = function(origin, decision) {
      return origin.fold(function() {
        var decisionRect = decision.rect;
        return NuPositionCss("absolute", Optional.some(decisionRect.x), Optional.some(decisionRect.y), Optional.none(), Optional.none());
      }, function(x2, y2, width2, height2) {
        return positionWithDirection("absolute", decision, x2, y2, width2, height2);
      }, function(x2, y2, width2, height2) {
        return positionWithDirection("fixed", decision, x2, y2, width2, height2);
      });
    };
    var toBox = function(origin, element2) {
      var rel = curry(find$2, element2);
      var position2 = origin.fold(rel, rel, function() {
        var scroll = get$9();
        return find$2(element2).translate(-scroll.left, -scroll.top);
      });
      var width2 = getOuter$1(element2);
      var height2 = getOuter$2(element2);
      return bounds(position2.left, position2.top, width2, height2);
    };
    var viewport2 = function(origin, getBounds3) {
      return getBounds3.fold(function() {
        return origin.fold(win, win, bounds);
      }, function(b3) {
        return origin.fold(b3, b3, function() {
          var bounds$12 = b3();
          var pos = translate$2(origin, bounds$12.x, bounds$12.y);
          return bounds(pos.left, pos.top, bounds$12.width, bounds$12.height);
        });
      });
    };
    var translate$2 = function(origin, x2, y2) {
      var pos = SugarPosition(x2, y2);
      var removeScroll = function() {
        var outerScroll = get$9();
        return pos.translate(-outerScroll.left, -outerScroll.top);
      };
      return origin.fold(constant$1(pos), constant$1(pos), removeScroll);
    };
    var cata$1 = function(subject, onNone, onRelative, onFixed) {
      return subject.fold(onNone, onRelative, onFixed);
    };
    adt$9.none;
    var relative$1 = adt$9.relative;
    var fixed$1 = adt$9.fixed;
    var anchor = function(anchorBox, origin) {
      return {
        anchorBox,
        origin
      };
    };
    var box = function(anchorBox, origin) {
      return anchor(anchorBox, origin);
    };
    var placementAttribute = "data-alloy-placement";
    var setPlacement$1 = function(element2, placement2) {
      set$8(element2, placementAttribute, placement2);
    };
    var getPlacement = function(element2) {
      return getOpt(element2, placementAttribute);
    };
    var reset$2 = function(element2) {
      return remove$7(element2, placementAttribute);
    };
    var adt$8 = Adt.generate([
      { fit: ["reposition"] },
      {
        nofit: [
          "reposition",
          "visibleW",
          "visibleH",
          "isVisible"
        ]
      }
    ]);
    var determinePosition = function(box2, bounds2) {
      var boundsX = bounds2.x, boundsY = bounds2.y, boundsRight = bounds2.right, boundsBottom = bounds2.bottom;
      var x2 = box2.x, y2 = box2.y, right3 = box2.right, bottom3 = box2.bottom, width2 = box2.width, height2 = box2.height;
      var xInBounds = x2 >= boundsX && x2 <= boundsRight;
      var yInBounds = y2 >= boundsY && y2 <= boundsBottom;
      var originInBounds = xInBounds && yInBounds;
      var rightInBounds = right3 <= boundsRight && right3 >= boundsX;
      var bottomInBounds = bottom3 <= boundsBottom && bottom3 >= boundsY;
      var sizeInBounds = rightInBounds && bottomInBounds;
      var visibleW = Math.min(width2, x2 >= boundsX ? boundsRight - x2 : right3 - boundsX);
      var visibleH = Math.min(height2, y2 >= boundsY ? boundsBottom - y2 : bottom3 - boundsY);
      return {
        originInBounds,
        sizeInBounds,
        visibleW,
        visibleH
      };
    };
    var calcReposition = function(box2, bounds$12) {
      var boundsX = bounds$12.x, boundsY = bounds$12.y, boundsRight = bounds$12.right, boundsBottom = bounds$12.bottom;
      var x2 = box2.x, y2 = box2.y, width2 = box2.width, height2 = box2.height;
      var maxX2 = Math.max(boundsX, boundsRight - width2);
      var maxY2 = Math.max(boundsY, boundsBottom - height2);
      var restrictedX = clamp$1(x2, boundsX, maxX2);
      var restrictedY = clamp$1(y2, boundsY, maxY2);
      var restrictedWidth = Math.min(restrictedX + width2, boundsRight) - restrictedX;
      var restrictedHeight = Math.min(restrictedY + height2, boundsBottom) - restrictedY;
      return bounds(restrictedX, restrictedY, restrictedWidth, restrictedHeight);
    };
    var calcMaxSizes = function(direction, box2, bounds2) {
      var upAvailable = constant$1(box2.bottom - bounds2.y);
      var downAvailable = constant$1(bounds2.bottom - box2.y);
      var maxHeight = cataVertical(direction, downAvailable, downAvailable, upAvailable);
      var westAvailable = constant$1(box2.right - bounds2.x);
      var eastAvailable = constant$1(bounds2.right - box2.x);
      var maxWidth = cataHorizontal(direction, eastAvailable, eastAvailable, westAvailable);
      return {
        maxWidth,
        maxHeight
      };
    };
    var attempt = function(candidate, width2, height2, bounds$12) {
      var bubble = candidate.bubble;
      var bubbleOffset = bubble.offset;
      var adjustedBounds = adjustBounds(bounds$12, candidate.restriction, bubbleOffset);
      var newX = candidate.x + bubbleOffset.left;
      var newY = candidate.y + bubbleOffset.top;
      var box2 = bounds(newX, newY, width2, height2);
      var _a2 = determinePosition(box2, adjustedBounds), originInBounds = _a2.originInBounds, sizeInBounds = _a2.sizeInBounds, visibleW = _a2.visibleW, visibleH = _a2.visibleH;
      var fits = originInBounds && sizeInBounds;
      var fittedBox = fits ? box2 : calcReposition(box2, adjustedBounds);
      var isPartlyVisible = fittedBox.width > 0 && fittedBox.height > 0;
      var _b = calcMaxSizes(candidate.direction, fittedBox, bounds$12), maxWidth = _b.maxWidth, maxHeight = _b.maxHeight;
      var reposition2 = {
        rect: fittedBox,
        maxHeight,
        maxWidth,
        direction: candidate.direction,
        placement: candidate.placement,
        classes: {
          on: bubble.classesOn,
          off: bubble.classesOff
        },
        layout: candidate.label,
        testY: newY
      };
      return fits || candidate.alwaysFit ? adt$8.fit(reposition2) : adt$8.nofit(reposition2, visibleW, visibleH, isPartlyVisible);
    };
    var attempts = function(element2, candidates, anchorBox, elementBox, bubbles, bounds2) {
      var panelWidth = elementBox.width;
      var panelHeight = elementBox.height;
      var attemptBestFit = function(layout2, reposition2, visibleW, visibleH, isVisible3) {
        var next = layout2(anchorBox, elementBox, bubbles, element2, bounds2);
        var attemptLayout = attempt(next, panelWidth, panelHeight, bounds2);
        return attemptLayout.fold(constant$1(attemptLayout), function(newReposition, newVisibleW, newVisibleH, newIsVisible) {
          var improved = isVisible3 === newIsVisible ? newVisibleH > visibleH || newVisibleW > visibleW : !isVisible3 && newIsVisible;
          return improved ? attemptLayout : adt$8.nofit(reposition2, visibleW, visibleH, isVisible3);
        });
      };
      var abc = foldl(candidates, function(b3, a2) {
        var bestNext = curry(attemptBestFit, a2);
        return b3.fold(constant$1(b3), bestNext);
      }, adt$8.nofit({
        rect: anchorBox,
        maxHeight: elementBox.height,
        maxWidth: elementBox.width,
        direction: southeast$3(),
        placement: "southeast",
        classes: {
          on: [],
          off: []
        },
        layout: "none",
        testY: anchorBox.y
      }, -1, -1, false));
      return abc.fold(identity$1, identity$1);
    };
    var singleton = function(doRevoke) {
      var subject = Cell(Optional.none());
      var revoke2 = function() {
        return subject.get().each(doRevoke);
      };
      var clear2 = function() {
        revoke2();
        subject.set(Optional.none());
      };
      var isSet = function() {
        return subject.get().isSome();
      };
      var get2 = function() {
        return subject.get();
      };
      var set3 = function(s2) {
        revoke2();
        subject.set(Optional.some(s2));
      };
      return {
        clear: clear2,
        isSet,
        get: get2,
        set: set3
      };
    };
    var destroyable = function() {
      return singleton(function(s2) {
        return s2.destroy();
      });
    };
    var unbindable = function() {
      return singleton(function(s2) {
        return s2.unbind();
      });
    };
    var api$1 = function() {
      var subject = destroyable();
      var run2 = function(f2) {
        return subject.get().each(f2);
      };
      return __assign(__assign({}, subject), { run: run2 });
    };
    var value$1 = function() {
      var subject = singleton(noop3);
      var on3 = function(f2) {
        return subject.get().each(f2);
      };
      return __assign(__assign({}, subject), { on: on3 });
    };
    var filter = always;
    var bind = function(element2, event, handler) {
      return bind$2(element2, event, filter, handler);
    };
    var capture = function(element2, event, handler) {
      return capture$1(element2, event, filter, handler);
    };
    var fromRawEvent = fromRawEvent$1;
    var properties = [
      "top",
      "bottom",
      "right",
      "left"
    ];
    var timerAttr = "data-alloy-transition-timer";
    var isTransitioning$1 = function(element2, transition) {
      return hasAll(element2, transition.classes);
    };
    var shouldApplyTransitionCss = function(transition, decision, lastPlacement) {
      return lastPlacement.exists(function(placer) {
        var mode = transition.mode;
        return mode === "all" ? true : placer[mode] !== decision[mode];
      });
    };
    var hasChanges = function(position2, intermediate) {
      var round4 = function(value2) {
        return parseFloat(value2).toFixed(3);
      };
      return find$4(intermediate, function(value2, key) {
        var newValue = position2[key].map(round4);
        var val = value2.map(round4);
        return !equals(newValue, val);
      }).isSome();
    };
    var getTransitionDuration = function(element2) {
      var get2 = function(name2) {
        var style = get$c(element2, name2);
        var times = isString(style) ? style.split(/\s*,\s*/) : [];
        return filter$2(times, isNotEmpty);
      };
      var parse4 = function(value2) {
        if (isString(value2) && /^[\d.]+/.test(value2)) {
          var num = parseFloat(value2);
          return endsWith(value2, "ms") ? num : num * 1e3;
        } else {
          return 0;
        }
      };
      var delay = get2("transition-delay");
      var duration = get2("transition-duration");
      return foldl(duration, function(acc, dur, i2) {
        var time = parse4(delay[i2]) + parse4(dur);
        return Math.max(acc, time);
      }, 0);
    };
    var setupTransitionListeners = function(element2, transition) {
      var transitionEnd = unbindable();
      var transitionCancel = unbindable();
      var timer;
      var isSourceTransition = function(e2) {
        var _a2;
        var pseudoElement = (_a2 = e2.raw.pseudoElement) !== null && _a2 !== void 0 ? _a2 : "";
        return eq2(e2.target, element2) && isEmpty(pseudoElement) && contains$2(properties, e2.raw.propertyName);
      };
      var transitionDone = function(e2) {
        if (isNullable(e2) || isSourceTransition(e2)) {
          transitionEnd.clear();
          transitionCancel.clear();
          var type2 = e2 === null || e2 === void 0 ? void 0 : e2.raw.type;
          if (isNullable(type2) || type2 === transitionend()) {
            clearTimeout(timer);
            remove$7(element2, timerAttr);
            remove$1(element2, transition.classes);
          }
        }
      };
      var transitionStarted = function() {
        transitionEnd.set(bind(element2, transitionend(), transitionDone));
        transitionCancel.set(bind(element2, transitioncancel(), transitionDone));
      };
      if ("ontransitionstart" in element2.dom) {
        var transitionStart_1 = bind(element2, transitionstart(), function(e2) {
          if (isSourceTransition(e2)) {
            transitionStart_1.unbind();
            transitionStarted();
          }
        });
      } else {
        transitionStarted();
      }
      var duration = getTransitionDuration(element2);
      requestAnimationFrame(function() {
        timer = setTimeout(transitionDone, duration + 17);
        set$8(element2, timerAttr, timer);
      });
    };
    var startTransitioning = function(element2, transition) {
      add$1(element2, transition.classes);
      getOpt(element2, timerAttr).each(function(timerId) {
        clearTimeout(parseInt(timerId, 10));
        remove$7(element2, timerAttr);
      });
      setupTransitionListeners(element2, transition);
    };
    var applyTransitionCss = function(element2, origin, position2, transition, decision, lastPlacement) {
      var shouldTransition = shouldApplyTransitionCss(transition, decision, lastPlacement);
      if (shouldTransition || isTransitioning$1(element2, transition)) {
        set$7(element2, "position", position2.position);
        var rect2 = toBox(origin, element2);
        var intermediatePosition_1 = reposition(origin, __assign(__assign({}, decision), { rect: rect2 }));
        var intermediateCssOptions = mapToObject(properties, function(prop) {
          return intermediatePosition_1[prop];
        });
        if (hasChanges(position2, intermediateCssOptions)) {
          setOptions(element2, intermediateCssOptions);
          if (shouldTransition) {
            startTransitioning(element2, transition);
          }
          reflow2(element2);
        }
      } else {
        remove$1(element2, transition.classes);
      }
    };
    var elementSize = function(p2) {
      return {
        width: getOuter$1(p2),
        height: getOuter$2(p2)
      };
    };
    var layout = function(anchorBox, element2, bubbles, options) {
      remove$6(element2, "max-height");
      remove$6(element2, "max-width");
      var elementBox = elementSize(element2);
      return attempts(element2, options.preference, anchorBox, elementBox, bubbles, options.bounds);
    };
    var setClasses = function(element2, decision) {
      var classInfo = decision.classes;
      remove$1(element2, classInfo.off);
      add$1(element2, classInfo.on);
    };
    var setHeight = function(element2, decision, options) {
      var maxHeightFunction = options.maxHeightFunction;
      maxHeightFunction(element2, decision.maxHeight);
    };
    var setWidth = function(element2, decision, options) {
      var maxWidthFunction = options.maxWidthFunction;
      maxWidthFunction(element2, decision.maxWidth);
    };
    var position$2 = function(element2, decision, options) {
      var positionCss = reposition(options.origin, decision);
      options.transition.each(function(transition) {
        applyTransitionCss(element2, options.origin, positionCss, transition, decision, options.lastPlacement);
      });
      applyPositionCss(element2, positionCss);
    };
    var setPlacement = function(element2, decision) {
      setPlacement$1(element2, decision.placement);
    };
    var setMaxHeight = function(element2, maxHeight) {
      setMax$1(element2, Math.floor(maxHeight));
    };
    var anchored = constant$1(function(element2, available) {
      setMaxHeight(element2, available);
      setAll(element2, {
        "overflow-x": "hidden",
        "overflow-y": "auto"
      });
    });
    var expandable$1 = constant$1(function(element2, available) {
      setMaxHeight(element2, available);
    });
    var defaultOr = function(options, key, dephault) {
      return options[key] === void 0 ? dephault : options[key];
    };
    var simple = function(anchor2, element2, bubble, layouts3, lastPlacement, getBounds3, overrideOptions, transition) {
      var maxHeightFunction = defaultOr(overrideOptions, "maxHeightFunction", anchored());
      var maxWidthFunction = defaultOr(overrideOptions, "maxWidthFunction", noop3);
      var anchorBox = anchor2.anchorBox;
      var origin = anchor2.origin;
      var options = {
        bounds: viewport2(origin, getBounds3),
        origin,
        preference: layouts3,
        maxHeightFunction,
        maxWidthFunction,
        lastPlacement,
        transition
      };
      return go(anchorBox, element2, bubble, options);
    };
    var go = function(anchorBox, element2, bubble, options) {
      var decision = layout(anchorBox, element2, bubble, options);
      position$2(element2, decision, options);
      setPlacement(element2, decision);
      setClasses(element2, decision);
      setHeight(element2, decision, options);
      setWidth(element2, decision, options);
      return {
        layout: decision.layout,
        placement: decision.placement
      };
    };
    var allAlignments = [
      "valignCentre",
      "alignLeft",
      "alignRight",
      "alignCentre",
      "top",
      "bottom",
      "left",
      "right",
      "inset"
    ];
    var nu$5 = function(xOffset, yOffset, classes2, insetModifier) {
      if (insetModifier === void 0) {
        insetModifier = 1;
      }
      var insetXOffset = xOffset * insetModifier;
      var insetYOffset = yOffset * insetModifier;
      var getClasses2 = function(prop) {
        return get$e(classes2, prop).getOr([]);
      };
      var make2 = function(xDelta, yDelta, alignmentsOn) {
        var alignmentsOff = difference(allAlignments, alignmentsOn);
        return {
          offset: SugarPosition(xDelta, yDelta),
          classesOn: bind$3(alignmentsOn, getClasses2),
          classesOff: bind$3(alignmentsOff, getClasses2)
        };
      };
      return {
        southeast: function() {
          return make2(-xOffset, yOffset, [
            "top",
            "alignLeft"
          ]);
        },
        southwest: function() {
          return make2(xOffset, yOffset, [
            "top",
            "alignRight"
          ]);
        },
        south: function() {
          return make2(-xOffset / 2, yOffset, [
            "top",
            "alignCentre"
          ]);
        },
        northeast: function() {
          return make2(-xOffset, -yOffset, [
            "bottom",
            "alignLeft"
          ]);
        },
        northwest: function() {
          return make2(xOffset, -yOffset, [
            "bottom",
            "alignRight"
          ]);
        },
        north: function() {
          return make2(-xOffset / 2, -yOffset, [
            "bottom",
            "alignCentre"
          ]);
        },
        east: function() {
          return make2(xOffset, -yOffset / 2, [
            "valignCentre",
            "left"
          ]);
        },
        west: function() {
          return make2(-xOffset, -yOffset / 2, [
            "valignCentre",
            "right"
          ]);
        },
        insetNortheast: function() {
          return make2(insetXOffset, insetYOffset, [
            "top",
            "alignLeft",
            "inset"
          ]);
        },
        insetNorthwest: function() {
          return make2(-insetXOffset, insetYOffset, [
            "top",
            "alignRight",
            "inset"
          ]);
        },
        insetNorth: function() {
          return make2(-insetXOffset / 2, insetYOffset, [
            "top",
            "alignCentre",
            "inset"
          ]);
        },
        insetSoutheast: function() {
          return make2(insetXOffset, -insetYOffset, [
            "bottom",
            "alignLeft",
            "inset"
          ]);
        },
        insetSouthwest: function() {
          return make2(-insetXOffset, -insetYOffset, [
            "bottom",
            "alignRight",
            "inset"
          ]);
        },
        insetSouth: function() {
          return make2(-insetXOffset / 2, -insetYOffset, [
            "bottom",
            "alignCentre",
            "inset"
          ]);
        },
        insetEast: function() {
          return make2(-insetXOffset, -insetYOffset / 2, [
            "valignCentre",
            "right",
            "inset"
          ]);
        },
        insetWest: function() {
          return make2(insetXOffset, -insetYOffset / 2, [
            "valignCentre",
            "left",
            "inset"
          ]);
        }
      };
    };
    var fallback = function() {
      return nu$5(0, 0, {});
    };
    var nu$4 = identity$1;
    var onDirection = function(isLtr, isRtl) {
      return function(element2) {
        return getDirection(element2) === "rtl" ? isRtl : isLtr;
      };
    };
    var getDirection = function(element2) {
      return get$c(element2, "direction") === "rtl" ? "rtl" : "ltr";
    };
    var AttributeValue;
    (function(AttributeValue2) {
      AttributeValue2["TopToBottom"] = "toptobottom";
      AttributeValue2["BottomToTop"] = "bottomtotop";
    })(AttributeValue || (AttributeValue = {}));
    var Attribute = "data-alloy-vertical-dir";
    var isBottomToTopDir = function(el) {
      return closest$2(el, function(current) {
        return isElement$2(current) && get$d(current, "data-alloy-vertical-dir") === AttributeValue.BottomToTop;
      });
    };
    var schema$y = function() {
      return optionObjOf("layouts", [
        required$1("onLtr"),
        required$1("onRtl"),
        option("onBottomLtr"),
        option("onBottomRtl")
      ]);
    };
    var get$4 = function(elem, info, defaultLtr, defaultRtl, defaultBottomLtr, defaultBottomRtl, dirElement) {
      var isBottomToTop = dirElement.map(isBottomToTopDir).getOr(false);
      var customLtr = info.layouts.map(function(ls) {
        return ls.onLtr(elem);
      });
      var customRtl = info.layouts.map(function(ls) {
        return ls.onRtl(elem);
      });
      var ltr = isBottomToTop ? info.layouts.bind(function(ls) {
        return ls.onBottomLtr.map(function(f3) {
          return f3(elem);
        });
      }).or(customLtr).getOr(defaultBottomLtr) : customLtr.getOr(defaultLtr);
      var rtl = isBottomToTop ? info.layouts.bind(function(ls) {
        return ls.onBottomRtl.map(function(f3) {
          return f3(elem);
        });
      }).or(customRtl).getOr(defaultBottomRtl) : customRtl.getOr(defaultRtl);
      var f2 = onDirection(ltr, rtl);
      return f2(elem);
    };
    var placement$4 = function(component, anchorInfo, origin) {
      var hotspot = anchorInfo.hotspot;
      var anchorBox = toBox(origin, hotspot.element);
      var layouts3 = get$4(component.element, anchorInfo, belowOrAbove(), belowOrAboveRtl(), aboveOrBelow(), aboveOrBelowRtl(), Optional.some(anchorInfo.hotspot.element));
      return Optional.some(nu$4({
        anchorBox,
        bubble: anchorInfo.bubble.getOr(fallback()),
        overrides: anchorInfo.overrides,
        layouts: layouts3,
        placer: Optional.none()
      }));
    };
    var HotspotAnchor = [
      required$1("hotspot"),
      option("bubble"),
      defaulted("overrides", {}),
      schema$y(),
      output$1("placement", placement$4)
    ];
    var placement$3 = function(component, anchorInfo, origin) {
      var pos = translate$2(origin, anchorInfo.x, anchorInfo.y);
      var anchorBox = bounds(pos.left, pos.top, anchorInfo.width, anchorInfo.height);
      var layouts3 = get$4(component.element, anchorInfo, all$1(), allRtl$1(), all$1(), allRtl$1(), Optional.none());
      return Optional.some(nu$4({
        anchorBox,
        bubble: anchorInfo.bubble,
        overrides: anchorInfo.overrides,
        layouts: layouts3,
        placer: Optional.none()
      }));
    };
    var MakeshiftAnchor = [
      required$1("x"),
      required$1("y"),
      defaulted("height", 0),
      defaulted("width", 0),
      defaulted("bubble", fallback()),
      defaulted("overrides", {}),
      schema$y(),
      output$1("placement", placement$3)
    ];
    var adt$7 = Adt.generate([
      { screen: ["point"] },
      {
        absolute: [
          "point",
          "scrollLeft",
          "scrollTop"
        ]
      }
    ]);
    var toFixed = function(pos) {
      return pos.fold(identity$1, function(point2, scrollLeft, scrollTop) {
        return point2.translate(-scrollLeft, -scrollTop);
      });
    };
    var toAbsolute = function(pos) {
      return pos.fold(identity$1, identity$1);
    };
    var sum = function(points) {
      return foldl(points, function(b3, a2) {
        return b3.translate(a2.left, a2.top);
      }, SugarPosition(0, 0));
    };
    var sumAsFixed = function(positions2) {
      var points = map$2(positions2, toFixed);
      return sum(points);
    };
    var sumAsAbsolute = function(positions2) {
      var points = map$2(positions2, toAbsolute);
      return sum(points);
    };
    var screen = adt$7.screen;
    var absolute$1 = adt$7.absolute;
    var getOffset = function(component, origin, anchorInfo) {
      var win2 = defaultView(anchorInfo.root).dom;
      var hasSameOwner = function(frame) {
        var frameOwner = owner$4(frame);
        var compOwner = owner$4(component.element);
        return eq2(frameOwner, compOwner);
      };
      return Optional.from(win2.frameElement).map(SugarElement.fromDom).filter(hasSameOwner).map(absolute$3);
    };
    var getRootPoint = function(component, origin, anchorInfo) {
      var doc = owner$4(component.element);
      var outerScroll = get$9(doc);
      var offset3 = getOffset(component, origin, anchorInfo).getOr(outerScroll);
      return absolute$1(offset3, outerScroll.left, outerScroll.top);
    };
    var getBox = function(left3, top3, width2, height2) {
      var point2 = screen(SugarPosition(left3, top3));
      return Optional.some(pointed(point2, width2, height2));
    };
    var calcNewAnchor = function(optBox, rootPoint, anchorInfo, origin, elem) {
      return optBox.map(function(box2) {
        var points = [
          rootPoint,
          box2.point
        ];
        var topLeft = cata$1(origin, function() {
          return sumAsAbsolute(points);
        }, function() {
          return sumAsAbsolute(points);
        }, function() {
          return sumAsFixed(points);
        });
        var anchorBox = rect(topLeft.left, topLeft.top, box2.width, box2.height);
        var layoutsLtr = anchorInfo.showAbove ? aboveOrBelow() : belowOrAbove();
        var layoutsRtl = anchorInfo.showAbove ? aboveOrBelowRtl() : belowOrAboveRtl();
        var layouts3 = get$4(elem, anchorInfo, layoutsLtr, layoutsRtl, layoutsLtr, layoutsRtl, Optional.none());
        return nu$4({
          anchorBox,
          bubble: anchorInfo.bubble.getOr(fallback()),
          overrides: anchorInfo.overrides,
          layouts: layouts3,
          placer: Optional.none()
        });
      });
    };
    var placement$2 = function(component, anchorInfo, origin) {
      var rootPoint = getRootPoint(component, origin, anchorInfo);
      return anchorInfo.node.filter(inBody).bind(function(target) {
        var rect2 = target.dom.getBoundingClientRect();
        var nodeBox = getBox(rect2.left, rect2.top, rect2.width, rect2.height);
        var elem = anchorInfo.node.getOr(component.element);
        return calcNewAnchor(nodeBox, rootPoint, anchorInfo, origin, elem);
      });
    };
    var NodeAnchor = [
      required$1("node"),
      required$1("root"),
      option("bubble"),
      schema$y(),
      defaulted("overrides", {}),
      defaulted("showAbove", false),
      output$1("placement", placement$2)
    ];
    var zeroWidth = "\uFEFF";
    var nbsp = "\xA0";
    var create$6 = function(start4, soffset, finish, foffset) {
      return {
        start: start4,
        soffset,
        finish,
        foffset
      };
    };
    var SimRange = { create: create$6 };
    var adt$6 = Adt.generate([
      { before: ["element"] },
      {
        on: [
          "element",
          "offset"
        ]
      },
      { after: ["element"] }
    ]);
    var cata = function(subject, onBefore, onOn, onAfter) {
      return subject.fold(onBefore, onOn, onAfter);
    };
    var getStart$1 = function(situ) {
      return situ.fold(identity$1, identity$1, identity$1);
    };
    var before = adt$6.before;
    var on$1 = adt$6.on;
    var after$1 = adt$6.after;
    var Situ = {
      before,
      on: on$1,
      after: after$1,
      cata,
      getStart: getStart$1
    };
    var adt$5 = Adt.generate([
      { domRange: ["rng"] },
      {
        relative: [
          "startSitu",
          "finishSitu"
        ]
      },
      {
        exact: [
          "start",
          "soffset",
          "finish",
          "foffset"
        ]
      }
    ]);
    var exactFromRange = function(simRange) {
      return adt$5.exact(simRange.start, simRange.soffset, simRange.finish, simRange.foffset);
    };
    var getStart = function(selection) {
      return selection.match({
        domRange: function(rng) {
          return SugarElement.fromDom(rng.startContainer);
        },
        relative: function(startSitu, _finishSitu) {
          return Situ.getStart(startSitu);
        },
        exact: function(start4, _soffset, _finish, _foffset) {
          return start4;
        }
      });
    };
    var domRange = adt$5.domRange;
    var relative = adt$5.relative;
    var exact = adt$5.exact;
    var getWin = function(selection) {
      var start4 = getStart(selection);
      return defaultView(start4);
    };
    var range$1 = SimRange.create;
    var SimSelection = {
      domRange,
      relative,
      exact,
      exactFromRange,
      getWin,
      range: range$1
    };
    var setStart = function(rng, situ) {
      situ.fold(function(e2) {
        rng.setStartBefore(e2.dom);
      }, function(e2, o2) {
        rng.setStart(e2.dom, o2);
      }, function(e2) {
        rng.setStartAfter(e2.dom);
      });
    };
    var setFinish = function(rng, situ) {
      situ.fold(function(e2) {
        rng.setEndBefore(e2.dom);
      }, function(e2, o2) {
        rng.setEnd(e2.dom, o2);
      }, function(e2) {
        rng.setEndAfter(e2.dom);
      });
    };
    var relativeToNative = function(win2, startSitu, finishSitu) {
      var range2 = win2.document.createRange();
      setStart(range2, startSitu);
      setFinish(range2, finishSitu);
      return range2;
    };
    var exactToNative = function(win2, start4, soffset, finish, foffset) {
      var rng = win2.document.createRange();
      rng.setStart(start4.dom, soffset);
      rng.setEnd(finish.dom, foffset);
      return rng;
    };
    var toRect = function(rect2) {
      return {
        left: rect2.left,
        top: rect2.top,
        right: rect2.right,
        bottom: rect2.bottom,
        width: rect2.width,
        height: rect2.height
      };
    };
    var getFirstRect$1 = function(rng) {
      var rects = rng.getClientRects();
      var rect2 = rects.length > 0 ? rects[0] : rng.getBoundingClientRect();
      return rect2.width > 0 || rect2.height > 0 ? Optional.some(rect2).map(toRect) : Optional.none();
    };
    var getBounds$2 = function(rng) {
      var rect2 = rng.getBoundingClientRect();
      return rect2.width > 0 || rect2.height > 0 ? Optional.some(rect2).map(toRect) : Optional.none();
    };
    var adt$4 = Adt.generate([
      {
        ltr: [
          "start",
          "soffset",
          "finish",
          "foffset"
        ]
      },
      {
        rtl: [
          "start",
          "soffset",
          "finish",
          "foffset"
        ]
      }
    ]);
    var fromRange = function(win2, type2, range2) {
      return type2(SugarElement.fromDom(range2.startContainer), range2.startOffset, SugarElement.fromDom(range2.endContainer), range2.endOffset);
    };
    var getRanges = function(win2, selection) {
      return selection.match({
        domRange: function(rng) {
          return {
            ltr: constant$1(rng),
            rtl: Optional.none
          };
        },
        relative: function(startSitu, finishSitu) {
          return {
            ltr: cached(function() {
              return relativeToNative(win2, startSitu, finishSitu);
            }),
            rtl: cached(function() {
              return Optional.some(relativeToNative(win2, finishSitu, startSitu));
            })
          };
        },
        exact: function(start4, soffset, finish, foffset) {
          return {
            ltr: cached(function() {
              return exactToNative(win2, start4, soffset, finish, foffset);
            }),
            rtl: cached(function() {
              return Optional.some(exactToNative(win2, finish, foffset, start4, soffset));
            })
          };
        }
      });
    };
    var doDiagnose = function(win2, ranges) {
      var rng = ranges.ltr();
      if (rng.collapsed) {
        var reversed = ranges.rtl().filter(function(rev) {
          return rev.collapsed === false;
        });
        return reversed.map(function(rev) {
          return adt$4.rtl(SugarElement.fromDom(rev.endContainer), rev.endOffset, SugarElement.fromDom(rev.startContainer), rev.startOffset);
        }).getOrThunk(function() {
          return fromRange(win2, adt$4.ltr, rng);
        });
      } else {
        return fromRange(win2, adt$4.ltr, rng);
      }
    };
    var diagnose = function(win2, selection) {
      var ranges = getRanges(win2, selection);
      return doDiagnose(win2, ranges);
    };
    var asLtrRange = function(win2, selection) {
      var diagnosis = diagnose(win2, selection);
      return diagnosis.match({
        ltr: function(start4, soffset, finish, foffset) {
          var rng = win2.document.createRange();
          rng.setStart(start4.dom, soffset);
          rng.setEnd(finish.dom, foffset);
          return rng;
        },
        rtl: function(start4, soffset, finish, foffset) {
          var rng = win2.document.createRange();
          rng.setStart(finish.dom, foffset);
          rng.setEnd(start4.dom, soffset);
          return rng;
        }
      });
    };
    adt$4.ltr;
    adt$4.rtl;
    var NodeValue = function(is2, name2) {
      var get2 = function(element2) {
        if (!is2(element2)) {
          throw new Error("Can only get " + name2 + " value of a " + name2 + " node");
        }
        return getOption2(element2).getOr("");
      };
      var getOption2 = function(element2) {
        return is2(element2) ? Optional.from(element2.dom.nodeValue) : Optional.none();
      };
      var set3 = function(element2, value2) {
        if (!is2(element2)) {
          throw new Error("Can only set raw " + name2 + " value of a " + name2 + " node");
        }
        element2.dom.nodeValue = value2;
      };
      return {
        get: get2,
        getOption: getOption2,
        set: set3
      };
    };
    var api = NodeValue(isText$1, "text");
    var get$3 = function(element2) {
      return api.get(element2);
    };
    var getOption = function(element2) {
      return api.getOption(element2);
    };
    var getEnd = function(element2) {
      return name$2(element2) === "img" ? 1 : getOption(element2).fold(function() {
        return children(element2).length;
      }, function(v2) {
        return v2.length;
      });
    };
    var isTextNodeWithCursorPosition = function(el) {
      return getOption(el).filter(function(text2) {
        return text2.trim().length !== 0 || text2.indexOf(nbsp) > -1;
      }).isSome();
    };
    var elementsWithCursorPosition = [
      "img",
      "br"
    ];
    var isCursorPosition = function(elem) {
      var hasCursorPosition = isTextNodeWithCursorPosition(elem);
      return hasCursorPosition || contains$2(elementsWithCursorPosition, name$2(elem));
    };
    var last$1 = function(element2) {
      return descendantRtl(element2, isCursorPosition);
    };
    var descendantRtl = function(scope, predicate) {
      var descend = function(element2) {
        var children$1 = children(element2);
        for (var i2 = children$1.length - 1; i2 >= 0; i2--) {
          var child2 = children$1[i2];
          if (predicate(child2)) {
            return Optional.some(child2);
          }
          var res = descend(child2);
          if (res.isSome()) {
            return res;
          }
        }
        return Optional.none();
      };
      return descend(scope);
    };
    var descendants = function(scope, selector) {
      return all$3(selector, scope);
    };
    var makeRange = function(start4, soffset, finish, foffset) {
      var doc = owner$4(start4);
      var rng = doc.dom.createRange();
      rng.setStart(start4.dom, soffset);
      rng.setEnd(finish.dom, foffset);
      return rng;
    };
    var after = function(start4, soffset, finish, foffset) {
      var r3 = makeRange(start4, soffset, finish, foffset);
      var same = eq2(start4, finish) && soffset === foffset;
      return r3.collapsed && !same;
    };
    var getNativeSelection = function(win2) {
      return Optional.from(win2.getSelection());
    };
    var readRange = function(selection) {
      if (selection.rangeCount > 0) {
        var firstRng = selection.getRangeAt(0);
        var lastRng = selection.getRangeAt(selection.rangeCount - 1);
        return Optional.some(SimRange.create(SugarElement.fromDom(firstRng.startContainer), firstRng.startOffset, SugarElement.fromDom(lastRng.endContainer), lastRng.endOffset));
      } else {
        return Optional.none();
      }
    };
    var doGetExact = function(selection) {
      if (selection.anchorNode === null || selection.focusNode === null) {
        return readRange(selection);
      } else {
        var anchor2 = SugarElement.fromDom(selection.anchorNode);
        var focus_1 = SugarElement.fromDom(selection.focusNode);
        return after(anchor2, selection.anchorOffset, focus_1, selection.focusOffset) ? Optional.some(SimRange.create(anchor2, selection.anchorOffset, focus_1, selection.focusOffset)) : readRange(selection);
      }
    };
    var getExact = function(win2) {
      return getNativeSelection(win2).filter(function(sel) {
        return sel.rangeCount > 0;
      }).bind(doGetExact);
    };
    var getFirstRect = function(win2, selection) {
      var rng = asLtrRange(win2, selection);
      return getFirstRect$1(rng);
    };
    var getBounds$1 = function(win2, selection) {
      var rng = asLtrRange(win2, selection);
      return getBounds$2(rng);
    };
    var point$1 = function(element2, offset3) {
      return {
        element: element2,
        offset: offset3
      };
    };
    var descendOnce$1 = function(element2, offset3) {
      var children$1 = children(element2);
      if (children$1.length === 0) {
        return point$1(element2, offset3);
      } else if (offset3 < children$1.length) {
        return point$1(children$1[offset3], 0);
      } else {
        var last2 = children$1[children$1.length - 1];
        var len = isText$1(last2) ? get$3(last2).length : children(last2).length;
        return point$1(last2, len);
      }
    };
    var descendOnce = function(element2, offset3) {
      return isText$1(element2) ? point$1(element2, offset3) : descendOnce$1(element2, offset3);
    };
    var getAnchorSelection = function(win2, anchorInfo) {
      var getSelection = anchorInfo.getSelection.getOrThunk(function() {
        return function() {
          return getExact(win2);
        };
      });
      return getSelection().map(function(sel) {
        var modStart = descendOnce(sel.start, sel.soffset);
        var modFinish = descendOnce(sel.finish, sel.foffset);
        return SimSelection.range(modStart.element, modStart.offset, modFinish.element, modFinish.offset);
      });
    };
    var placement$1 = function(component, anchorInfo, origin) {
      var win2 = defaultView(anchorInfo.root).dom;
      var rootPoint = getRootPoint(component, origin, anchorInfo);
      var selectionBox = getAnchorSelection(win2, anchorInfo).bind(function(sel) {
        var optRect = getBounds$1(win2, SimSelection.exactFromRange(sel)).orThunk(function() {
          var x2 = SugarElement.fromText(zeroWidth);
          before$2(sel.start, x2);
          var rect2 = getFirstRect(win2, SimSelection.exact(x2, 0, x2, 1));
          remove$5(x2);
          return rect2;
        });
        return optRect.bind(function(rawRect) {
          return getBox(rawRect.left, rawRect.top, rawRect.width, rawRect.height);
        });
      });
      var targetElement = getAnchorSelection(win2, anchorInfo).bind(function(sel) {
        return isElement$2(sel.start) ? Optional.some(sel.start) : parentNode(sel.start);
      });
      var elem = targetElement.getOr(component.element);
      return calcNewAnchor(selectionBox, rootPoint, anchorInfo, origin, elem);
    };
    var SelectionAnchor = [
      option("getSelection"),
      required$1("root"),
      option("bubble"),
      schema$y(),
      defaulted("overrides", {}),
      defaulted("showAbove", false),
      output$1("placement", placement$1)
    ];
    var labelPrefix$1 = "link-layout";
    var eastX = function(anchor2) {
      return anchor2.x + anchor2.width;
    };
    var westX = function(anchor2, element2) {
      return anchor2.x - element2.width;
    };
    var northY$1 = function(anchor2, element2) {
      return anchor2.y - element2.height + anchor2.height;
    };
    var southY$1 = function(anchor2) {
      return anchor2.y;
    };
    var southeast$1 = function(anchor2, element2, bubbles) {
      return nu$6(eastX(anchor2), southY$1(anchor2), bubbles.southeast(), southeast$3(), "southeast", boundsRestriction(anchor2, {
        left: 0,
        top: 2
      }), labelPrefix$1);
    };
    var southwest$1 = function(anchor2, element2, bubbles) {
      return nu$6(westX(anchor2, element2), southY$1(anchor2), bubbles.southwest(), southwest$3(), "southwest", boundsRestriction(anchor2, {
        right: 1,
        top: 2
      }), labelPrefix$1);
    };
    var northeast$1 = function(anchor2, element2, bubbles) {
      return nu$6(eastX(anchor2), northY$1(anchor2, element2), bubbles.northeast(), northeast$3(), "northeast", boundsRestriction(anchor2, {
        left: 0,
        bottom: 3
      }), labelPrefix$1);
    };
    var northwest$1 = function(anchor2, element2, bubbles) {
      return nu$6(westX(anchor2, element2), northY$1(anchor2, element2), bubbles.northwest(), northwest$3(), "northwest", boundsRestriction(anchor2, {
        right: 1,
        bottom: 3
      }), labelPrefix$1);
    };
    var all = function() {
      return [
        southeast$1,
        southwest$1,
        northeast$1,
        northwest$1
      ];
    };
    var allRtl = function() {
      return [
        southwest$1,
        southeast$1,
        northwest$1,
        northeast$1
      ];
    };
    var placement = function(component, submenuInfo, origin) {
      var anchorBox = toBox(origin, submenuInfo.item.element);
      var layouts3 = get$4(component.element, submenuInfo, all(), allRtl(), all(), allRtl(), Optional.none());
      return Optional.some(nu$4({
        anchorBox,
        bubble: fallback(),
        overrides: submenuInfo.overrides,
        layouts: layouts3,
        placer: Optional.none()
      }));
    };
    var SubmenuAnchor = [
      required$1("item"),
      schema$y(),
      defaulted("overrides", {}),
      output$1("placement", placement)
    ];
    var AnchorSchema = choose$1("type", {
      selection: SelectionAnchor,
      node: NodeAnchor,
      hotspot: HotspotAnchor,
      submenu: SubmenuAnchor,
      makeshift: MakeshiftAnchor
    });
    var TransitionSchema = [
      requiredArrayOf("classes", string),
      defaultedStringEnum("mode", "all", [
        "all",
        "layout",
        "placement"
      ])
    ];
    var PositionSchema = [
      defaulted("useFixed", never),
      option("getBounds")
    ];
    var PlacementSchema = [
      requiredOf("anchor", AnchorSchema),
      optionObjOf("transition", TransitionSchema)
    ];
    var getFixedOrigin = function() {
      var html = document.documentElement;
      return fixed$1(0, 0, html.clientWidth, html.clientHeight);
    };
    var getRelativeOrigin = function(component) {
      var position2 = absolute$3(component.element);
      var bounds2 = component.element.dom.getBoundingClientRect();
      return relative$1(position2.left, position2.top, bounds2.width, bounds2.height);
    };
    var place = function(component, origin, anchoring, getBounds3, placee, lastPlace, transition) {
      var anchor2 = box(anchoring.anchorBox, origin);
      return simple(anchor2, placee.element, anchoring.bubble, anchoring.layouts, lastPlace, getBounds3, anchoring.overrides, transition);
    };
    var position$1 = function(component, posConfig, posState, placee, placementSpec) {
      positionWithin(component, posConfig, posState, placee, placementSpec, Optional.none());
    };
    var positionWithin = function(component, posConfig, posState, placee, placementSpec, boxElement) {
      var boundsBox = boxElement.map(box$1);
      return positionWithinBounds(component, posConfig, posState, placee, placementSpec, boundsBox);
    };
    var positionWithinBounds = function(component, posConfig, posState, placee, placementSpec, bounds2) {
      var placeeDetail = asRawOrDie$1("placement.info", objOf(PlacementSchema), placementSpec);
      var anchorage = placeeDetail.anchor;
      var element2 = placee.element;
      var placeeState = posState.get(placee.uid);
      preserve$1(function() {
        set$7(element2, "position", "fixed");
        var oldVisibility = getRaw(element2, "visibility");
        set$7(element2, "visibility", "hidden");
        var origin = posConfig.useFixed() ? getFixedOrigin() : getRelativeOrigin(component);
        var placer = anchorage.placement;
        var getBounds3 = bounds2.map(constant$1).or(posConfig.getBounds);
        placer(component, anchorage, origin).each(function(anchoring) {
          var doPlace = anchoring.placer.getOr(place);
          var newState = doPlace(component, origin, anchoring, getBounds3, placee, placeeState, placeeDetail.transition);
          posState.set(placee.uid, newState);
        });
        oldVisibility.fold(function() {
          remove$6(element2, "visibility");
        }, function(vis) {
          set$7(element2, "visibility", vis);
        });
        if (getRaw(element2, "left").isNone() && getRaw(element2, "top").isNone() && getRaw(element2, "right").isNone() && getRaw(element2, "bottom").isNone() && is$1(getRaw(element2, "position"), "fixed")) {
          remove$6(element2, "position");
        }
      }, element2);
    };
    var getMode = function(component, pConfig, _pState) {
      return pConfig.useFixed() ? "fixed" : "absolute";
    };
    var reset$1 = function(component, pConfig, posState, placee) {
      var element2 = placee.element;
      each$1([
        "position",
        "left",
        "right",
        "top",
        "bottom"
      ], function(prop) {
        return remove$6(element2, prop);
      });
      reset$2(element2);
      posState.clear(placee.uid);
    };
    var PositionApis = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      position: position$1,
      positionWithin,
      positionWithinBounds,
      getMode,
      reset: reset$1
    });
    var init$g = function() {
      var state = {};
      var set3 = function(id2, data) {
        state[id2] = data;
      };
      var get2 = function(id2) {
        return get$e(state, id2);
      };
      var clear2 = function(id2) {
        if (isNonNullable(id2)) {
          delete state[id2];
        } else {
          state = {};
        }
      };
      return nu$8({
        readState: function() {
          return state;
        },
        clear: clear2,
        set: set3,
        get: get2
      });
    };
    var PositioningState = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      init: init$g
    });
    var Positioning = create$7({
      fields: PositionSchema,
      name: "positioning",
      active: ActivePosition,
      apis: PositionApis,
      state: PositioningState
    });
    var fireDetaching = function(component) {
      emit(component, detachedFromDom());
      var children2 = component.components();
      each$1(children2, fireDetaching);
    };
    var fireAttaching = function(component) {
      var children2 = component.components();
      each$1(children2, fireAttaching);
      emit(component, attachedToDom());
    };
    var attach$1 = function(parent2, child2) {
      append$2(parent2.element, child2.element);
    };
    var detachChildren$1 = function(component) {
      each$1(component.components(), function(childComp) {
        return remove$5(childComp.element);
      });
      empty(component.element);
      component.syncComponents();
    };
    var replaceChildren = function(component, newChildren) {
      var subs2 = component.components();
      detachChildren$1(component);
      var deleted = difference(subs2, newChildren);
      each$1(deleted, function(comp) {
        fireDetaching(comp);
        component.getSystem().removeFromWorld(comp);
      });
      each$1(newChildren, function(childComp) {
        if (!childComp.getSystem().isConnected()) {
          component.getSystem().addToWorld(childComp);
          attach$1(component, childComp);
          if (inBody(component.element)) {
            fireAttaching(childComp);
          }
        } else {
          attach$1(component, childComp);
        }
        component.syncComponents();
      });
    };
    var attach = function(parent2, child2) {
      attachWith(parent2, child2, append$2);
    };
    var attachWith = function(parent2, child2, insertion) {
      parent2.getSystem().addToWorld(child2);
      insertion(parent2.element, child2.element);
      if (inBody(parent2.element)) {
        fireAttaching(child2);
      }
      parent2.syncComponents();
    };
    var doDetach = function(component) {
      fireDetaching(component);
      remove$5(component.element);
      component.getSystem().removeFromWorld(component);
    };
    var detach = function(component) {
      var parent$1 = parent(component.element).bind(function(p2) {
        return component.getSystem().getByDom(p2).toOptional();
      });
      doDetach(component);
      parent$1.each(function(p2) {
        p2.syncComponents();
      });
    };
    var detachChildren = function(component) {
      var subs2 = component.components();
      each$1(subs2, doDetach);
      empty(component.element);
      component.syncComponents();
    };
    var attachSystem = function(element2, guiSystem) {
      attachSystemWith(element2, guiSystem, append$2);
    };
    var attachSystemAfter = function(element2, guiSystem) {
      attachSystemWith(element2, guiSystem, after$2);
    };
    var attachSystemWith = function(element2, guiSystem, inserter) {
      inserter(element2, guiSystem.element);
      var children$1 = children(guiSystem.element);
      each$1(children$1, function(child2) {
        guiSystem.getByDom(child2).each(fireAttaching);
      });
    };
    var detachSystem = function(guiSystem) {
      var children$1 = children(guiSystem.element);
      each$1(children$1, function(child2) {
        guiSystem.getByDom(child2).each(fireDetaching);
      });
      remove$5(guiSystem.element);
    };
    var rebuild = function(sandbox, sConfig, sState, data) {
      sState.get().each(function(_data) {
        detachChildren(sandbox);
      });
      var point2 = sConfig.getAttachPoint(sandbox);
      attach(point2, sandbox);
      var built = sandbox.getSystem().build(data);
      attach(sandbox, built);
      sState.set(built);
      return built;
    };
    var open$1 = function(sandbox, sConfig, sState, data) {
      var newState = rebuild(sandbox, sConfig, sState, data);
      sConfig.onOpen(sandbox, newState);
      return newState;
    };
    var setContent = function(sandbox, sConfig, sState, data) {
      return sState.get().map(function() {
        return rebuild(sandbox, sConfig, sState, data);
      });
    };
    var openWhileCloaked = function(sandbox, sConfig, sState, data, transaction) {
      cloak(sandbox, sConfig);
      open$1(sandbox, sConfig, sState, data);
      transaction();
      decloak(sandbox, sConfig);
    };
    var close$1 = function(sandbox, sConfig, sState) {
      sState.get().each(function(data) {
        detachChildren(sandbox);
        detach(sandbox);
        sConfig.onClose(sandbox, data);
        sState.clear();
      });
    };
    var isOpen$1 = function(_sandbox, _sConfig, sState) {
      return sState.isOpen();
    };
    var isPartOf = function(sandbox, sConfig, sState, queryElem) {
      return isOpen$1(sandbox, sConfig, sState) && sState.get().exists(function(data) {
        return sConfig.isPartOf(sandbox, data, queryElem);
      });
    };
    var getState$2 = function(_sandbox, _sConfig, sState) {
      return sState.get();
    };
    var store = function(sandbox, cssKey, attr, newValue) {
      getRaw(sandbox.element, cssKey).fold(function() {
        remove$7(sandbox.element, attr);
      }, function(v2) {
        set$8(sandbox.element, attr, v2);
      });
      set$7(sandbox.element, cssKey, newValue);
    };
    var restore = function(sandbox, cssKey, attr) {
      getOpt(sandbox.element, attr).fold(function() {
        return remove$6(sandbox.element, cssKey);
      }, function(oldValue) {
        return set$7(sandbox.element, cssKey, oldValue);
      });
    };
    var cloak = function(sandbox, sConfig, _sState) {
      var sink = sConfig.getAttachPoint(sandbox);
      set$7(sandbox.element, "position", Positioning.getMode(sink));
      store(sandbox, "visibility", sConfig.cloakVisibilityAttr, "hidden");
    };
    var hasPosition = function(element2) {
      return exists([
        "top",
        "left",
        "right",
        "bottom"
      ], function(pos) {
        return getRaw(element2, pos).isSome();
      });
    };
    var decloak = function(sandbox, sConfig, _sState) {
      if (!hasPosition(sandbox.element)) {
        remove$6(sandbox.element, "position");
      }
      restore(sandbox, "visibility", sConfig.cloakVisibilityAttr);
    };
    var SandboxApis = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      cloak,
      decloak,
      open: open$1,
      openWhileCloaked,
      close: close$1,
      isOpen: isOpen$1,
      isPartOf,
      getState: getState$2,
      setContent
    });
    var events$g = function(sandboxConfig, sandboxState) {
      return derive$2([run$1(sandboxClose(), function(sandbox, _simulatedEvent) {
        close$1(sandbox, sandboxConfig, sandboxState);
      })]);
    };
    var ActiveSandbox = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      events: events$g
    });
    var SandboxSchema = [
      onHandler("onOpen"),
      onHandler("onClose"),
      required$1("isPartOf"),
      required$1("getAttachPoint"),
      defaulted("cloakVisibilityAttr", "data-precloak-visibility")
    ];
    var init$f = function() {
      var contents2 = value$1();
      var readState = constant$1("not-implemented");
      return nu$8({
        readState,
        isOpen: contents2.isSet,
        clear: contents2.clear,
        set: contents2.set,
        get: contents2.get
      });
    };
    var SandboxState = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      init: init$f
    });
    var Sandboxing = create$7({
      fields: SandboxSchema,
      name: "sandboxing",
      active: ActiveSandbox,
      apis: SandboxApis,
      state: SandboxState
    });
    var dismissPopups = constant$1("dismiss.popups");
    var repositionPopups = constant$1("reposition.popups");
    var mouseReleased = constant$1("mouse.released");
    var schema$x = objOfOnly([
      defaulted("isExtraPart", never),
      optionObjOf("fireEventInstead", [defaulted("event", dismissRequested())])
    ]);
    var receivingChannel$1 = function(rawSpec) {
      var _a2;
      var detail = asRawOrDie$1("Dismissal", schema$x, rawSpec);
      return _a2 = {}, _a2[dismissPopups()] = {
        schema: objOfOnly([required$1("target")]),
        onReceive: function(sandbox, data) {
          if (Sandboxing.isOpen(sandbox)) {
            var isPart = Sandboxing.isPartOf(sandbox, data.target) || detail.isExtraPart(sandbox, data.target);
            if (!isPart) {
              detail.fireEventInstead.fold(function() {
                return Sandboxing.close(sandbox);
              }, function(fe2) {
                return emit(sandbox, fe2.event);
              });
            }
          }
        }
      }, _a2;
    };
    var schema$w = objOfOnly([
      optionObjOf("fireEventInstead", [defaulted("event", repositionRequested())]),
      requiredFunction("doReposition")
    ]);
    var receivingChannel = function(rawSpec) {
      var _a2;
      var detail = asRawOrDie$1("Reposition", schema$w, rawSpec);
      return _a2 = {}, _a2[repositionPopups()] = {
        onReceive: function(sandbox) {
          if (Sandboxing.isOpen(sandbox)) {
            detail.fireEventInstead.fold(function() {
              return detail.doReposition(sandbox);
            }, function(fe2) {
              return emit(sandbox, fe2.event);
            });
          }
        }
      }, _a2;
    };
    var onLoad$5 = function(component, repConfig, repState) {
      repConfig.store.manager.onLoad(component, repConfig, repState);
    };
    var onUnload$2 = function(component, repConfig, repState) {
      repConfig.store.manager.onUnload(component, repConfig, repState);
    };
    var setValue$3 = function(component, repConfig, repState, data) {
      repConfig.store.manager.setValue(component, repConfig, repState, data);
    };
    var getValue$3 = function(component, repConfig, repState) {
      return repConfig.store.manager.getValue(component, repConfig, repState);
    };
    var getState$1 = function(component, repConfig, repState) {
      return repState;
    };
    var RepresentApis = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      onLoad: onLoad$5,
      onUnload: onUnload$2,
      setValue: setValue$3,
      getValue: getValue$3,
      getState: getState$1
    });
    var events$f = function(repConfig, repState) {
      var es = repConfig.resetOnDom ? [
        runOnAttached(function(comp, _se) {
          onLoad$5(comp, repConfig, repState);
        }),
        runOnDetached(function(comp, _se) {
          onUnload$2(comp, repConfig, repState);
        })
      ] : [loadEvent(repConfig, repState, onLoad$5)];
      return derive$2(es);
    };
    var ActiveRepresenting = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      events: events$f
    });
    var memory$1 = function() {
      var data = Cell(null);
      var readState = function() {
        return {
          mode: "memory",
          value: data.get()
        };
      };
      var isNotSet = function() {
        return data.get() === null;
      };
      var clear2 = function() {
        data.set(null);
      };
      return nu$8({
        set: data.set,
        get: data.get,
        isNotSet,
        clear: clear2,
        readState
      });
    };
    var manual = function() {
      var readState = noop3;
      return nu$8({ readState });
    };
    var dataset = function() {
      var dataByValue = Cell({});
      var dataByText = Cell({});
      var readState = function() {
        return {
          mode: "dataset",
          dataByValue: dataByValue.get(),
          dataByText: dataByText.get()
        };
      };
      var clear2 = function() {
        dataByValue.set({});
        dataByText.set({});
      };
      var lookup2 = function(itemString) {
        return get$e(dataByValue.get(), itemString).orThunk(function() {
          return get$e(dataByText.get(), itemString);
        });
      };
      var update = function(items) {
        var currentDataByValue = dataByValue.get();
        var currentDataByText = dataByText.get();
        var newDataByValue = {};
        var newDataByText = {};
        each$1(items, function(item2) {
          newDataByValue[item2.value] = item2;
          get$e(item2, "meta").each(function(meta) {
            get$e(meta, "text").each(function(text2) {
              newDataByText[text2] = item2;
            });
          });
        });
        dataByValue.set(__assign(__assign({}, currentDataByValue), newDataByValue));
        dataByText.set(__assign(__assign({}, currentDataByText), newDataByText));
      };
      return nu$8({
        readState,
        lookup: lookup2,
        update,
        clear: clear2
      });
    };
    var init$e = function(spec) {
      return spec.store.manager.state(spec);
    };
    var RepresentState = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      memory: memory$1,
      dataset,
      manual,
      init: init$e
    });
    var setValue$2 = function(component, repConfig, repState, data) {
      var store2 = repConfig.store;
      repState.update([data]);
      store2.setValue(component, data);
      repConfig.onSetValue(component, data);
    };
    var getValue$2 = function(component, repConfig, repState) {
      var store2 = repConfig.store;
      var key = store2.getDataKey(component);
      return repState.lookup(key).getOrThunk(function() {
        return store2.getFallbackEntry(key);
      });
    };
    var onLoad$4 = function(component, repConfig, repState) {
      var store2 = repConfig.store;
      store2.initialValue.each(function(data) {
        setValue$2(component, repConfig, repState, data);
      });
    };
    var onUnload$1 = function(component, repConfig, repState) {
      repState.clear();
    };
    var DatasetStore = [
      option("initialValue"),
      required$1("getFallbackEntry"),
      required$1("getDataKey"),
      required$1("setValue"),
      output$1("manager", {
        setValue: setValue$2,
        getValue: getValue$2,
        onLoad: onLoad$4,
        onUnload: onUnload$1,
        state: dataset
      })
    ];
    var getValue$1 = function(component, repConfig, _repState) {
      return repConfig.store.getValue(component);
    };
    var setValue$1 = function(component, repConfig, _repState, data) {
      repConfig.store.setValue(component, data);
      repConfig.onSetValue(component, data);
    };
    var onLoad$3 = function(component, repConfig, _repState) {
      repConfig.store.initialValue.each(function(data) {
        repConfig.store.setValue(component, data);
      });
    };
    var ManualStore = [
      required$1("getValue"),
      defaulted("setValue", noop3),
      option("initialValue"),
      output$1("manager", {
        setValue: setValue$1,
        getValue: getValue$1,
        onLoad: onLoad$3,
        onUnload: noop3,
        state: NoState.init
      })
    ];
    var setValue = function(component, repConfig, repState, data) {
      repState.set(data);
      repConfig.onSetValue(component, data);
    };
    var getValue = function(component, repConfig, repState) {
      return repState.get();
    };
    var onLoad$2 = function(component, repConfig, repState) {
      repConfig.store.initialValue.each(function(initVal) {
        if (repState.isNotSet()) {
          repState.set(initVal);
        }
      });
    };
    var onUnload = function(component, repConfig, repState) {
      repState.clear();
    };
    var MemoryStore = [
      option("initialValue"),
      output$1("manager", {
        setValue,
        getValue,
        onLoad: onLoad$2,
        onUnload,
        state: memory$1
      })
    ];
    var RepresentSchema = [
      defaultedOf("store", { mode: "memory" }, choose$1("mode", {
        memory: MemoryStore,
        manual: ManualStore,
        dataset: DatasetStore
      })),
      onHandler("onSetValue"),
      defaulted("resetOnDom", false)
    ];
    var Representing = create$7({
      fields: RepresentSchema,
      name: "representing",
      active: ActiveRepresenting,
      apis: RepresentApis,
      extra: {
        setValueFrom: function(component, source) {
          var value2 = Representing.getValue(source);
          Representing.setValue(component, value2);
        }
      },
      state: RepresentState
    });
    var field = function(name2, forbidden) {
      return defaultedObjOf(name2, {}, map$2(forbidden, function(f2) {
        return forbid(f2.name(), "Cannot configure " + f2.name() + " for " + name2);
      }).concat([customField("dump", identity$1)]));
    };
    var get$2 = function(data) {
      return data.dump;
    };
    var augment = function(data, original2) {
      return __assign(__assign({}, derive$1(original2)), data.dump);
    };
    var SketchBehaviours = {
      field,
      augment,
      get: get$2
    };
    var _placeholder = "placeholder";
    var adt$3 = Adt.generate([
      {
        single: [
          "required",
          "valueThunk"
        ]
      },
      {
        multiple: [
          "required",
          "valueThunks"
        ]
      }
    ]);
    var isSubstituted = function(spec) {
      return has$2(spec, "uiType");
    };
    var subPlaceholder = function(owner2, detail, compSpec, placeholders) {
      if (owner2.exists(function(o2) {
        return o2 !== compSpec.owner;
      })) {
        return adt$3.single(true, constant$1(compSpec));
      }
      return get$e(placeholders, compSpec.name).fold(function() {
        throw new Error("Unknown placeholder component: " + compSpec.name + "\nKnown: [" + keys(placeholders) + "]\nNamespace: " + owner2.getOr("none") + "\nSpec: " + JSON.stringify(compSpec, null, 2));
      }, function(newSpec) {
        return newSpec.replace();
      });
    };
    var scan = function(owner2, detail, compSpec, placeholders) {
      if (isSubstituted(compSpec) && compSpec.uiType === _placeholder) {
        return subPlaceholder(owner2, detail, compSpec, placeholders);
      } else {
        return adt$3.single(false, constant$1(compSpec));
      }
    };
    var substitute = function(owner2, detail, compSpec, placeholders) {
      var base2 = scan(owner2, detail, compSpec, placeholders);
      return base2.fold(function(req, valueThunk2) {
        var value2 = isSubstituted(compSpec) ? valueThunk2(detail, compSpec.config, compSpec.validated) : valueThunk2(detail);
        var childSpecs = get$e(value2, "components").getOr([]);
        var substituted = bind$3(childSpecs, function(c2) {
          return substitute(owner2, detail, c2, placeholders);
        });
        return [__assign(__assign({}, value2), { components: substituted })];
      }, function(req, valuesThunk) {
        if (isSubstituted(compSpec)) {
          var values2 = valuesThunk(detail, compSpec.config, compSpec.validated);
          var preprocessor = compSpec.validated.preprocess.getOr(identity$1);
          return preprocessor(values2);
        } else {
          return valuesThunk(detail);
        }
      });
    };
    var substituteAll = function(owner2, detail, components2, placeholders) {
      return bind$3(components2, function(c2) {
        return substitute(owner2, detail, c2, placeholders);
      });
    };
    var oneReplace = function(label, replacements) {
      var called = false;
      var used = function() {
        return called;
      };
      var replace = function() {
        if (called) {
          throw new Error("Trying to use the same placeholder more than once: " + label);
        }
        called = true;
        return replacements;
      };
      var required2 = function() {
        return replacements.fold(function(req, _2) {
          return req;
        }, function(req, _2) {
          return req;
        });
      };
      return {
        name: constant$1(label),
        required: required2,
        used,
        replace
      };
    };
    var substitutePlaces = function(owner2, detail, components2, placeholders) {
      var ps = map$12(placeholders, function(ph, name2) {
        return oneReplace(name2, ph);
      });
      var outcome = substituteAll(owner2, detail, components2, ps);
      each2(ps, function(p2) {
        if (p2.used() === false && p2.required()) {
          throw new Error("Placeholder: " + p2.name() + " was not found in components list\nNamespace: " + owner2.getOr("none") + "\nComponents: " + JSON.stringify(detail.components, null, 2));
        }
      });
      return outcome;
    };
    var single$2 = adt$3.single;
    var multiple = adt$3.multiple;
    var placeholder = constant$1(_placeholder);
    var adt$2 = Adt.generate([
      { required: ["data"] },
      { external: ["data"] },
      { optional: ["data"] },
      { group: ["data"] }
    ]);
    var fFactory = defaulted("factory", { sketch: identity$1 });
    var fSchema = defaulted("schema", []);
    var fName = required$1("name");
    var fPname = field$1("pname", "pname", defaultedThunk(function(typeSpec) {
      return "<alloy." + generate$6(typeSpec.name) + ">";
    }), anyValue());
    var fGroupSchema = customField("schema", function() {
      return [option("preprocess")];
    });
    var fDefaults = defaulted("defaults", constant$1({}));
    var fOverrides = defaulted("overrides", constant$1({}));
    var requiredSpec = objOf([
      fFactory,
      fSchema,
      fName,
      fPname,
      fDefaults,
      fOverrides
    ]);
    var externalSpec = objOf([
      fFactory,
      fSchema,
      fName,
      fDefaults,
      fOverrides
    ]);
    var optionalSpec = objOf([
      fFactory,
      fSchema,
      fName,
      fPname,
      fDefaults,
      fOverrides
    ]);
    var groupSpec = objOf([
      fFactory,
      fGroupSchema,
      fName,
      required$1("unit"),
      fPname,
      fDefaults,
      fOverrides
    ]);
    var asNamedPart = function(part2) {
      return part2.fold(Optional.some, Optional.none, Optional.some, Optional.some);
    };
    var name$1 = function(part2) {
      var get2 = function(data) {
        return data.name;
      };
      return part2.fold(get2, get2, get2, get2);
    };
    var asCommon = function(part2) {
      return part2.fold(identity$1, identity$1, identity$1, identity$1);
    };
    var convert = function(adtConstructor, partSchema) {
      return function(spec) {
        var data = asRawOrDie$1("Converting part type", partSchema, spec);
        return adtConstructor(data);
      };
    };
    var required = convert(adt$2.required, requiredSpec);
    var external$1 = convert(adt$2.external, externalSpec);
    var optional = convert(adt$2.optional, optionalSpec);
    var group = convert(adt$2.group, groupSpec);
    var original = constant$1("entirety");
    var PartType = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      required,
      external: external$1,
      optional,
      group,
      asNamedPart,
      name: name$1,
      asCommon,
      original
    });
    var combine = function(detail, data, partSpec, partValidated) {
      return deepMerge(data.defaults(detail, partSpec, partValidated), partSpec, { uid: detail.partUids[data.name] }, data.overrides(detail, partSpec, partValidated));
    };
    var subs = function(owner2, detail, parts2) {
      var internals = {};
      var externals = {};
      each$1(parts2, function(part2) {
        part2.fold(function(data) {
          internals[data.pname] = single$2(true, function(detail2, partSpec, partValidated) {
            return data.factory.sketch(combine(detail2, data, partSpec, partValidated));
          });
        }, function(data) {
          var partSpec = detail.parts[data.name];
          externals[data.name] = constant$1(data.factory.sketch(combine(detail, data, partSpec[original()]), partSpec));
        }, function(data) {
          internals[data.pname] = single$2(false, function(detail2, partSpec, partValidated) {
            return data.factory.sketch(combine(detail2, data, partSpec, partValidated));
          });
        }, function(data) {
          internals[data.pname] = multiple(true, function(detail2, _partSpec, _partValidated) {
            var units2 = detail2[data.name];
            return map$2(units2, function(u2) {
              return data.factory.sketch(deepMerge(data.defaults(detail2, u2, _partValidated), u2, data.overrides(detail2, u2)));
            });
          });
        });
      });
      return {
        internals: constant$1(internals),
        externals: constant$1(externals)
      };
    };
    var generate$3 = function(owner2, parts2) {
      var r3 = {};
      each$1(parts2, function(part2) {
        asNamedPart(part2).each(function(np) {
          var g2 = doGenerateOne(owner2, np.pname);
          r3[np.name] = function(config2) {
            var validated = asRawOrDie$1("Part: " + np.name + " in " + owner2, objOf(np.schema), config2);
            return __assign(__assign({}, g2), {
              config: config2,
              validated
            });
          };
        });
      });
      return r3;
    };
    var doGenerateOne = function(owner2, pname) {
      return {
        uiType: placeholder(),
        owner: owner2,
        name: pname
      };
    };
    var generateOne$1 = function(owner2, pname, config2) {
      return {
        uiType: placeholder(),
        owner: owner2,
        name: pname,
        config: config2,
        validated: {}
      };
    };
    var schemas = function(parts2) {
      return bind$3(parts2, function(part2) {
        return part2.fold(Optional.none, Optional.some, Optional.none, Optional.none).map(function(data) {
          return requiredObjOf(data.name, data.schema.concat([snapshot(original())]));
        }).toArray();
      });
    };
    var names2 = function(parts2) {
      return map$2(parts2, name$1);
    };
    var substitutes = function(owner2, detail, parts2) {
      return subs(owner2, detail, parts2);
    };
    var components$1 = function(owner2, detail, internals) {
      return substitutePlaces(Optional.some(owner2), detail, detail.components, internals);
    };
    var getPart = function(component, detail, partKey) {
      var uid2 = detail.partUids[partKey];
      return component.getSystem().getByUid(uid2).toOptional();
    };
    var getPartOrDie = function(component, detail, partKey) {
      return getPart(component, detail, partKey).getOrDie("Could not find part: " + partKey);
    };
    var getParts = function(component, detail, partKeys) {
      var r3 = {};
      var uids2 = detail.partUids;
      var system = component.getSystem();
      each$1(partKeys, function(pk) {
        r3[pk] = constant$1(system.getByUid(uids2[pk]));
      });
      return r3;
    };
    var getAllParts = function(component, detail) {
      var system = component.getSystem();
      return map$12(detail.partUids, function(pUid, _k) {
        return constant$1(system.getByUid(pUid));
      });
    };
    var getAllPartNames = function(detail) {
      return keys(detail.partUids);
    };
    var getPartsOrDie = function(component, detail, partKeys) {
      var r3 = {};
      var uids2 = detail.partUids;
      var system = component.getSystem();
      each$1(partKeys, function(pk) {
        r3[pk] = constant$1(system.getByUid(uids2[pk]).getOrDie());
      });
      return r3;
    };
    var defaultUids = function(baseUid, partTypes) {
      var partNames = names2(partTypes);
      return wrapAll(map$2(partNames, function(pn2) {
        return {
          key: pn2,
          value: baseUid + "-" + pn2
        };
      }));
    };
    var defaultUidsSchema = function(partTypes) {
      return field$1("partUids", "partUids", mergeWithThunk(function(spec) {
        return defaultUids(spec.uid, partTypes);
      }), anyValue());
    };
    var AlloyParts = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      generate: generate$3,
      generateOne: generateOne$1,
      schemas,
      names: names2,
      substitutes,
      components: components$1,
      defaultUids,
      defaultUidsSchema,
      getAllParts,
      getAllPartNames,
      getPart,
      getPartOrDie,
      getParts,
      getPartsOrDie
    });
    var base = function(partSchemas, partUidsSchemas) {
      var ps = partSchemas.length > 0 ? [requiredObjOf("parts", partSchemas)] : [];
      return ps.concat([
        required$1("uid"),
        defaulted("dom", {}),
        defaulted("components", []),
        snapshot("originalSpec"),
        defaulted("debug.sketcher", {})
      ]).concat(partUidsSchemas);
    };
    var asRawOrDie = function(label, schema2, spec, partSchemas, partUidsSchemas) {
      var baseS = base(partSchemas, partUidsSchemas);
      return asRawOrDie$1(label + " [SpecSchema]", objOfOnly(baseS.concat(schema2)), spec);
    };
    var single$1 = function(owner2, schema2, factory2, spec) {
      var specWithUid = supplyUid(spec);
      var detail = asRawOrDie(owner2, schema2, specWithUid, [], []);
      return factory2(detail, specWithUid);
    };
    var composite$1 = function(owner2, schema2, partTypes, factory2, spec) {
      var specWithUid = supplyUid(spec);
      var partSchemas = schemas(partTypes);
      var partUidsSchema = defaultUidsSchema(partTypes);
      var detail = asRawOrDie(owner2, schema2, specWithUid, partSchemas, [partUidsSchema]);
      var subs2 = substitutes(owner2, detail, partTypes);
      var components2 = components$1(owner2, detail, subs2.internals());
      return factory2(detail, components2, specWithUid, subs2.externals());
    };
    var hasUid = function(spec) {
      return has$2(spec, "uid");
    };
    var supplyUid = function(spec) {
      return hasUid(spec) ? spec : __assign(__assign({}, spec), { uid: generate$5("uid") });
    };
    var isSketchSpec = function(spec) {
      return spec.uid !== void 0;
    };
    var singleSchema = objOfOnly([
      required$1("name"),
      required$1("factory"),
      required$1("configFields"),
      defaulted("apis", {}),
      defaulted("extraApis", {})
    ]);
    var compositeSchema = objOfOnly([
      required$1("name"),
      required$1("factory"),
      required$1("configFields"),
      required$1("partFields"),
      defaulted("apis", {}),
      defaulted("extraApis", {})
    ]);
    var single = function(rawConfig) {
      var config2 = asRawOrDie$1("Sketcher for " + rawConfig.name, singleSchema, rawConfig);
      var sketch2 = function(spec) {
        return single$1(config2.name, config2.configFields, config2.factory, spec);
      };
      var apis = map$12(config2.apis, makeApi);
      var extraApis = map$12(config2.extraApis, function(f2, k2) {
        return markAsExtraApi(f2, k2);
      });
      return __assign(__assign({
        name: config2.name,
        configFields: config2.configFields,
        sketch: sketch2
      }, apis), extraApis);
    };
    var composite = function(rawConfig) {
      var config2 = asRawOrDie$1("Sketcher for " + rawConfig.name, compositeSchema, rawConfig);
      var sketch2 = function(spec) {
        return composite$1(config2.name, config2.configFields, config2.partFields, config2.factory, spec);
      };
      var parts2 = generate$3(config2.name, config2.partFields);
      var apis = map$12(config2.apis, makeApi);
      var extraApis = map$12(config2.extraApis, function(f2, k2) {
        return markAsExtraApi(f2, k2);
      });
      return __assign(__assign({
        name: config2.name,
        partFields: config2.partFields,
        configFields: config2.configFields,
        sketch: sketch2,
        parts: parts2
      }, apis), extraApis);
    };
    var inside = function(target) {
      return name$2(target) === "input" && get$d(target, "type") !== "radio" || name$2(target) === "textarea";
    };
    var getCurrent = function(component, composeConfig, _composeState) {
      return composeConfig.find(component);
    };
    var ComposeApis = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      getCurrent
    });
    var ComposeSchema = [required$1("find")];
    var Composing = create$7({
      fields: ComposeSchema,
      name: "composing",
      apis: ComposeApis
    });
    var nativeDisabled = [
      "input",
      "button",
      "textarea",
      "select"
    ];
    var onLoad$1 = function(component, disableConfig, disableState) {
      var f2 = disableConfig.disabled() ? disable$1 : enable$1;
      f2(component, disableConfig);
    };
    var hasNative = function(component, config2) {
      return config2.useNative === true && contains$2(nativeDisabled, name$2(component.element));
    };
    var nativeIsDisabled = function(component) {
      return has$1(component.element, "disabled");
    };
    var nativeDisable = function(component) {
      set$8(component.element, "disabled", "disabled");
    };
    var nativeEnable = function(component) {
      remove$7(component.element, "disabled");
    };
    var ariaIsDisabled = function(component) {
      return get$d(component.element, "aria-disabled") === "true";
    };
    var ariaDisable = function(component) {
      set$8(component.element, "aria-disabled", "true");
    };
    var ariaEnable = function(component) {
      set$8(component.element, "aria-disabled", "false");
    };
    var disable$1 = function(component, disableConfig, _disableState) {
      disableConfig.disableClass.each(function(disableClass) {
        add$2(component.element, disableClass);
      });
      var f2 = hasNative(component, disableConfig) ? nativeDisable : ariaDisable;
      f2(component);
      disableConfig.onDisabled(component);
    };
    var enable$1 = function(component, disableConfig, _disableState) {
      disableConfig.disableClass.each(function(disableClass) {
        remove$2(component.element, disableClass);
      });
      var f2 = hasNative(component, disableConfig) ? nativeEnable : ariaEnable;
      f2(component);
      disableConfig.onEnabled(component);
    };
    var isDisabled2 = function(component, disableConfig) {
      return hasNative(component, disableConfig) ? nativeIsDisabled(component) : ariaIsDisabled(component);
    };
    var set$3 = function(component, disableConfig, disableState, disabled) {
      var f2 = disabled ? disable$1 : enable$1;
      f2(component, disableConfig);
    };
    var DisableApis = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      enable: enable$1,
      disable: disable$1,
      isDisabled: isDisabled2,
      onLoad: onLoad$1,
      set: set$3
    });
    var exhibit$5 = function(base2, disableConfig) {
      return nu$7({ classes: disableConfig.disabled() ? disableConfig.disableClass.toArray() : [] });
    };
    var events$e = function(disableConfig, disableState) {
      return derive$2([
        abort(execute$5(), function(component, _simulatedEvent) {
          return isDisabled2(component, disableConfig);
        }),
        loadEvent(disableConfig, disableState, onLoad$1)
      ]);
    };
    var ActiveDisable = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      exhibit: exhibit$5,
      events: events$e
    });
    var DisableSchema = [
      defaultedFunction("disabled", never),
      defaulted("useNative", true),
      option("disableClass"),
      onHandler("onDisabled"),
      onHandler("onEnabled")
    ];
    var Disabling = create$7({
      fields: DisableSchema,
      name: "disabling",
      active: ActiveDisable,
      apis: DisableApis
    });
    var dehighlightAllExcept = function(component, hConfig, hState, skip2) {
      var highlighted = descendants(component.element, "." + hConfig.highlightClass);
      each$1(highlighted, function(h3) {
        if (!exists(skip2, function(skipComp) {
          return skipComp.element === h3;
        })) {
          remove$2(h3, hConfig.highlightClass);
          component.getSystem().getByDom(h3).each(function(target) {
            hConfig.onDehighlight(component, target);
            emit(target, dehighlight$1());
          });
        }
      });
    };
    var dehighlightAll = function(component, hConfig, hState) {
      return dehighlightAllExcept(component, hConfig, hState, []);
    };
    var dehighlight = function(component, hConfig, hState, target) {
      if (isHighlighted(component, hConfig, hState, target)) {
        remove$2(target.element, hConfig.highlightClass);
        hConfig.onDehighlight(component, target);
        emit(target, dehighlight$1());
      }
    };
    var highlight = function(component, hConfig, hState, target) {
      dehighlightAllExcept(component, hConfig, hState, [target]);
      if (!isHighlighted(component, hConfig, hState, target)) {
        add$2(target.element, hConfig.highlightClass);
        hConfig.onHighlight(component, target);
        emit(target, highlight$1());
      }
    };
    var highlightFirst = function(component, hConfig, hState) {
      getFirst(component, hConfig).each(function(firstComp) {
        highlight(component, hConfig, hState, firstComp);
      });
    };
    var highlightLast = function(component, hConfig, hState) {
      getLast(component, hConfig).each(function(lastComp) {
        highlight(component, hConfig, hState, lastComp);
      });
    };
    var highlightAt = function(component, hConfig, hState, index) {
      getByIndex(component, hConfig, hState, index).fold(function(err) {
        throw err;
      }, function(firstComp) {
        highlight(component, hConfig, hState, firstComp);
      });
    };
    var highlightBy = function(component, hConfig, hState, predicate) {
      var candidates = getCandidates(component, hConfig);
      var targetComp = find$5(candidates, predicate);
      targetComp.each(function(c2) {
        highlight(component, hConfig, hState, c2);
      });
    };
    var isHighlighted = function(component, hConfig, hState, queryTarget) {
      return has(queryTarget.element, hConfig.highlightClass);
    };
    var getHighlighted = function(component, hConfig, _hState) {
      return descendant(component.element, "." + hConfig.highlightClass).bind(function(e2) {
        return component.getSystem().getByDom(e2).toOptional();
      });
    };
    var getByIndex = function(component, hConfig, hState, index) {
      var items = descendants(component.element, "." + hConfig.itemClass);
      return Optional.from(items[index]).fold(function() {
        return Result.error(new Error("No element found with index " + index));
      }, component.getSystem().getByDom);
    };
    var getFirst = function(component, hConfig, _hState) {
      return descendant(component.element, "." + hConfig.itemClass).bind(function(e2) {
        return component.getSystem().getByDom(e2).toOptional();
      });
    };
    var getLast = function(component, hConfig, _hState) {
      var items = descendants(component.element, "." + hConfig.itemClass);
      var last2 = items.length > 0 ? Optional.some(items[items.length - 1]) : Optional.none();
      return last2.bind(function(c2) {
        return component.getSystem().getByDom(c2).toOptional();
      });
    };
    var getDelta$2 = function(component, hConfig, hState, delta) {
      var items = descendants(component.element, "." + hConfig.itemClass);
      var current = findIndex$1(items, function(item2) {
        return has(item2, hConfig.highlightClass);
      });
      return current.bind(function(selected) {
        var dest = cycleBy(selected, delta, 0, items.length - 1);
        return component.getSystem().getByDom(items[dest]).toOptional();
      });
    };
    var getPrevious = function(component, hConfig, hState) {
      return getDelta$2(component, hConfig, hState, -1);
    };
    var getNext = function(component, hConfig, hState) {
      return getDelta$2(component, hConfig, hState, 1);
    };
    var getCandidates = function(component, hConfig, _hState) {
      var items = descendants(component.element, "." + hConfig.itemClass);
      return cat(map$2(items, function(i2) {
        return component.getSystem().getByDom(i2).toOptional();
      }));
    };
    var HighlightApis = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      dehighlightAll,
      dehighlight,
      highlight,
      highlightFirst,
      highlightLast,
      highlightAt,
      highlightBy,
      isHighlighted,
      getHighlighted,
      getFirst,
      getLast,
      getPrevious,
      getNext,
      getCandidates
    });
    var HighlightSchema = [
      required$1("highlightClass"),
      required$1("itemClass"),
      onHandler("onHighlight"),
      onHandler("onDehighlight")
    ];
    var Highlighting = create$7({
      fields: HighlightSchema,
      name: "highlighting",
      apis: HighlightApis
    });
    var BACKSPACE = [8];
    var TAB = [9];
    var ENTER = [13];
    var ESCAPE = [27];
    var SPACE = [32];
    var LEFT = [37];
    var UP = [38];
    var RIGHT = [39];
    var DOWN = [40];
    var cyclePrev = function(values2, index, predicate) {
      var before2 = reverse(values2.slice(0, index));
      var after2 = reverse(values2.slice(index + 1));
      return find$5(before2.concat(after2), predicate);
    };
    var tryPrev = function(values2, index, predicate) {
      var before2 = reverse(values2.slice(0, index));
      return find$5(before2, predicate);
    };
    var cycleNext = function(values2, index, predicate) {
      var before2 = values2.slice(0, index);
      var after2 = values2.slice(index + 1);
      return find$5(after2.concat(before2), predicate);
    };
    var tryNext = function(values2, index, predicate) {
      var after2 = values2.slice(index + 1);
      return find$5(after2, predicate);
    };
    var inSet = function(keys2) {
      return function(event) {
        var raw = event.raw;
        return contains$2(keys2, raw.which);
      };
    };
    var and = function(preds) {
      return function(event) {
        return forall(preds, function(pred) {
          return pred(event);
        });
      };
    };
    var isShift = function(event) {
      var raw = event.raw;
      return raw.shiftKey === true;
    };
    var isControl = function(event) {
      var raw = event.raw;
      return raw.ctrlKey === true;
    };
    var isNotShift = not(isShift);
    var rule = function(matches, action) {
      return {
        matches,
        classification: action
      };
    };
    var choose = function(transitions, event) {
      var transition = find$5(transitions, function(t3) {
        return t3.matches(event);
      });
      return transition.map(function(t3) {
        return t3.classification;
      });
    };
    var reportFocusShifting = function(component, prevFocus, newFocus) {
      var noChange = prevFocus.exists(function(p2) {
        return newFocus.exists(function(n2) {
          return eq2(n2, p2);
        });
      });
      if (!noChange) {
        emitWith(component, focusShifted(), {
          prevFocus,
          newFocus
        });
      }
    };
    var dom$2 = function() {
      var get2 = function(component) {
        return search(component.element);
      };
      var set3 = function(component, focusee) {
        var prevFocus = get2(component);
        component.getSystem().triggerFocus(focusee, component.element);
        var newFocus = get2(component);
        reportFocusShifting(component, prevFocus, newFocus);
      };
      return {
        get: get2,
        set: set3
      };
    };
    var highlights = function() {
      var get2 = function(component) {
        return Highlighting.getHighlighted(component).map(function(item2) {
          return item2.element;
        });
      };
      var set3 = function(component, element2) {
        var prevFocus = get2(component);
        component.getSystem().getByDom(element2).fold(noop3, function(item2) {
          Highlighting.highlight(component, item2);
        });
        var newFocus = get2(component);
        reportFocusShifting(component, prevFocus, newFocus);
      };
      return {
        get: get2,
        set: set3
      };
    };
    var FocusInsideModes;
    (function(FocusInsideModes2) {
      FocusInsideModes2["OnFocusMode"] = "onFocus";
      FocusInsideModes2["OnEnterOrSpaceMode"] = "onEnterOrSpace";
      FocusInsideModes2["OnApiMode"] = "onApi";
    })(FocusInsideModes || (FocusInsideModes = {}));
    var typical = function(infoSchema, stateInit, getKeydownRules2, getKeyupRules2, optFocusIn) {
      var schema2 = function() {
        return infoSchema.concat([
          defaulted("focusManager", dom$2()),
          defaultedOf("focusInside", "onFocus", valueOf(function(val) {
            return contains$2([
              "onFocus",
              "onEnterOrSpace",
              "onApi"
            ], val) ? Result.value(val) : Result.error("Invalid value for focusInside");
          })),
          output$1("handler", me2),
          output$1("state", stateInit),
          output$1("sendFocusIn", optFocusIn)
        ]);
      };
      var processKey = function(component, simulatedEvent, getRules, keyingConfig, keyingState) {
        var rules = getRules(component, simulatedEvent, keyingConfig, keyingState);
        return choose(rules, simulatedEvent.event).bind(function(rule2) {
          return rule2(component, simulatedEvent, keyingConfig, keyingState);
        });
      };
      var toEvents2 = function(keyingConfig, keyingState) {
        var onFocusHandler = keyingConfig.focusInside !== FocusInsideModes.OnFocusMode ? Optional.none() : optFocusIn(keyingConfig).map(function(focusIn2) {
          return run$1(focus$4(), function(component, simulatedEvent) {
            focusIn2(component, keyingConfig, keyingState);
            simulatedEvent.stop();
          });
        });
        var tryGoInsideComponent = function(component, simulatedEvent) {
          var isEnterOrSpace = inSet(SPACE.concat(ENTER))(simulatedEvent.event);
          if (keyingConfig.focusInside === FocusInsideModes.OnEnterOrSpaceMode && isEnterOrSpace && isSource(component, simulatedEvent)) {
            optFocusIn(keyingConfig).each(function(focusIn2) {
              focusIn2(component, keyingConfig, keyingState);
              simulatedEvent.stop();
            });
          }
        };
        var keyboardEvents = [
          run$1(keydown(), function(component, simulatedEvent) {
            processKey(component, simulatedEvent, getKeydownRules2, keyingConfig, keyingState).fold(function() {
              tryGoInsideComponent(component, simulatedEvent);
            }, function(_2) {
              simulatedEvent.stop();
            });
          }),
          run$1(keyup(), function(component, simulatedEvent) {
            processKey(component, simulatedEvent, getKeyupRules2, keyingConfig, keyingState).each(function(_2) {
              simulatedEvent.stop();
            });
          })
        ];
        return derive$2(onFocusHandler.toArray().concat(keyboardEvents));
      };
      var me2 = {
        schema: schema2,
        processKey,
        toEvents: toEvents2
      };
      return me2;
    };
    var create$5 = function(cyclicField) {
      var schema2 = [
        option("onEscape"),
        option("onEnter"),
        defaulted("selector", '[data-alloy-tabstop="true"]:not(:disabled)'),
        defaulted("firstTabstop", 0),
        defaulted("useTabstopAt", always),
        option("visibilitySelector")
      ].concat([cyclicField]);
      var isVisible3 = function(tabbingConfig, element2) {
        var target = tabbingConfig.visibilitySelector.bind(function(sel) {
          return closest$1(element2, sel);
        }).getOr(element2);
        return get$b(target) > 0;
      };
      var findInitial = function(component, tabbingConfig) {
        var tabstops = descendants(component.element, tabbingConfig.selector);
        var visibles = filter$2(tabstops, function(elem) {
          return isVisible3(tabbingConfig, elem);
        });
        return Optional.from(visibles[tabbingConfig.firstTabstop]);
      };
      var findCurrent2 = function(component, tabbingConfig) {
        return tabbingConfig.focusManager.get(component).bind(function(elem) {
          return closest$1(elem, tabbingConfig.selector);
        });
      };
      var isTabstop = function(tabbingConfig, element2) {
        return isVisible3(tabbingConfig, element2) && tabbingConfig.useTabstopAt(element2);
      };
      var focusIn2 = function(component, tabbingConfig, _tabbingState) {
        findInitial(component, tabbingConfig).each(function(target) {
          tabbingConfig.focusManager.set(component, target);
        });
      };
      var goFromTabstop = function(component, tabstops, stopIndex, tabbingConfig, cycle) {
        return cycle(tabstops, stopIndex, function(elem) {
          return isTabstop(tabbingConfig, elem);
        }).fold(function() {
          return tabbingConfig.cyclic ? Optional.some(true) : Optional.none();
        }, function(target) {
          tabbingConfig.focusManager.set(component, target);
          return Optional.some(true);
        });
      };
      var go2 = function(component, _simulatedEvent, tabbingConfig, cycle) {
        var tabstops = descendants(component.element, tabbingConfig.selector);
        return findCurrent2(component, tabbingConfig).bind(function(tabstop) {
          var optStopIndex = findIndex$1(tabstops, curry(eq2, tabstop));
          return optStopIndex.bind(function(stopIndex) {
            return goFromTabstop(component, tabstops, stopIndex, tabbingConfig, cycle);
          });
        });
      };
      var goBackwards = function(component, simulatedEvent, tabbingConfig) {
        var navigate = tabbingConfig.cyclic ? cyclePrev : tryPrev;
        return go2(component, simulatedEvent, tabbingConfig, navigate);
      };
      var goForwards = function(component, simulatedEvent, tabbingConfig) {
        var navigate = tabbingConfig.cyclic ? cycleNext : tryNext;
        return go2(component, simulatedEvent, tabbingConfig, navigate);
      };
      var execute3 = function(component, simulatedEvent, tabbingConfig) {
        return tabbingConfig.onEnter.bind(function(f2) {
          return f2(component, simulatedEvent);
        });
      };
      var exit = function(component, simulatedEvent, tabbingConfig) {
        return tabbingConfig.onEscape.bind(function(f2) {
          return f2(component, simulatedEvent);
        });
      };
      var getKeydownRules2 = constant$1([
        rule(and([
          isShift,
          inSet(TAB)
        ]), goBackwards),
        rule(inSet(TAB), goForwards),
        rule(inSet(ESCAPE), exit),
        rule(and([
          isNotShift,
          inSet(ENTER)
        ]), execute3)
      ]);
      var getKeyupRules2 = constant$1([]);
      return typical(schema2, NoState.init, getKeydownRules2, getKeyupRules2, function() {
        return Optional.some(focusIn2);
      });
    };
    var AcyclicType = create$5(customField("cyclic", never));
    var CyclicType = create$5(customField("cyclic", always));
    var doDefaultExecute = function(component, _simulatedEvent, focused) {
      dispatch2(component, focused, execute$5());
      return Optional.some(true);
    };
    var defaultExecute = function(component, simulatedEvent, focused) {
      var isComplex = inside(focused) && inSet(SPACE)(simulatedEvent.event);
      return isComplex ? Optional.none() : doDefaultExecute(component, simulatedEvent, focused);
    };
    var stopEventForFirefox = function(_component, _simulatedEvent) {
      return Optional.some(true);
    };
    var schema$v = [
      defaulted("execute", defaultExecute),
      defaulted("useSpace", false),
      defaulted("useEnter", true),
      defaulted("useControlEnter", false),
      defaulted("useDown", false)
    ];
    var execute$4 = function(component, simulatedEvent, executeConfig) {
      return executeConfig.execute(component, simulatedEvent, component.element);
    };
    var getKeydownRules$5 = function(component, _simulatedEvent, executeConfig, _executeState) {
      var spaceExec = executeConfig.useSpace && !inside(component.element) ? SPACE : [];
      var enterExec = executeConfig.useEnter ? ENTER : [];
      var downExec = executeConfig.useDown ? DOWN : [];
      var execKeys = spaceExec.concat(enterExec).concat(downExec);
      return [rule(inSet(execKeys), execute$4)].concat(executeConfig.useControlEnter ? [rule(and([
        isControl,
        inSet(ENTER)
      ]), execute$4)] : []);
    };
    var getKeyupRules$5 = function(component, _simulatedEvent, executeConfig, _executeState) {
      return executeConfig.useSpace && !inside(component.element) ? [rule(inSet(SPACE), stopEventForFirefox)] : [];
    };
    var ExecutionType = typical(schema$v, NoState.init, getKeydownRules$5, getKeyupRules$5, function() {
      return Optional.none();
    });
    var flatgrid$1 = function() {
      var dimensions = value$1();
      var setGridSize = function(numRows, numColumns) {
        dimensions.set({
          numRows,
          numColumns
        });
      };
      var getNumRows = function() {
        return dimensions.get().map(function(d2) {
          return d2.numRows;
        });
      };
      var getNumColumns = function() {
        return dimensions.get().map(function(d2) {
          return d2.numColumns;
        });
      };
      return nu$8({
        readState: function() {
          return dimensions.get().map(function(d2) {
            return {
              numRows: String(d2.numRows),
              numColumns: String(d2.numColumns)
            };
          }).getOr({
            numRows: "?",
            numColumns: "?"
          });
        },
        setGridSize,
        getNumRows,
        getNumColumns
      });
    };
    var init$d = function(spec) {
      return spec.state(spec);
    };
    var KeyingState = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      flatgrid: flatgrid$1,
      init: init$d
    });
    var useH = function(movement) {
      return function(component, simulatedEvent, config2, state) {
        var move2 = movement(component.element);
        return use(move2, component, simulatedEvent, config2, state);
      };
    };
    var west$1 = function(moveLeft2, moveRight2) {
      var movement = onDirection(moveLeft2, moveRight2);
      return useH(movement);
    };
    var east$1 = function(moveLeft2, moveRight2) {
      var movement = onDirection(moveRight2, moveLeft2);
      return useH(movement);
    };
    var useV = function(move2) {
      return function(component, simulatedEvent, config2, state) {
        return use(move2, component, simulatedEvent, config2, state);
      };
    };
    var use = function(move2, component, simulatedEvent, config2, state) {
      var outcome = config2.focusManager.get(component).bind(function(focused) {
        return move2(component.element, focused, config2, state);
      });
      return outcome.map(function(newFocus) {
        config2.focusManager.set(component, newFocus);
        return true;
      });
    };
    var north$1 = useV;
    var south$1 = useV;
    var move$1 = useV;
    var isHidden$1 = function(dom2) {
      return dom2.offsetWidth <= 0 && dom2.offsetHeight <= 0;
    };
    var isVisible2 = function(element2) {
      return !isHidden$1(element2.dom);
    };
    var locate = function(candidates, predicate) {
      return findIndex$1(candidates, predicate).map(function(index) {
        return {
          index,
          candidates
        };
      });
    };
    var locateVisible = function(container, current, selector) {
      var predicate = function(x2) {
        return eq2(x2, current);
      };
      var candidates = descendants(container, selector);
      var visible = filter$2(candidates, isVisible2);
      return locate(visible, predicate);
    };
    var findIndex2 = function(elements2, target) {
      return findIndex$1(elements2, function(elem) {
        return eq2(target, elem);
      });
    };
    var withGrid = function(values2, index, numCols, f2) {
      var oldRow = Math.floor(index / numCols);
      var oldColumn = index % numCols;
      return f2(oldRow, oldColumn).bind(function(address) {
        var newIndex = address.row * numCols + address.column;
        return newIndex >= 0 && newIndex < values2.length ? Optional.some(values2[newIndex]) : Optional.none();
      });
    };
    var cycleHorizontal$1 = function(values2, index, numRows, numCols, delta) {
      return withGrid(values2, index, numCols, function(oldRow, oldColumn) {
        var onLastRow = oldRow === numRows - 1;
        var colsInRow = onLastRow ? values2.length - oldRow * numCols : numCols;
        var newColumn = cycleBy(oldColumn, delta, 0, colsInRow - 1);
        return Optional.some({
          row: oldRow,
          column: newColumn
        });
      });
    };
    var cycleVertical$1 = function(values2, index, numRows, numCols, delta) {
      return withGrid(values2, index, numCols, function(oldRow, oldColumn) {
        var newRow = cycleBy(oldRow, delta, 0, numRows - 1);
        var onLastRow = newRow === numRows - 1;
        var colsInRow = onLastRow ? values2.length - newRow * numCols : numCols;
        var newCol = clamp$1(oldColumn, 0, colsInRow - 1);
        return Optional.some({
          row: newRow,
          column: newCol
        });
      });
    };
    var cycleRight$1 = function(values2, index, numRows, numCols) {
      return cycleHorizontal$1(values2, index, numRows, numCols, 1);
    };
    var cycleLeft$1 = function(values2, index, numRows, numCols) {
      return cycleHorizontal$1(values2, index, numRows, numCols, -1);
    };
    var cycleUp$1 = function(values2, index, numRows, numCols) {
      return cycleVertical$1(values2, index, numRows, numCols, -1);
    };
    var cycleDown$1 = function(values2, index, numRows, numCols) {
      return cycleVertical$1(values2, index, numRows, numCols, 1);
    };
    var schema$u = [
      required$1("selector"),
      defaulted("execute", defaultExecute),
      onKeyboardHandler("onEscape"),
      defaulted("captureTab", false),
      initSize()
    ];
    var focusIn$3 = function(component, gridConfig, _gridState) {
      descendant(component.element, gridConfig.selector).each(function(first2) {
        gridConfig.focusManager.set(component, first2);
      });
    };
    var findCurrent$1 = function(component, gridConfig) {
      return gridConfig.focusManager.get(component).bind(function(elem) {
        return closest$1(elem, gridConfig.selector);
      });
    };
    var execute$3 = function(component, simulatedEvent, gridConfig, _gridState) {
      return findCurrent$1(component, gridConfig).bind(function(focused) {
        return gridConfig.execute(component, simulatedEvent, focused);
      });
    };
    var doMove$2 = function(cycle) {
      return function(element2, focused, gridConfig, gridState) {
        return locateVisible(element2, focused, gridConfig.selector).bind(function(identified) {
          return cycle(identified.candidates, identified.index, gridState.getNumRows().getOr(gridConfig.initSize.numRows), gridState.getNumColumns().getOr(gridConfig.initSize.numColumns));
        });
      };
    };
    var handleTab = function(_component, _simulatedEvent, gridConfig) {
      return gridConfig.captureTab ? Optional.some(true) : Optional.none();
    };
    var doEscape$1 = function(component, simulatedEvent, gridConfig) {
      return gridConfig.onEscape(component, simulatedEvent);
    };
    var moveLeft$3 = doMove$2(cycleLeft$1);
    var moveRight$3 = doMove$2(cycleRight$1);
    var moveNorth$1 = doMove$2(cycleUp$1);
    var moveSouth$1 = doMove$2(cycleDown$1);
    var getKeydownRules$4 = constant$1([
      rule(inSet(LEFT), west$1(moveLeft$3, moveRight$3)),
      rule(inSet(RIGHT), east$1(moveLeft$3, moveRight$3)),
      rule(inSet(UP), north$1(moveNorth$1)),
      rule(inSet(DOWN), south$1(moveSouth$1)),
      rule(and([
        isShift,
        inSet(TAB)
      ]), handleTab),
      rule(and([
        isNotShift,
        inSet(TAB)
      ]), handleTab),
      rule(inSet(ESCAPE), doEscape$1),
      rule(inSet(SPACE.concat(ENTER)), execute$3)
    ]);
    var getKeyupRules$4 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]);
    var FlatgridType = typical(schema$u, flatgrid$1, getKeydownRules$4, getKeyupRules$4, function() {
      return Optional.some(focusIn$3);
    });
    var horizontal = function(container, selector, current, delta) {
      var isDisabledButton = function(candidate) {
        return name$2(candidate) === "button" && get$d(candidate, "disabled") === "disabled";
      };
      var tryCycle = function(initial, index, candidates) {
        var newIndex = cycleBy(index, delta, 0, candidates.length - 1);
        if (newIndex === initial) {
          return Optional.none();
        } else {
          return isDisabledButton(candidates[newIndex]) ? tryCycle(initial, newIndex, candidates) : Optional.from(candidates[newIndex]);
        }
      };
      return locateVisible(container, current, selector).bind(function(identified) {
        var index = identified.index;
        var candidates = identified.candidates;
        return tryCycle(index, index, candidates);
      });
    };
    var schema$t = [
      required$1("selector"),
      defaulted("getInitial", Optional.none),
      defaulted("execute", defaultExecute),
      onKeyboardHandler("onEscape"),
      defaulted("executeOnMove", false),
      defaulted("allowVertical", true)
    ];
    var findCurrent = function(component, flowConfig) {
      return flowConfig.focusManager.get(component).bind(function(elem) {
        return closest$1(elem, flowConfig.selector);
      });
    };
    var execute$2 = function(component, simulatedEvent, flowConfig) {
      return findCurrent(component, flowConfig).bind(function(focused) {
        return flowConfig.execute(component, simulatedEvent, focused);
      });
    };
    var focusIn$2 = function(component, flowConfig, _state) {
      flowConfig.getInitial(component).orThunk(function() {
        return descendant(component.element, flowConfig.selector);
      }).each(function(first2) {
        flowConfig.focusManager.set(component, first2);
      });
    };
    var moveLeft$2 = function(element2, focused, info) {
      return horizontal(element2, info.selector, focused, -1);
    };
    var moveRight$2 = function(element2, focused, info) {
      return horizontal(element2, info.selector, focused, 1);
    };
    var doMove$1 = function(movement) {
      return function(component, simulatedEvent, flowConfig, flowState) {
        return movement(component, simulatedEvent, flowConfig, flowState).bind(function() {
          return flowConfig.executeOnMove ? execute$2(component, simulatedEvent, flowConfig) : Optional.some(true);
        });
      };
    };
    var doEscape = function(component, simulatedEvent, flowConfig) {
      return flowConfig.onEscape(component, simulatedEvent);
    };
    var getKeydownRules$3 = function(_component, _se, flowConfig, _flowState) {
      var westMovers = LEFT.concat(flowConfig.allowVertical ? UP : []);
      var eastMovers = RIGHT.concat(flowConfig.allowVertical ? DOWN : []);
      return [
        rule(inSet(westMovers), doMove$1(west$1(moveLeft$2, moveRight$2))),
        rule(inSet(eastMovers), doMove$1(east$1(moveLeft$2, moveRight$2))),
        rule(inSet(ENTER), execute$2),
        rule(inSet(SPACE), execute$2),
        rule(inSet(ESCAPE), doEscape)
      ];
    };
    var getKeyupRules$3 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]);
    var FlowType = typical(schema$t, NoState.init, getKeydownRules$3, getKeyupRules$3, function() {
      return Optional.some(focusIn$2);
    });
    var toCell = function(matrix2, rowIndex, columnIndex) {
      return Optional.from(matrix2[rowIndex]).bind(function(row) {
        return Optional.from(row[columnIndex]).map(function(cell) {
          return {
            rowIndex,
            columnIndex,
            cell
          };
        });
      });
    };
    var cycleHorizontal = function(matrix2, rowIndex, startCol, deltaCol) {
      var row = matrix2[rowIndex];
      var colsInRow = row.length;
      var newColIndex = cycleBy(startCol, deltaCol, 0, colsInRow - 1);
      return toCell(matrix2, rowIndex, newColIndex);
    };
    var cycleVertical = function(matrix2, colIndex, startRow, deltaRow) {
      var nextRowIndex = cycleBy(startRow, deltaRow, 0, matrix2.length - 1);
      var colsInNextRow = matrix2[nextRowIndex].length;
      var nextColIndex = clamp$1(colIndex, 0, colsInNextRow - 1);
      return toCell(matrix2, nextRowIndex, nextColIndex);
    };
    var moveHorizontal = function(matrix2, rowIndex, startCol, deltaCol) {
      var row = matrix2[rowIndex];
      var colsInRow = row.length;
      var newColIndex = clamp$1(startCol + deltaCol, 0, colsInRow - 1);
      return toCell(matrix2, rowIndex, newColIndex);
    };
    var moveVertical = function(matrix2, colIndex, startRow, deltaRow) {
      var nextRowIndex = clamp$1(startRow + deltaRow, 0, matrix2.length - 1);
      var colsInNextRow = matrix2[nextRowIndex].length;
      var nextColIndex = clamp$1(colIndex, 0, colsInNextRow - 1);
      return toCell(matrix2, nextRowIndex, nextColIndex);
    };
    var cycleRight = function(matrix2, startRow, startCol) {
      return cycleHorizontal(matrix2, startRow, startCol, 1);
    };
    var cycleLeft = function(matrix2, startRow, startCol) {
      return cycleHorizontal(matrix2, startRow, startCol, -1);
    };
    var cycleUp = function(matrix2, startRow, startCol) {
      return cycleVertical(matrix2, startCol, startRow, -1);
    };
    var cycleDown = function(matrix2, startRow, startCol) {
      return cycleVertical(matrix2, startCol, startRow, 1);
    };
    var moveLeft$1 = function(matrix2, startRow, startCol) {
      return moveHorizontal(matrix2, startRow, startCol, -1);
    };
    var moveRight$1 = function(matrix2, startRow, startCol) {
      return moveHorizontal(matrix2, startRow, startCol, 1);
    };
    var moveUp$1 = function(matrix2, startRow, startCol) {
      return moveVertical(matrix2, startCol, startRow, -1);
    };
    var moveDown$1 = function(matrix2, startRow, startCol) {
      return moveVertical(matrix2, startCol, startRow, 1);
    };
    var schema$s = [
      requiredObjOf("selectors", [
        required$1("row"),
        required$1("cell")
      ]),
      defaulted("cycles", true),
      defaulted("previousSelector", Optional.none),
      defaulted("execute", defaultExecute)
    ];
    var focusIn$1 = function(component, matrixConfig, _state) {
      var focused = matrixConfig.previousSelector(component).orThunk(function() {
        var selectors = matrixConfig.selectors;
        return descendant(component.element, selectors.cell);
      });
      focused.each(function(cell) {
        matrixConfig.focusManager.set(component, cell);
      });
    };
    var execute$1 = function(component, simulatedEvent, matrixConfig) {
      return search(component.element).bind(function(focused) {
        return matrixConfig.execute(component, simulatedEvent, focused);
      });
    };
    var toMatrix = function(rows, matrixConfig) {
      return map$2(rows, function(row) {
        return descendants(row, matrixConfig.selectors.cell);
      });
    };
    var doMove = function(ifCycle, ifMove) {
      return function(element2, focused, matrixConfig) {
        var move2 = matrixConfig.cycles ? ifCycle : ifMove;
        return closest$1(focused, matrixConfig.selectors.row).bind(function(inRow) {
          var cellsInRow = descendants(inRow, matrixConfig.selectors.cell);
          return findIndex2(cellsInRow, focused).bind(function(colIndex) {
            var allRows = descendants(element2, matrixConfig.selectors.row);
            return findIndex2(allRows, inRow).bind(function(rowIndex) {
              var matrix2 = toMatrix(allRows, matrixConfig);
              return move2(matrix2, rowIndex, colIndex).map(function(next) {
                return next.cell;
              });
            });
          });
        });
      };
    };
    var moveLeft = doMove(cycleLeft, moveLeft$1);
    var moveRight = doMove(cycleRight, moveRight$1);
    var moveNorth = doMove(cycleUp, moveUp$1);
    var moveSouth = doMove(cycleDown, moveDown$1);
    var getKeydownRules$2 = constant$1([
      rule(inSet(LEFT), west$1(moveLeft, moveRight)),
      rule(inSet(RIGHT), east$1(moveLeft, moveRight)),
      rule(inSet(UP), north$1(moveNorth)),
      rule(inSet(DOWN), south$1(moveSouth)),
      rule(inSet(SPACE.concat(ENTER)), execute$1)
    ]);
    var getKeyupRules$2 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]);
    var MatrixType = typical(schema$s, NoState.init, getKeydownRules$2, getKeyupRules$2, function() {
      return Optional.some(focusIn$1);
    });
    var schema$r = [
      required$1("selector"),
      defaulted("execute", defaultExecute),
      defaulted("moveOnTab", false)
    ];
    var execute2 = function(component, simulatedEvent, menuConfig) {
      return menuConfig.focusManager.get(component).bind(function(focused) {
        return menuConfig.execute(component, simulatedEvent, focused);
      });
    };
    var focusIn = function(component, menuConfig, _state) {
      descendant(component.element, menuConfig.selector).each(function(first2) {
        menuConfig.focusManager.set(component, first2);
      });
    };
    var moveUp = function(element2, focused, info) {
      return horizontal(element2, info.selector, focused, -1);
    };
    var moveDown = function(element2, focused, info) {
      return horizontal(element2, info.selector, focused, 1);
    };
    var fireShiftTab = function(component, simulatedEvent, menuConfig, menuState) {
      return menuConfig.moveOnTab ? move$1(moveUp)(component, simulatedEvent, menuConfig, menuState) : Optional.none();
    };
    var fireTab = function(component, simulatedEvent, menuConfig, menuState) {
      return menuConfig.moveOnTab ? move$1(moveDown)(component, simulatedEvent, menuConfig, menuState) : Optional.none();
    };
    var getKeydownRules$1 = constant$1([
      rule(inSet(UP), move$1(moveUp)),
      rule(inSet(DOWN), move$1(moveDown)),
      rule(and([
        isShift,
        inSet(TAB)
      ]), fireShiftTab),
      rule(and([
        isNotShift,
        inSet(TAB)
      ]), fireTab),
      rule(inSet(ENTER), execute2),
      rule(inSet(SPACE), execute2)
    ]);
    var getKeyupRules$1 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]);
    var MenuType = typical(schema$r, NoState.init, getKeydownRules$1, getKeyupRules$1, function() {
      return Optional.some(focusIn);
    });
    var schema$q = [
      onKeyboardHandler("onSpace"),
      onKeyboardHandler("onEnter"),
      onKeyboardHandler("onShiftEnter"),
      onKeyboardHandler("onLeft"),
      onKeyboardHandler("onRight"),
      onKeyboardHandler("onTab"),
      onKeyboardHandler("onShiftTab"),
      onKeyboardHandler("onUp"),
      onKeyboardHandler("onDown"),
      onKeyboardHandler("onEscape"),
      defaulted("stopSpaceKeyup", false),
      option("focusIn")
    ];
    var getKeydownRules = function(component, simulatedEvent, specialInfo) {
      return [
        rule(inSet(SPACE), specialInfo.onSpace),
        rule(and([
          isNotShift,
          inSet(ENTER)
        ]), specialInfo.onEnter),
        rule(and([
          isShift,
          inSet(ENTER)
        ]), specialInfo.onShiftEnter),
        rule(and([
          isShift,
          inSet(TAB)
        ]), specialInfo.onShiftTab),
        rule(and([
          isNotShift,
          inSet(TAB)
        ]), specialInfo.onTab),
        rule(inSet(UP), specialInfo.onUp),
        rule(inSet(DOWN), specialInfo.onDown),
        rule(inSet(LEFT), specialInfo.onLeft),
        rule(inSet(RIGHT), specialInfo.onRight),
        rule(inSet(SPACE), specialInfo.onSpace),
        rule(inSet(ESCAPE), specialInfo.onEscape)
      ];
    };
    var getKeyupRules = function(component, simulatedEvent, specialInfo) {
      return specialInfo.stopSpaceKeyup ? [rule(inSet(SPACE), stopEventForFirefox)] : [];
    };
    var SpecialType = typical(schema$q, NoState.init, getKeydownRules, getKeyupRules, function(specialInfo) {
      return specialInfo.focusIn;
    });
    var acyclic = AcyclicType.schema();
    var cyclic = CyclicType.schema();
    var flow = FlowType.schema();
    var flatgrid = FlatgridType.schema();
    var matrix = MatrixType.schema();
    var execution = ExecutionType.schema();
    var menu = MenuType.schema();
    var special = SpecialType.schema();
    var KeyboardBranches = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      acyclic,
      cyclic,
      flow,
      flatgrid,
      matrix,
      execution,
      menu,
      special
    });
    var isFlatgridState = function(keyState) {
      return hasNonNullableKey(keyState, "setGridSize");
    };
    var Keying = createModes({
      branchKey: "mode",
      branches: KeyboardBranches,
      name: "keying",
      active: {
        events: function(keyingConfig, keyingState) {
          var handler = keyingConfig.handler;
          return handler.toEvents(keyingConfig, keyingState);
        }
      },
      apis: {
        focusIn: function(component, keyConfig, keyState) {
          keyConfig.sendFocusIn(keyConfig).fold(function() {
            component.getSystem().triggerFocus(component.element, component.element);
          }, function(sendFocusIn) {
            sendFocusIn(component, keyConfig, keyState);
          });
        },
        setGridSize: function(component, keyConfig, keyState, numRows, numColumns) {
          if (!isFlatgridState(keyState)) {
            console.error("Layout does not support setGridSize");
          } else {
            keyState.setGridSize(numRows, numColumns);
          }
        }
      },
      state: KeyingState
    });
    var set$2 = function(component, replaceConfig, replaceState, data) {
      preserve$1(function() {
        var newChildren = map$2(data, component.getSystem().build);
        replaceChildren(component, newChildren);
      }, component.element);
    };
    var insert = function(component, replaceConfig, insertion, childSpec) {
      var child2 = component.getSystem().build(childSpec);
      attachWith(component, child2, insertion);
    };
    var append = function(component, replaceConfig, replaceState, appendee) {
      insert(component, replaceConfig, append$2, appendee);
    };
    var prepend = function(component, replaceConfig, replaceState, prependee) {
      insert(component, replaceConfig, prepend$1, prependee);
    };
    var remove = function(component, replaceConfig, replaceState, removee) {
      var children2 = contents(component);
      var foundChild = find$5(children2, function(child2) {
        return eq2(removee.element, child2.element);
      });
      foundChild.each(detach);
    };
    var contents = function(component, _replaceConfig) {
      return component.components();
    };
    var replaceAt = function(component, replaceConfig, replaceState, replaceeIndex, replacer) {
      var children2 = contents(component);
      return Optional.from(children2[replaceeIndex]).map(function(replacee) {
        remove(component, replaceConfig, replaceState, replacee);
        replacer.each(function(r3) {
          insert(component, replaceConfig, function(p2, c2) {
            appendAt(p2, c2, replaceeIndex);
          }, r3);
        });
        return replacee;
      });
    };
    var replaceBy = function(component, replaceConfig, replaceState, replaceePred, replacer) {
      var children2 = contents(component);
      return findIndex$1(children2, replaceePred).bind(function(replaceeIndex) {
        return replaceAt(component, replaceConfig, replaceState, replaceeIndex, replacer);
      });
    };
    var ReplaceApis = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      append,
      prepend,
      remove,
      replaceAt,
      replaceBy,
      set: set$2,
      contents
    });
    var Replacing = create$7({
      fields: [],
      name: "replacing",
      apis: ReplaceApis
    });
    var events$d = function(name2, eventHandlers) {
      var events2 = derive$2(eventHandlers);
      return create$7({
        fields: [required$1("enabled")],
        name: name2,
        active: { events: constant$1(events2) }
      });
    };
    var config = function(name2, eventHandlers) {
      var me2 = events$d(name2, eventHandlers);
      return {
        key: name2,
        value: {
          config: {},
          me: me2,
          configAsRaw: constant$1({}),
          initialConfig: {},
          state: NoState
        }
      };
    };
    var focus$2 = function(component, focusConfig) {
      if (!focusConfig.ignore) {
        focus$3(component.element);
        focusConfig.onFocus(component);
      }
    };
    var blur = function(component, focusConfig) {
      if (!focusConfig.ignore) {
        blur$1(component.element);
      }
    };
    var isFocused = function(component) {
      return hasFocus(component.element);
    };
    var FocusApis = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      focus: focus$2,
      blur,
      isFocused
    });
    var exhibit$4 = function(base2, focusConfig) {
      var mod = focusConfig.ignore ? {} : { attributes: { tabindex: "-1" } };
      return nu$7(mod);
    };
    var events$c = function(focusConfig) {
      return derive$2([run$1(focus$4(), function(component, simulatedEvent) {
        focus$2(component, focusConfig);
        simulatedEvent.stop();
      })].concat(focusConfig.stopMousedown ? [run$1(mousedown(), function(_2, simulatedEvent) {
        simulatedEvent.event.prevent();
      })] : []));
    };
    var ActiveFocus = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      exhibit: exhibit$4,
      events: events$c
    });
    var FocusSchema = [
      onHandler("onFocus"),
      defaulted("stopMousedown", false),
      defaulted("ignore", false)
    ];
    var Focusing = create$7({
      fields: FocusSchema,
      name: "focusing",
      active: ActiveFocus,
      apis: FocusApis
    });
    var SetupBehaviourCellState = function(initialState) {
      var init2 = function() {
        var cell = Cell(initialState);
        var get2 = function() {
          return cell.get();
        };
        var set3 = function(newState) {
          return cell.set(newState);
        };
        var clear2 = function() {
          return cell.set(initialState);
        };
        var readState = function() {
          return cell.get();
        };
        return {
          get: get2,
          set: set3,
          clear: clear2,
          readState
        };
      };
      return { init: init2 };
    };
    var updateAriaState = function(component, toggleConfig, toggleState) {
      var ariaInfo = toggleConfig.aria;
      ariaInfo.update(component, ariaInfo, toggleState.get());
    };
    var updateClass = function(component, toggleConfig, toggleState) {
      toggleConfig.toggleClass.each(function(toggleClass) {
        if (toggleState.get()) {
          add$2(component.element, toggleClass);
        } else {
          remove$2(component.element, toggleClass);
        }
      });
    };
    var toggle$2 = function(component, toggleConfig, toggleState) {
      set$1(component, toggleConfig, toggleState, !toggleState.get());
    };
    var on2 = function(component, toggleConfig, toggleState) {
      toggleState.set(true);
      updateClass(component, toggleConfig, toggleState);
      updateAriaState(component, toggleConfig, toggleState);
    };
    var off = function(component, toggleConfig, toggleState) {
      toggleState.set(false);
      updateClass(component, toggleConfig, toggleState);
      updateAriaState(component, toggleConfig, toggleState);
    };
    var set$1 = function(component, toggleConfig, toggleState, state) {
      var action = state ? on2 : off;
      action(component, toggleConfig, toggleState);
    };
    var isOn = function(component, toggleConfig, toggleState) {
      return toggleState.get();
    };
    var onLoad = function(component, toggleConfig, toggleState) {
      set$1(component, toggleConfig, toggleState, toggleConfig.selected);
    };
    var ToggleApis = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      onLoad,
      toggle: toggle$2,
      isOn,
      on: on2,
      off,
      set: set$1
    });
    var exhibit$3 = function() {
      return nu$7({});
    };
    var events$b = function(toggleConfig, toggleState) {
      var execute3 = executeEvent(toggleConfig, toggleState, toggle$2);
      var load = loadEvent(toggleConfig, toggleState, onLoad);
      return derive$2(flatten([
        toggleConfig.toggleOnExecute ? [execute3] : [],
        [load]
      ]));
    };
    var ActiveToggle = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      exhibit: exhibit$3,
      events: events$b
    });
    var updatePressed = function(component, ariaInfo, status) {
      set$8(component.element, "aria-pressed", status);
      if (ariaInfo.syncWithExpanded) {
        updateExpanded(component, ariaInfo, status);
      }
    };
    var updateSelected = function(component, ariaInfo, status) {
      set$8(component.element, "aria-selected", status);
    };
    var updateChecked = function(component, ariaInfo, status) {
      set$8(component.element, "aria-checked", status);
    };
    var updateExpanded = function(component, ariaInfo, status) {
      set$8(component.element, "aria-expanded", status);
    };
    var ToggleSchema = [
      defaulted("selected", false),
      option("toggleClass"),
      defaulted("toggleOnExecute", true),
      defaultedOf("aria", { mode: "none" }, choose$1("mode", {
        pressed: [
          defaulted("syncWithExpanded", false),
          output$1("update", updatePressed)
        ],
        checked: [output$1("update", updateChecked)],
        expanded: [output$1("update", updateExpanded)],
        selected: [output$1("update", updateSelected)],
        none: [output$1("update", noop3)]
      }))
    ];
    var Toggling = create$7({
      fields: ToggleSchema,
      name: "toggling",
      active: ActiveToggle,
      apis: ToggleApis,
      state: SetupBehaviourCellState(false)
    });
    var pointerEvents = function() {
      var onClick = function(component, simulatedEvent) {
        simulatedEvent.stop();
        emitExecute(component);
      };
      return [
        run$1(click(), onClick),
        run$1(tap(), onClick),
        cutter(touchstart()),
        cutter(mousedown())
      ];
    };
    var events$a = function(optAction) {
      var executeHandler = function(action) {
        return runOnExecute$1(function(component, simulatedEvent) {
          action(component);
          simulatedEvent.stop();
        });
      };
      return derive$2(flatten([
        optAction.map(executeHandler).toArray(),
        pointerEvents()
      ]));
    };
    var hoverEvent = "alloy.item-hover";
    var focusEvent = "alloy.item-focus";
    var onHover = function(item2) {
      if (search(item2.element).isNone() || Focusing.isFocused(item2)) {
        if (!Focusing.isFocused(item2)) {
          Focusing.focus(item2);
        }
        emitWith(item2, hoverEvent, { item: item2 });
      }
    };
    var onFocus$1 = function(item2) {
      emitWith(item2, focusEvent, { item: item2 });
    };
    var hover = constant$1(hoverEvent);
    var focus$1 = constant$1(focusEvent);
    var builder$2 = function(detail) {
      return {
        dom: detail.dom,
        domModification: __assign(__assign({}, detail.domModification), { attributes: __assign(__assign(__assign({ "role": detail.toggling.isSome() ? "menuitemcheckbox" : "menuitem" }, detail.domModification.attributes), { "aria-haspopup": detail.hasSubmenu }), detail.hasSubmenu ? { "aria-expanded": false } : {}) }),
        behaviours: SketchBehaviours.augment(detail.itemBehaviours, [
          detail.toggling.fold(Toggling.revoke, function(tConfig) {
            return Toggling.config(__assign({ aria: { mode: "checked" } }, tConfig));
          }),
          Focusing.config({
            ignore: detail.ignoreFocus,
            stopMousedown: detail.ignoreFocus,
            onFocus: function(component) {
              onFocus$1(component);
            }
          }),
          Keying.config({ mode: "execution" }),
          Representing.config({
            store: {
              mode: "memory",
              initialValue: detail.data
            }
          }),
          config("item-type-events", __spreadArray(__spreadArray([], pointerEvents(), true), [
            run$1(mouseover(), onHover),
            run$1(focusItem(), Focusing.focus)
          ], false))
        ]),
        components: detail.components,
        eventOrder: detail.eventOrder
      };
    };
    var schema$p = [
      required$1("data"),
      required$1("components"),
      required$1("dom"),
      defaulted("hasSubmenu", false),
      option("toggling"),
      SketchBehaviours.field("itemBehaviours", [
        Toggling,
        Focusing,
        Keying,
        Representing
      ]),
      defaulted("ignoreFocus", false),
      defaulted("domModification", {}),
      output$1("builder", builder$2),
      defaulted("eventOrder", {})
    ];
    var builder$1 = function(detail) {
      return {
        dom: detail.dom,
        components: detail.components,
        events: derive$2([stopper(focusItem())])
      };
    };
    var schema$o = [
      required$1("dom"),
      required$1("components"),
      output$1("builder", builder$1)
    ];
    var owner$2 = constant$1("item-widget");
    var parts$h = constant$1([required({
      name: "widget",
      overrides: function(detail) {
        return {
          behaviours: derive$1([Representing.config({
            store: {
              mode: "manual",
              getValue: function(_component) {
                return detail.data;
              },
              setValue: noop3
            }
          })])
        };
      }
    })]);
    var builder = function(detail) {
      var subs2 = substitutes(owner$2(), detail, parts$h());
      var components2 = components$1(owner$2(), detail, subs2.internals());
      var focusWidget = function(component) {
        return getPart(component, detail, "widget").map(function(widget) {
          Keying.focusIn(widget);
          return widget;
        });
      };
      var onHorizontalArrow = function(component, simulatedEvent) {
        return inside(simulatedEvent.event.target) ? Optional.none() : function() {
          if (detail.autofocus) {
            simulatedEvent.setSource(component.element);
            return Optional.none();
          } else {
            return Optional.none();
          }
        }();
      };
      return {
        dom: detail.dom,
        components: components2,
        domModification: detail.domModification,
        events: derive$2([
          runOnExecute$1(function(component, simulatedEvent) {
            focusWidget(component).each(function(_widget) {
              simulatedEvent.stop();
            });
          }),
          run$1(mouseover(), onHover),
          run$1(focusItem(), function(component, _simulatedEvent) {
            if (detail.autofocus) {
              focusWidget(component);
            } else {
              Focusing.focus(component);
            }
          })
        ]),
        behaviours: SketchBehaviours.augment(detail.widgetBehaviours, [
          Representing.config({
            store: {
              mode: "memory",
              initialValue: detail.data
            }
          }),
          Focusing.config({
            ignore: detail.ignoreFocus,
            onFocus: function(component) {
              onFocus$1(component);
            }
          }),
          Keying.config({
            mode: "special",
            focusIn: detail.autofocus ? function(component) {
              focusWidget(component);
            } : revoke(),
            onLeft: onHorizontalArrow,
            onRight: onHorizontalArrow,
            onEscape: function(component, simulatedEvent) {
              if (!Focusing.isFocused(component) && !detail.autofocus) {
                Focusing.focus(component);
                return Optional.some(true);
              } else if (detail.autofocus) {
                simulatedEvent.setSource(component.element);
                return Optional.none();
              } else {
                return Optional.none();
              }
            }
          })
        ])
      };
    };
    var schema$n = [
      required$1("uid"),
      required$1("data"),
      required$1("components"),
      required$1("dom"),
      defaulted("autofocus", false),
      defaulted("ignoreFocus", false),
      SketchBehaviours.field("widgetBehaviours", [
        Representing,
        Focusing,
        Keying
      ]),
      defaulted("domModification", {}),
      defaultUidsSchema(parts$h()),
      output$1("builder", builder)
    ];
    var itemSchema$2 = choose$1("type", {
      widget: schema$n,
      item: schema$p,
      separator: schema$o
    });
    var configureGrid = function(detail, movementInfo) {
      return {
        mode: "flatgrid",
        selector: "." + detail.markers.item,
        initSize: {
          numColumns: movementInfo.initSize.numColumns,
          numRows: movementInfo.initSize.numRows
        },
        focusManager: detail.focusManager
      };
    };
    var configureMatrix = function(detail, movementInfo) {
      return {
        mode: "matrix",
        selectors: {
          row: movementInfo.rowSelector,
          cell: "." + detail.markers.item
        },
        focusManager: detail.focusManager
      };
    };
    var configureMenu = function(detail, movementInfo) {
      return {
        mode: "menu",
        selector: "." + detail.markers.item,
        moveOnTab: movementInfo.moveOnTab,
        focusManager: detail.focusManager
      };
    };
    var parts$g = constant$1([group({
      factory: {
        sketch: function(spec) {
          var itemInfo = asRawOrDie$1("menu.spec item", itemSchema$2, spec);
          return itemInfo.builder(itemInfo);
        }
      },
      name: "items",
      unit: "item",
      defaults: function(detail, u2) {
        return has$2(u2, "uid") ? u2 : __assign(__assign({}, u2), { uid: generate$5("item") });
      },
      overrides: function(detail, u2) {
        return {
          type: u2.type,
          ignoreFocus: detail.fakeFocus,
          domModification: { classes: [detail.markers.item] }
        };
      }
    })]);
    var schema$m = constant$1([
      required$1("value"),
      required$1("items"),
      required$1("dom"),
      required$1("components"),
      defaulted("eventOrder", {}),
      field("menuBehaviours", [
        Highlighting,
        Representing,
        Composing,
        Keying
      ]),
      defaultedOf("movement", {
        mode: "menu",
        moveOnTab: true
      }, choose$1("mode", {
        grid: [
          initSize(),
          output$1("config", configureGrid)
        ],
        matrix: [
          output$1("config", configureMatrix),
          required$1("rowSelector")
        ],
        menu: [
          defaulted("moveOnTab", true),
          output$1("config", configureMenu)
        ]
      })),
      itemMarkers(),
      defaulted("fakeFocus", false),
      defaulted("focusManager", dom$2()),
      onHandler("onHighlight")
    ]);
    var focus = constant$1("alloy.menu-focus");
    var make$7 = function(detail, components2, _spec, _externals) {
      return {
        uid: detail.uid,
        dom: detail.dom,
        markers: detail.markers,
        behaviours: augment(detail.menuBehaviours, [
          Highlighting.config({
            highlightClass: detail.markers.selectedItem,
            itemClass: detail.markers.item,
            onHighlight: detail.onHighlight
          }),
          Representing.config({
            store: {
              mode: "memory",
              initialValue: detail.value
            }
          }),
          Composing.config({ find: Optional.some }),
          Keying.config(detail.movement.config(detail, detail.movement))
        ]),
        events: derive$2([
          run$1(focus$1(), function(menu2, simulatedEvent) {
            var event = simulatedEvent.event;
            menu2.getSystem().getByDom(event.target).each(function(item2) {
              Highlighting.highlight(menu2, item2);
              simulatedEvent.stop();
              emitWith(menu2, focus(), {
                menu: menu2,
                item: item2
              });
            });
          }),
          run$1(hover(), function(menu2, simulatedEvent) {
            var item2 = simulatedEvent.event.item;
            Highlighting.highlight(menu2, item2);
          })
        ]),
        components: components2,
        eventOrder: detail.eventOrder,
        domModification: { attributes: { role: "menu" } }
      };
    };
    var Menu = composite({
      name: "Menu",
      configFields: schema$m(),
      partFields: parts$g(),
      factory: make$7
    });
    var transpose$1 = function(obj) {
      return tupleMap(obj, function(v2, k2) {
        return {
          k: v2,
          v: k2
        };
      });
    };
    var trace = function(items, byItem, byMenu, finish) {
      return get$e(byMenu, finish).bind(function(triggerItem) {
        return get$e(items, triggerItem).bind(function(triggerMenu) {
          var rest = trace(items, byItem, byMenu, triggerMenu);
          return Optional.some([triggerMenu].concat(rest));
        });
      }).getOr([]);
    };
    var generate$2 = function(menus, expansions) {
      var items = {};
      each2(menus, function(menuItems, menu2) {
        each$1(menuItems, function(item2) {
          items[item2] = menu2;
        });
      });
      var byItem = expansions;
      var byMenu = transpose$1(expansions);
      var menuPaths = map$12(byMenu, function(_triggerItem, submenu) {
        return [submenu].concat(trace(items, byItem, byMenu, submenu));
      });
      return map$12(items, function(menu2) {
        return get$e(menuPaths, menu2).getOr([menu2]);
      });
    };
    var init$c = function() {
      var expansions = Cell({});
      var menus = Cell({});
      var paths = Cell({});
      var primary = value$1();
      var directory = Cell({});
      var clear2 = function() {
        expansions.set({});
        menus.set({});
        paths.set({});
        primary.clear();
      };
      var isClear = function() {
        return primary.get().isNone();
      };
      var setMenuBuilt = function(menuName, built) {
        var _a2;
        menus.set(__assign(__assign({}, menus.get()), (_a2 = {}, _a2[menuName] = {
          type: "prepared",
          menu: built
        }, _a2)));
      };
      var setContents = function(sPrimary, sMenus, sExpansions, dir) {
        primary.set(sPrimary);
        expansions.set(sExpansions);
        menus.set(sMenus);
        directory.set(dir);
        var sPaths = generate$2(dir, sExpansions);
        paths.set(sPaths);
      };
      var getTriggeringItem = function(menuValue) {
        return find$4(expansions.get(), function(v2, _k) {
          return v2 === menuValue;
        });
      };
      var getTriggerData = function(menuValue, getItemByValue, path2) {
        return getPreparedMenu(menuValue).bind(function(menu2) {
          return getTriggeringItem(menuValue).bind(function(triggeringItemValue) {
            return getItemByValue(triggeringItemValue).map(function(triggeredItem) {
              return {
                triggeredMenu: menu2,
                triggeringItem: triggeredItem,
                triggeringPath: path2
              };
            });
          });
        });
      };
      var getTriggeringPath = function(itemValue, getItemByValue) {
        var extraPath = filter$2(lookupItem(itemValue).toArray(), function(menuValue) {
          return getPreparedMenu(menuValue).isSome();
        });
        return get$e(paths.get(), itemValue).bind(function(path2) {
          var revPath = reverse(extraPath.concat(path2));
          var triggers = bind$3(revPath, function(menuValue, menuIndex) {
            return getTriggerData(menuValue, getItemByValue, revPath.slice(0, menuIndex + 1)).fold(function() {
              return is$1(primary.get(), menuValue) ? [] : [Optional.none()];
            }, function(data) {
              return [Optional.some(data)];
            });
          });
          return sequence(triggers);
        });
      };
      var expand2 = function(itemValue) {
        return get$e(expansions.get(), itemValue).map(function(menu2) {
          var current = get$e(paths.get(), itemValue).getOr([]);
          return [menu2].concat(current);
        });
      };
      var collapse = function(itemValue) {
        return get$e(paths.get(), itemValue).bind(function(path2) {
          return path2.length > 1 ? Optional.some(path2.slice(1)) : Optional.none();
        });
      };
      var refresh2 = function(itemValue) {
        return get$e(paths.get(), itemValue);
      };
      var getPreparedMenu = function(menuValue) {
        return lookupMenu(menuValue).bind(extractPreparedMenu);
      };
      var lookupMenu = function(menuValue) {
        return get$e(menus.get(), menuValue);
      };
      var lookupItem = function(itemValue) {
        return get$e(expansions.get(), itemValue);
      };
      var otherMenus = function(path2) {
        var menuValues = directory.get();
        return difference(keys(menuValues), path2);
      };
      var getPrimary = function() {
        return primary.get().bind(getPreparedMenu);
      };
      var getMenus2 = function() {
        return menus.get();
      };
      return {
        setMenuBuilt,
        setContents,
        expand: expand2,
        refresh: refresh2,
        collapse,
        lookupMenu,
        lookupItem,
        otherMenus,
        getPrimary,
        getMenus: getMenus2,
        clear: clear2,
        isClear,
        getTriggeringPath
      };
    };
    var extractPreparedMenu = function(prep) {
      return prep.type === "prepared" ? Optional.some(prep.menu) : Optional.none();
    };
    var LayeredState = {
      init: init$c,
      extractPreparedMenu
    };
    var make$6 = function(detail, _rawUiSpec) {
      var submenuParentItems = value$1();
      var buildMenus = function(container, primaryName, menus) {
        return map$12(menus, function(spec, name2) {
          var makeSketch = function() {
            return Menu.sketch(__assign(__assign({}, spec), {
              value: name2,
              markers: detail.markers,
              fakeFocus: detail.fakeFocus,
              onHighlight: detail.onHighlight,
              focusManager: detail.fakeFocus ? highlights() : dom$2()
            }));
          };
          return name2 === primaryName ? {
            type: "prepared",
            menu: container.getSystem().build(makeSketch())
          } : {
            type: "notbuilt",
            nbMenu: makeSketch
          };
        });
      };
      var layeredState = LayeredState.init();
      var setup2 = function(container) {
        var componentMap = buildMenus(container, detail.data.primary, detail.data.menus);
        var directory = toDirectory();
        layeredState.setContents(detail.data.primary, componentMap, detail.data.expansions, directory);
        return layeredState.getPrimary();
      };
      var getItemValue = function(item2) {
        return Representing.getValue(item2).value;
      };
      var getItemByValue = function(_container, menus, itemValue) {
        return findMap(menus, function(menu2) {
          if (!menu2.getSystem().isConnected()) {
            return Optional.none();
          }
          var candidates = Highlighting.getCandidates(menu2);
          return find$5(candidates, function(c2) {
            return getItemValue(c2) === itemValue;
          });
        });
      };
      var toDirectory = function(_container) {
        return map$12(detail.data.menus, function(data, _menuName) {
          return bind$3(data.items, function(item2) {
            return item2.type === "separator" ? [] : [item2.data.value];
          });
        });
      };
      var setActiveMenu = function(container, menu2) {
        Highlighting.highlight(container, menu2);
        Highlighting.getHighlighted(menu2).orThunk(function() {
          return Highlighting.getFirst(menu2);
        }).each(function(item2) {
          dispatch2(container, item2.element, focusItem());
        });
      };
      var getMenus2 = function(state, menuValues) {
        return cat(map$2(menuValues, function(mv) {
          return state.lookupMenu(mv).bind(function(prep) {
            return prep.type === "prepared" ? Optional.some(prep.menu) : Optional.none();
          });
        }));
      };
      var closeOthers = function(container, state, path2) {
        var others = getMenus2(state, state.otherMenus(path2));
        each$1(others, function(o2) {
          remove$1(o2.element, [detail.markers.backgroundMenu]);
          if (!detail.stayInDom) {
            Replacing.remove(container, o2);
          }
        });
      };
      var getSubmenuParents = function(container) {
        return submenuParentItems.get().getOrThunk(function() {
          var r3 = {};
          var items = descendants(container.element, "." + detail.markers.item);
          var parentItems = filter$2(items, function(i2) {
            return get$d(i2, "aria-haspopup") === "true";
          });
          each$1(parentItems, function(i2) {
            container.getSystem().getByDom(i2).each(function(itemComp) {
              var key = getItemValue(itemComp);
              r3[key] = itemComp;
            });
          });
          submenuParentItems.set(r3);
          return r3;
        });
      };
      var updateAriaExpansions = function(container, path2) {
        var parentItems = getSubmenuParents(container);
        each2(parentItems, function(v2, k2) {
          var expanded = contains$2(path2, k2);
          set$8(v2.element, "aria-expanded", expanded);
        });
      };
      var updateMenuPath = function(container, state, path2) {
        return Optional.from(path2[0]).bind(function(latestMenuName) {
          return state.lookupMenu(latestMenuName).bind(function(menuPrep) {
            if (menuPrep.type === "notbuilt") {
              return Optional.none();
            } else {
              var activeMenu = menuPrep.menu;
              var rest = getMenus2(state, path2.slice(1));
              each$1(rest, function(r3) {
                add$2(r3.element, detail.markers.backgroundMenu);
              });
              if (!inBody(activeMenu.element)) {
                Replacing.append(container, premade(activeMenu));
              }
              remove$1(activeMenu.element, [detail.markers.backgroundMenu]);
              setActiveMenu(container, activeMenu);
              closeOthers(container, state, path2);
              return Optional.some(activeMenu);
            }
          });
        });
      };
      var ExpandHighlightDecision;
      (function(ExpandHighlightDecision2) {
        ExpandHighlightDecision2[ExpandHighlightDecision2["HighlightSubmenu"] = 0] = "HighlightSubmenu";
        ExpandHighlightDecision2[ExpandHighlightDecision2["HighlightParent"] = 1] = "HighlightParent";
      })(ExpandHighlightDecision || (ExpandHighlightDecision = {}));
      var buildIfRequired = function(container, menuName, menuPrep) {
        if (menuPrep.type === "notbuilt") {
          var menu2 = container.getSystem().build(menuPrep.nbMenu());
          layeredState.setMenuBuilt(menuName, menu2);
          return menu2;
        } else {
          return menuPrep.menu;
        }
      };
      var expandRight = function(container, item2, decision) {
        if (decision === void 0) {
          decision = ExpandHighlightDecision.HighlightSubmenu;
        }
        if (item2.hasConfigured(Disabling) && Disabling.isDisabled(item2)) {
          return Optional.some(item2);
        } else {
          var value2 = getItemValue(item2);
          return layeredState.expand(value2).bind(function(path2) {
            updateAriaExpansions(container, path2);
            return Optional.from(path2[0]).bind(function(menuName) {
              return layeredState.lookupMenu(menuName).bind(function(activeMenuPrep) {
                var activeMenu = buildIfRequired(container, menuName, activeMenuPrep);
                if (!inBody(activeMenu.element)) {
                  Replacing.append(container, premade(activeMenu));
                }
                detail.onOpenSubmenu(container, item2, activeMenu, reverse(path2));
                if (decision === ExpandHighlightDecision.HighlightSubmenu) {
                  Highlighting.highlightFirst(activeMenu);
                  return updateMenuPath(container, layeredState, path2);
                } else {
                  Highlighting.dehighlightAll(activeMenu);
                  return Optional.some(item2);
                }
              });
            });
          });
        }
      };
      var collapseLeft = function(container, item2) {
        var value2 = getItemValue(item2);
        return layeredState.collapse(value2).bind(function(path2) {
          updateAriaExpansions(container, path2);
          return updateMenuPath(container, layeredState, path2).map(function(activeMenu) {
            detail.onCollapseMenu(container, item2, activeMenu);
            return activeMenu;
          });
        });
      };
      var updateView = function(container, item2) {
        var value2 = getItemValue(item2);
        return layeredState.refresh(value2).bind(function(path2) {
          updateAriaExpansions(container, path2);
          return updateMenuPath(container, layeredState, path2);
        });
      };
      var onRight2 = function(container, item2) {
        return inside(item2.element) ? Optional.none() : expandRight(container, item2, ExpandHighlightDecision.HighlightSubmenu);
      };
      var onLeft2 = function(container, item2) {
        return inside(item2.element) ? Optional.none() : collapseLeft(container, item2);
      };
      var onEscape = function(container, item2) {
        return collapseLeft(container, item2).orThunk(function() {
          return detail.onEscape(container, item2).map(function() {
            return container;
          });
        });
      };
      var keyOnItem = function(f2) {
        return function(container, simulatedEvent) {
          return closest$1(simulatedEvent.getSource(), "." + detail.markers.item).bind(function(target) {
            return container.getSystem().getByDom(target).toOptional().bind(function(item2) {
              return f2(container, item2).map(always);
            });
          });
        };
      };
      var events2 = derive$2([
        run$1(focus(), function(sandbox, simulatedEvent) {
          var item2 = simulatedEvent.event.item;
          layeredState.lookupItem(getItemValue(item2)).each(function() {
            var menu2 = simulatedEvent.event.menu;
            Highlighting.highlight(sandbox, menu2);
            var value2 = getItemValue(simulatedEvent.event.item);
            layeredState.refresh(value2).each(function(path2) {
              return closeOthers(sandbox, layeredState, path2);
            });
          });
        }),
        runOnExecute$1(function(component, simulatedEvent) {
          var target = simulatedEvent.event.target;
          component.getSystem().getByDom(target).each(function(item2) {
            var itemValue = getItemValue(item2);
            if (itemValue.indexOf("collapse-item") === 0) {
              collapseLeft(component, item2);
            }
            expandRight(component, item2, ExpandHighlightDecision.HighlightSubmenu).fold(function() {
              detail.onExecute(component, item2);
            }, noop3);
          });
        }),
        runOnAttached(function(container, _simulatedEvent) {
          setup2(container).each(function(primary) {
            Replacing.append(container, premade(primary));
            detail.onOpenMenu(container, primary);
            if (detail.highlightImmediately) {
              setActiveMenu(container, primary);
            }
          });
        })
      ].concat(detail.navigateOnHover ? [run$1(hover(), function(sandbox, simulatedEvent) {
        var item2 = simulatedEvent.event.item;
        updateView(sandbox, item2);
        expandRight(sandbox, item2, ExpandHighlightDecision.HighlightParent);
        detail.onHover(sandbox, item2);
      })] : []));
      var getActiveItem = function(container) {
        return Highlighting.getHighlighted(container).bind(Highlighting.getHighlighted);
      };
      var collapseMenuApi = function(container) {
        getActiveItem(container).each(function(currentItem) {
          collapseLeft(container, currentItem);
        });
      };
      var highlightPrimary = function(container) {
        layeredState.getPrimary().each(function(primary) {
          setActiveMenu(container, primary);
        });
      };
      var extractMenuFromContainer = function(container) {
        return Optional.from(container.components()[0]).filter(function(comp) {
          return get$d(comp.element, "role") === "menu";
        });
      };
      var repositionMenus2 = function(container) {
        var maybeActivePrimary = layeredState.getPrimary().bind(function(primary) {
          return getActiveItem(container).bind(function(currentItem) {
            var itemValue = getItemValue(currentItem);
            var allMenus = values(layeredState.getMenus());
            var preparedMenus = cat(map$2(allMenus, LayeredState.extractPreparedMenu));
            return layeredState.getTriggeringPath(itemValue, function(v2) {
              return getItemByValue(container, preparedMenus, v2);
            });
          }).map(function(triggeringPath) {
            return {
              primary,
              triggeringPath
            };
          });
        });
        maybeActivePrimary.fold(function() {
          extractMenuFromContainer(container).each(function(primaryMenu) {
            detail.onRepositionMenu(container, primaryMenu, []);
          });
        }, function(_a2) {
          var primary = _a2.primary, triggeringPath = _a2.triggeringPath;
          detail.onRepositionMenu(container, primary, triggeringPath);
        });
      };
      var apis = {
        collapseMenu: collapseMenuApi,
        highlightPrimary,
        repositionMenus: repositionMenus2
      };
      return {
        uid: detail.uid,
        dom: detail.dom,
        markers: detail.markers,
        behaviours: augment(detail.tmenuBehaviours, [
          Keying.config({
            mode: "special",
            onRight: keyOnItem(onRight2),
            onLeft: keyOnItem(onLeft2),
            onEscape: keyOnItem(onEscape),
            focusIn: function(container, _keyInfo) {
              layeredState.getPrimary().each(function(primary) {
                dispatch2(container, primary.element, focusItem());
              });
            }
          }),
          Highlighting.config({
            highlightClass: detail.markers.selectedMenu,
            itemClass: detail.markers.menu
          }),
          Composing.config({
            find: function(container) {
              return Highlighting.getHighlighted(container);
            }
          }),
          Replacing.config({})
        ]),
        eventOrder: detail.eventOrder,
        apis,
        events: events2
      };
    };
    var collapseItem$1 = constant$1("collapse-item");
    var tieredData = function(primary, menus, expansions) {
      return {
        primary,
        menus,
        expansions
      };
    };
    var singleData = function(name2, menu2) {
      return {
        primary: name2,
        menus: wrap$1(name2, menu2),
        expansions: {}
      };
    };
    var collapseItem = function(text2) {
      return {
        value: generate$6(collapseItem$1()),
        meta: { text: text2 }
      };
    };
    var tieredMenu = single({
      name: "TieredMenu",
      configFields: [
        onStrictKeyboardHandler("onExecute"),
        onStrictKeyboardHandler("onEscape"),
        onStrictHandler("onOpenMenu"),
        onStrictHandler("onOpenSubmenu"),
        onHandler("onRepositionMenu"),
        onHandler("onCollapseMenu"),
        defaulted("highlightImmediately", true),
        requiredObjOf("data", [
          required$1("primary"),
          required$1("menus"),
          required$1("expansions")
        ]),
        defaulted("fakeFocus", false),
        onHandler("onHighlight"),
        onHandler("onHover"),
        tieredMenuMarkers(),
        required$1("dom"),
        defaulted("navigateOnHover", true),
        defaulted("stayInDom", false),
        field("tmenuBehaviours", [
          Keying,
          Highlighting,
          Composing,
          Replacing
        ]),
        defaulted("eventOrder", {})
      ],
      apis: {
        collapseMenu: function(apis, tmenu) {
          apis.collapseMenu(tmenu);
        },
        highlightPrimary: function(apis, tmenu) {
          apis.highlightPrimary(tmenu);
        },
        repositionMenus: function(apis, tmenu) {
          apis.repositionMenus(tmenu);
        }
      },
      factory: make$6,
      extraApis: {
        tieredData,
        singleData,
        collapseItem
      }
    });
    var makeMenu = function(detail, menuSandbox, placementSpec, menuSpec, getBounds3) {
      var lazySink = function() {
        return detail.lazySink(menuSandbox);
      };
      var layouts3 = menuSpec.type === "horizontal" ? {
        layouts: {
          onLtr: function() {
            return belowOrAbove();
          },
          onRtl: function() {
            return belowOrAboveRtl();
          }
        }
      } : {};
      var isFirstTierSubmenu = function(triggeringPaths) {
        return triggeringPaths.length === 2;
      };
      var getSubmenuLayouts = function(triggeringPaths) {
        return isFirstTierSubmenu(triggeringPaths) ? layouts3 : {};
      };
      return tieredMenu.sketch({
        dom: { tag: "div" },
        data: menuSpec.data,
        markers: menuSpec.menu.markers,
        highlightImmediately: menuSpec.menu.highlightImmediately,
        onEscape: function() {
          Sandboxing.close(menuSandbox);
          detail.onEscape.map(function(handler) {
            return handler(menuSandbox);
          });
          return Optional.some(true);
        },
        onExecute: function() {
          return Optional.some(true);
        },
        onOpenMenu: function(tmenu, menu2) {
          Positioning.positionWithinBounds(lazySink().getOrDie(), menu2, placementSpec, getBounds3());
        },
        onOpenSubmenu: function(tmenu, item2, submenu, triggeringPaths) {
          var sink = lazySink().getOrDie();
          Positioning.position(sink, submenu, {
            anchor: __assign({
              type: "submenu",
              item: item2
            }, getSubmenuLayouts(triggeringPaths))
          });
        },
        onRepositionMenu: function(tmenu, primaryMenu, submenuTriggers) {
          var sink = lazySink().getOrDie();
          Positioning.positionWithinBounds(sink, primaryMenu, placementSpec, getBounds3());
          each$1(submenuTriggers, function(st2) {
            var submenuLayouts = getSubmenuLayouts(st2.triggeringPath);
            Positioning.position(sink, st2.triggeredMenu, {
              anchor: __assign({
                type: "submenu",
                item: st2.triggeringItem
              }, submenuLayouts)
            });
          });
        }
      });
    };
    var factory$m = function(detail, spec) {
      var isPartOfRelated = function(sandbox, queryElem) {
        var related = detail.getRelated(sandbox);
        return related.exists(function(rel) {
          return isPartOf$1(rel, queryElem);
        });
      };
      var setContent2 = function(sandbox, thing) {
        Sandboxing.setContent(sandbox, thing);
      };
      var showAt = function(sandbox, thing, placementSpec) {
        showWithin(sandbox, thing, placementSpec, Optional.none());
      };
      var showWithin = function(sandbox, thing, placementSpec, boxElement) {
        showWithinBounds(sandbox, thing, placementSpec, function() {
          return boxElement.map(function(elem) {
            return box$1(elem);
          });
        });
      };
      var showWithinBounds = function(sandbox, thing, placementSpec, getBounds3) {
        var sink = detail.lazySink(sandbox).getOrDie();
        Sandboxing.openWhileCloaked(sandbox, thing, function() {
          return Positioning.positionWithinBounds(sink, sandbox, placementSpec, getBounds3());
        });
        Representing.setValue(sandbox, Optional.some({
          mode: "position",
          config: placementSpec,
          getBounds: getBounds3
        }));
      };
      var showMenuAt = function(sandbox, placementSpec, menuSpec) {
        showMenuWithinBounds(sandbox, placementSpec, menuSpec, Optional.none);
      };
      var showMenuWithinBounds = function(sandbox, placementSpec, menuSpec, getBounds3) {
        var menu2 = makeMenu(detail, sandbox, placementSpec, menuSpec, getBounds3);
        Sandboxing.open(sandbox, menu2);
        Representing.setValue(sandbox, Optional.some({
          mode: "menu",
          menu: menu2
        }));
      };
      var hide2 = function(sandbox) {
        if (Sandboxing.isOpen(sandbox)) {
          Representing.setValue(sandbox, Optional.none());
          Sandboxing.close(sandbox);
        }
      };
      var getContent = function(sandbox) {
        return Sandboxing.getState(sandbox);
      };
      var reposition2 = function(sandbox) {
        if (Sandboxing.isOpen(sandbox)) {
          Representing.getValue(sandbox).each(function(state) {
            switch (state.mode) {
              case "menu":
                Sandboxing.getState(sandbox).each(tieredMenu.repositionMenus);
                break;
              case "position":
                var sink = detail.lazySink(sandbox).getOrDie();
                Positioning.positionWithinBounds(sink, sandbox, state.config, state.getBounds());
                break;
            }
          });
        }
      };
      var apis = {
        setContent: setContent2,
        showAt,
        showWithin,
        showWithinBounds,
        showMenuAt,
        showMenuWithinBounds,
        hide: hide2,
        getContent,
        reposition: reposition2,
        isOpen: Sandboxing.isOpen
      };
      return {
        uid: detail.uid,
        dom: detail.dom,
        behaviours: augment(detail.inlineBehaviours, [
          Sandboxing.config({
            isPartOf: function(sandbox, data, queryElem) {
              return isPartOf$1(data, queryElem) || isPartOfRelated(sandbox, queryElem);
            },
            getAttachPoint: function(sandbox) {
              return detail.lazySink(sandbox).getOrDie();
            },
            onOpen: function(sandbox) {
              detail.onShow(sandbox);
            },
            onClose: function(sandbox) {
              detail.onHide(sandbox);
            }
          }),
          Representing.config({
            store: {
              mode: "memory",
              initialValue: Optional.none()
            }
          }),
          Receiving.config({
            channels: __assign(__assign({}, receivingChannel$1(__assign({ isExtraPart: spec.isExtraPart }, detail.fireDismissalEventInstead.map(function(fe2) {
              return { fireEventInstead: { event: fe2.event } };
            }).getOr({})))), receivingChannel(__assign(__assign({}, detail.fireRepositionEventInstead.map(function(fe2) {
              return { fireEventInstead: { event: fe2.event } };
            }).getOr({})), { doReposition: reposition2 })))
          })
        ]),
        eventOrder: detail.eventOrder,
        apis
      };
    };
    var InlineView = single({
      name: "InlineView",
      configFields: [
        required$1("lazySink"),
        onHandler("onShow"),
        onHandler("onHide"),
        optionFunction("onEscape"),
        field("inlineBehaviours", [
          Sandboxing,
          Representing,
          Receiving
        ]),
        optionObjOf("fireDismissalEventInstead", [defaulted("event", dismissRequested())]),
        optionObjOf("fireRepositionEventInstead", [defaulted("event", repositionRequested())]),
        defaulted("getRelated", Optional.none),
        defaulted("isExtraPart", never),
        defaulted("eventOrder", Optional.none)
      ],
      factory: factory$m,
      apis: {
        showAt: function(apis, component, anchor2, thing) {
          apis.showAt(component, anchor2, thing);
        },
        showWithin: function(apis, component, anchor2, thing, boxElement) {
          apis.showWithin(component, anchor2, thing, boxElement);
        },
        showWithinBounds: function(apis, component, anchor2, thing, bounds2) {
          apis.showWithinBounds(component, anchor2, thing, bounds2);
        },
        showMenuAt: function(apis, component, anchor2, menuSpec) {
          apis.showMenuAt(component, anchor2, menuSpec);
        },
        showMenuWithinBounds: function(apis, component, anchor2, menuSpec, bounds2) {
          apis.showMenuWithinBounds(component, anchor2, menuSpec, bounds2);
        },
        hide: function(apis, component) {
          apis.hide(component);
        },
        isOpen: function(apis, component) {
          return apis.isOpen(component);
        },
        getContent: function(apis, component) {
          return apis.getContent(component);
        },
        setContent: function(apis, component, thing) {
          apis.setContent(component, thing);
        },
        reposition: function(apis, component) {
          apis.reposition(component);
        }
      }
    });
    var labelPrefix = "layout-inset";
    var westEdgeX = function(anchor2) {
      return anchor2.x;
    };
    var middleX = function(anchor2, element2) {
      return anchor2.x + anchor2.width / 2 - element2.width / 2;
    };
    var eastEdgeX = function(anchor2, element2) {
      return anchor2.x + anchor2.width - element2.width;
    };
    var northY = function(anchor2) {
      return anchor2.y;
    };
    var southY = function(anchor2, element2) {
      return anchor2.y + anchor2.height - element2.height;
    };
    var centreY = function(anchor2, element2) {
      return anchor2.y + anchor2.height / 2 - element2.height / 2;
    };
    var southwest = function(anchor2, element2, bubbles) {
      return nu$6(eastEdgeX(anchor2, element2), southY(anchor2, element2), bubbles.insetSouthwest(), northwest$3(), "southwest", boundsRestriction(anchor2, {
        right: 0,
        bottom: 3
      }), labelPrefix);
    };
    var southeast = function(anchor2, element2, bubbles) {
      return nu$6(westEdgeX(anchor2), southY(anchor2, element2), bubbles.insetSoutheast(), northeast$3(), "southeast", boundsRestriction(anchor2, {
        left: 1,
        bottom: 3
      }), labelPrefix);
    };
    var northwest = function(anchor2, element2, bubbles) {
      return nu$6(eastEdgeX(anchor2, element2), northY(anchor2), bubbles.insetNorthwest(), southwest$3(), "northwest", boundsRestriction(anchor2, {
        right: 0,
        top: 2
      }), labelPrefix);
    };
    var northeast = function(anchor2, element2, bubbles) {
      return nu$6(westEdgeX(anchor2), northY(anchor2), bubbles.insetNortheast(), southeast$3(), "northeast", boundsRestriction(anchor2, {
        left: 1,
        top: 2
      }), labelPrefix);
    };
    var north = function(anchor2, element2, bubbles) {
      return nu$6(middleX(anchor2, element2), northY(anchor2), bubbles.insetNorth(), south$3(), "north", boundsRestriction(anchor2, { top: 2 }), labelPrefix);
    };
    var south = function(anchor2, element2, bubbles) {
      return nu$6(middleX(anchor2, element2), southY(anchor2, element2), bubbles.insetSouth(), north$3(), "south", boundsRestriction(anchor2, { bottom: 3 }), labelPrefix);
    };
    var east = function(anchor2, element2, bubbles) {
      return nu$6(eastEdgeX(anchor2, element2), centreY(anchor2, element2), bubbles.insetEast(), west$3(), "east", boundsRestriction(anchor2, { right: 0 }), labelPrefix);
    };
    var west = function(anchor2, element2, bubbles) {
      return nu$6(westEdgeX(anchor2), centreY(anchor2, element2), bubbles.insetWest(), east$3(), "west", boundsRestriction(anchor2, { left: 1 }), labelPrefix);
    };
    var lookupPreserveLayout = function(lastPlacement) {
      switch (lastPlacement) {
        case "north":
          return north;
        case "northeast":
          return northeast;
        case "northwest":
          return northwest;
        case "south":
          return south;
        case "southeast":
          return southeast;
        case "southwest":
          return southwest;
        case "east":
          return east;
        case "west":
          return west;
      }
    };
    var preserve = function(anchor2, element2, bubbles, placee, bounds2) {
      var layout2 = getPlacement(placee).map(lookupPreserveLayout).getOr(north);
      return layout2(anchor2, element2, bubbles, placee, bounds2);
    };
    var lookupFlippedLayout = function(lastPlacement) {
      switch (lastPlacement) {
        case "north":
          return south;
        case "northeast":
          return southeast;
        case "northwest":
          return southwest;
        case "south":
          return north;
        case "southeast":
          return northeast;
        case "southwest":
          return northwest;
        case "east":
          return west;
        case "west":
          return east;
      }
    };
    var flip$2 = function(anchor2, element2, bubbles, placee, bounds2) {
      var layout2 = getPlacement(placee).map(lookupFlippedLayout).getOr(north);
      return layout2(anchor2, element2, bubbles, placee, bounds2);
    };
    var global$f = tinymce.util.Tools.resolve("tinymce.util.Delay");
    var factory$l = function(detail) {
      var events2 = events$a(detail.action);
      var tag = detail.dom.tag;
      var lookupAttr = function(attr) {
        return get$e(detail.dom, "attributes").bind(function(attrs) {
          return get$e(attrs, attr);
        });
      };
      var getModAttributes = function() {
        if (tag === "button") {
          var type2 = lookupAttr("type").getOr("button");
          var roleAttrs = lookupAttr("role").map(function(role2) {
            return { role: role2 };
          }).getOr({});
          return __assign({ type: type2 }, roleAttrs);
        } else {
          var role = lookupAttr("role").getOr("button");
          return { role };
        }
      };
      return {
        uid: detail.uid,
        dom: detail.dom,
        components: detail.components,
        events: events2,
        behaviours: SketchBehaviours.augment(detail.buttonBehaviours, [
          Focusing.config({}),
          Keying.config({
            mode: "execution",
            useSpace: true,
            useEnter: true
          })
        ]),
        domModification: { attributes: getModAttributes() },
        eventOrder: detail.eventOrder
      };
    };
    var Button2 = single({
      name: "Button",
      factory: factory$l,
      configFields: [
        defaulted("uid", void 0),
        required$1("dom"),
        defaulted("components", []),
        SketchBehaviours.field("buttonBehaviours", [
          Focusing,
          Keying
        ]),
        option("action"),
        option("role"),
        defaulted("eventOrder", {})
      ]
    });
    var record = function(spec) {
      var uid2 = isSketchSpec(spec) && hasNonNullableKey(spec, "uid") ? spec.uid : generate$5("memento");
      var get2 = function(anyInSystem) {
        return anyInSystem.getSystem().getByUid(uid2).getOrDie();
      };
      var getOpt2 = function(anyInSystem) {
        return anyInSystem.getSystem().getByUid(uid2).toOptional();
      };
      var asSpec = function() {
        return __assign(__assign({}, spec), { uid: uid2 });
      };
      return {
        get: get2,
        getOpt: getOpt2,
        asSpec
      };
    };
    var global$e = tinymce.util.Tools.resolve("tinymce.util.I18n");
    var rtlTransform = {
      "indent": true,
      "outdent": true,
      "table-insert-column-after": true,
      "table-insert-column-before": true,
      "paste-column-after": true,
      "paste-column-before": true,
      "unordered-list": true,
      "list-bull-circle": true,
      "list-bull-default": true,
      "list-bull-square": true
    };
    var defaultIconName = "temporary-placeholder";
    var defaultIcon = function(icons) {
      return function() {
        return get$e(icons, defaultIconName).getOr("!not found!");
      };
    };
    var getIconName = function(name2, icons) {
      var lcName = name2.toLowerCase();
      if (global$e.isRtl()) {
        var rtlName = ensureTrailing(lcName, "-rtl");
        return has$2(icons, rtlName) ? rtlName : lcName;
      } else {
        return lcName;
      }
    };
    var lookupIcon = function(name2, icons) {
      return get$e(icons, getIconName(name2, icons));
    };
    var get$1 = function(name2, iconProvider) {
      var icons = iconProvider();
      return lookupIcon(name2, icons).getOrThunk(defaultIcon(icons));
    };
    var getOr = function(name2, iconProvider, fallbackIcon) {
      var icons = iconProvider();
      return lookupIcon(name2, icons).or(fallbackIcon).getOrThunk(defaultIcon(icons));
    };
    var needsRtlTransform = function(iconName) {
      return global$e.isRtl() ? has$2(rtlTransform, iconName) : false;
    };
    var addFocusableBehaviour = function() {
      return config("add-focusable", [runOnAttached(function(comp) {
        child(comp.element, "svg").each(function(svg) {
          return set$8(svg, "focusable", "false");
        });
      })]);
    };
    var renderIcon$2 = function(spec, iconName, icons, fallbackIcon) {
      var _a2, _b;
      var rtlIconClasses = needsRtlTransform(iconName) ? ["tox-icon--flip"] : [];
      var iconHtml = get$e(icons, getIconName(iconName, icons)).or(fallbackIcon).getOrThunk(defaultIcon(icons));
      return {
        dom: {
          tag: spec.tag,
          attributes: (_a2 = spec.attributes) !== null && _a2 !== void 0 ? _a2 : {},
          classes: spec.classes.concat(rtlIconClasses),
          innerHtml: iconHtml
        },
        behaviours: derive$1(__spreadArray(__spreadArray([], (_b = spec.behaviours) !== null && _b !== void 0 ? _b : [], true), [addFocusableBehaviour()], false))
      };
    };
    var render$3 = function(iconName, spec, iconProvider, fallbackIcon) {
      if (fallbackIcon === void 0) {
        fallbackIcon = Optional.none();
      }
      return renderIcon$2(spec, iconName, iconProvider(), fallbackIcon);
    };
    var renderFirst = function(iconNames, spec, iconProvider) {
      var icons = iconProvider();
      var iconName = find$5(iconNames, function(name2) {
        return has$2(icons, getIconName(name2, icons));
      });
      return renderIcon$2(spec, iconName.getOr(defaultIconName), icons, Optional.none());
    };
    var notificationIconMap = {
      success: "checkmark",
      error: "warning",
      err: "error",
      warning: "warning",
      warn: "warning",
      info: "info"
    };
    var factory$k = function(detail) {
      var memBannerText = record({
        dom: {
          tag: "p",
          innerHtml: detail.translationProvider(detail.text)
        },
        behaviours: derive$1([Replacing.config({})])
      });
      var renderPercentBar = function(percent) {
        return {
          dom: {
            tag: "div",
            classes: ["tox-bar"],
            attributes: { style: "width: " + percent + "%" }
          }
        };
      };
      var renderPercentText = function(percent) {
        return {
          dom: {
            tag: "div",
            classes: ["tox-text"],
            innerHtml: percent + "%"
          }
        };
      };
      var memBannerProgress = record({
        dom: {
          tag: "div",
          classes: detail.progress ? [
            "tox-progress-bar",
            "tox-progress-indicator"
          ] : ["tox-progress-bar"]
        },
        components: [
          {
            dom: {
              tag: "div",
              classes: ["tox-bar-container"]
            },
            components: [renderPercentBar(0)]
          },
          renderPercentText(0)
        ],
        behaviours: derive$1([Replacing.config({})])
      });
      var updateProgress = function(comp, percent) {
        if (comp.getSystem().isConnected()) {
          memBannerProgress.getOpt(comp).each(function(progress) {
            Replacing.set(progress, [
              {
                dom: {
                  tag: "div",
                  classes: ["tox-bar-container"]
                },
                components: [renderPercentBar(percent)]
              },
              renderPercentText(percent)
            ]);
          });
        }
      };
      var updateText = function(comp, text$1) {
        if (comp.getSystem().isConnected()) {
          var banner = memBannerText.get(comp);
          Replacing.set(banner, [text(text$1)]);
        }
      };
      var apis = {
        updateProgress,
        updateText
      };
      var iconChoices = flatten([
        detail.icon.toArray(),
        detail.level.toArray(),
        detail.level.bind(function(level) {
          return Optional.from(notificationIconMap[level]);
        }).toArray()
      ]);
      var memButton = record(Button2.sketch({
        dom: {
          tag: "button",
          classes: [
            "tox-notification__dismiss",
            "tox-button",
            "tox-button--naked",
            "tox-button--icon"
          ]
        },
        components: [render$3("close", {
          tag: "div",
          classes: ["tox-icon"],
          attributes: { "aria-label": detail.translationProvider("Close") }
        }, detail.iconProvider)],
        action: function(comp) {
          detail.onAction(comp);
        }
      }));
      var notificationIconSpec = renderFirst(iconChoices, {
        tag: "div",
        classes: ["tox-notification__icon"]
      }, detail.iconProvider);
      var notificationBodySpec = {
        dom: {
          tag: "div",
          classes: ["tox-notification__body"]
        },
        components: [memBannerText.asSpec()],
        behaviours: derive$1([Replacing.config({})])
      };
      var components2 = [
        notificationIconSpec,
        notificationBodySpec
      ];
      return {
        uid: detail.uid,
        dom: {
          tag: "div",
          attributes: { role: "alert" },
          classes: detail.level.map(function(level) {
            return [
              "tox-notification",
              "tox-notification--in",
              "tox-notification--" + level
            ];
          }).getOr([
            "tox-notification",
            "tox-notification--in"
          ])
        },
        behaviours: derive$1([
          Focusing.config({}),
          config("notification-events", [run$1(focusin(), function(comp) {
            memButton.getOpt(comp).each(Focusing.focus);
          })])
        ]),
        components: components2.concat(detail.progress ? [memBannerProgress.asSpec()] : []).concat(!detail.closeButton ? [] : [memButton.asSpec()]),
        apis
      };
    };
    var Notification = single({
      name: "Notification",
      factory: factory$k,
      configFields: [
        option("level"),
        required$1("progress"),
        required$1("icon"),
        required$1("onAction"),
        required$1("text"),
        required$1("iconProvider"),
        required$1("translationProvider"),
        defaultedBoolean("closeButton", true)
      ],
      apis: {
        updateProgress: function(apis, comp, percent) {
          apis.updateProgress(comp, percent);
        },
        updateText: function(apis, comp, text2) {
          apis.updateText(comp, text2);
        }
      }
    });
    function NotificationManagerImpl(editor, extras, uiMothership) {
      var sharedBackstage = extras.backstage.shared;
      var getLayoutDirection = function(rel) {
        switch (rel) {
          case "bc-bc":
            return south;
          case "tc-tc":
            return north;
          case "tc-bc":
            return north$2;
          case "bc-tc":
          default:
            return south$2;
        }
      };
      var reposition2 = function(notifications) {
        if (notifications.length > 0) {
          each$1(notifications, function(notification, index) {
            if (index === 0) {
              notification.moveRel(null, "banner");
            } else {
              notification.moveRel(notifications[index - 1].getEl(), "bc-tc");
            }
          });
        }
      };
      var open2 = function(settings, closeCallback) {
        var hideCloseButton = !settings.closeButton && settings.timeout && (settings.timeout > 0 || settings.timeout < 0);
        var close3 = function() {
          closeCallback();
          InlineView.hide(notificationWrapper);
        };
        var notification = build$1(Notification.sketch({
          text: settings.text,
          level: contains$2([
            "success",
            "error",
            "warning",
            "warn",
            "info"
          ], settings.type) ? settings.type : void 0,
          progress: settings.progressBar === true,
          icon: Optional.from(settings.icon),
          closeButton: !hideCloseButton,
          onAction: close3,
          iconProvider: sharedBackstage.providers.icons,
          translationProvider: sharedBackstage.providers.translate
        }));
        var notificationWrapper = build$1(InlineView.sketch(__assign({
          dom: {
            tag: "div",
            classes: ["tox-notifications-container"]
          },
          lazySink: sharedBackstage.getSink,
          fireDismissalEventInstead: {}
        }, sharedBackstage.header.isPositionedAtTop() ? {} : { fireRepositionEventInstead: {} })));
        uiMothership.add(notificationWrapper);
        if (settings.timeout > 0) {
          global$f.setTimeout(function() {
            close3();
          }, settings.timeout);
        }
        var getBounds3 = function() {
          var contentArea = box$1(SugarElement.fromDom(editor.getContentAreaContainer()));
          var win$1 = win();
          var x2 = clamp$1(win$1.x, contentArea.x, contentArea.right);
          var y2 = clamp$1(win$1.y, contentArea.y, contentArea.bottom);
          var right3 = Math.max(contentArea.right, win$1.right);
          var bottom3 = Math.max(contentArea.bottom, win$1.bottom);
          return Optional.some(bounds(x2, y2, right3 - x2, bottom3 - y2));
        };
        return {
          close: close3,
          moveTo: function(x2, y2) {
            InlineView.showAt(notificationWrapper, premade(notification), {
              anchor: {
                type: "makeshift",
                x: x2,
                y: y2
              }
            });
          },
          moveRel: function(element2, rel) {
            var notificationSpec = premade(notification);
            var anchorOverrides2 = { maxHeightFunction: expandable$1() };
            if (rel !== "banner" && isNonNullable(element2)) {
              var layoutDirection_1 = getLayoutDirection(rel);
              var nodeAnchor = {
                type: "node",
                root: body(),
                node: Optional.some(SugarElement.fromDom(element2)),
                overrides: anchorOverrides2,
                layouts: {
                  onRtl: function() {
                    return [layoutDirection_1];
                  },
                  onLtr: function() {
                    return [layoutDirection_1];
                  }
                }
              };
              InlineView.showWithinBounds(notificationWrapper, notificationSpec, { anchor: nodeAnchor }, getBounds3);
            } else {
              var anchor2 = __assign(__assign({}, sharedBackstage.anchors.banner()), { overrides: anchorOverrides2 });
              InlineView.showWithinBounds(notificationWrapper, notificationSpec, { anchor: anchor2 }, getBounds3);
            }
          },
          text: function(nuText) {
            Notification.updateText(notification, nuText);
          },
          settings,
          getEl: function() {
            return notification.element.dom;
          },
          progressBar: {
            value: function(percent) {
              Notification.updateProgress(notification, percent);
            }
          }
        };
      };
      var close2 = function(notification) {
        notification.close();
      };
      var getArgs = function(notification) {
        return notification.settings;
      };
      return {
        open: open2,
        close: close2,
        reposition: reposition2,
        getArgs
      };
    }
    var first = function(fn3, rate) {
      var timer = null;
      var cancel = function() {
        if (!isNull(timer)) {
          clearTimeout(timer);
          timer = null;
        }
      };
      var throttle2 = function() {
        var args = [];
        for (var _i2 = 0; _i2 < arguments.length; _i2++) {
          args[_i2] = arguments[_i2];
        }
        if (isNull(timer)) {
          timer = setTimeout(function() {
            timer = null;
            fn3.apply(null, args);
          }, rate);
        }
      };
      return {
        cancel,
        throttle: throttle2
      };
    };
    var last = function(fn3, rate) {
      var timer = null;
      var cancel = function() {
        if (!isNull(timer)) {
          clearTimeout(timer);
          timer = null;
        }
      };
      var throttle2 = function() {
        var args = [];
        for (var _i2 = 0; _i2 < arguments.length; _i2++) {
          args[_i2] = arguments[_i2];
        }
        cancel();
        timer = setTimeout(function() {
          timer = null;
          fn3.apply(null, args);
        }, rate);
      };
      return {
        cancel,
        throttle: throttle2
      };
    };
    var global$d = tinymce.util.Tools.resolve("tinymce.dom.TextSeeker");
    var isBoundary = function(dom2, node) {
      return dom2.isBlock(node) || contains$2([
        "BR",
        "IMG",
        "HR",
        "INPUT"
      ], node.nodeName) || dom2.getContentEditable(node) === "false";
    };
    var repeatLeft = function(dom2, node, offset3, process3, rootNode) {
      var search2 = global$d(dom2, function(node2) {
        return isBoundary(dom2, node2);
      });
      return Optional.from(search2.backwards(node, offset3, process3, rootNode));
    };
    var autocompleteSelector = "[data-mce-autocompleter]";
    var create$4 = function(editor, range2) {
      return detect(SugarElement.fromDom(editor.selection.getNode())).getOrThunk(function() {
        var wrapper = SugarElement.fromHtml('<span data-mce-autocompleter="1" data-mce-bogus="1"></span>', editor.getDoc());
        append$2(wrapper, SugarElement.fromDom(range2.extractContents()));
        range2.insertNode(wrapper.dom);
        parent(wrapper).each(function(elm) {
          return elm.dom.normalize();
        });
        last$1(wrapper).map(function(last2) {
          editor.selection.setCursorLocation(last2.dom, getEnd(last2));
        });
        return wrapper;
      });
    };
    var detect = function(elm) {
      return closest$1(elm, autocompleteSelector);
    };
    var isValidTextRange = function(rng) {
      return rng.collapsed && rng.startContainer.nodeType === 3;
    };
    var getText = function(rng) {
      return rng.toString().replace(/\u00A0/g, " ").replace(/\uFEFF/g, "");
    };
    var isWhitespace = function(chr) {
      return chr !== "" && " \xA0\f\n\r	\v".indexOf(chr) !== -1;
    };
    var stripTriggerChar = function(text2, triggerCh) {
      return text2.substring(triggerCh.length);
    };
    var findChar = function(text2, index, ch) {
      var i2;
      for (i2 = index - 1; i2 >= 0; i2--) {
        var char = text2.charAt(i2);
        if (isWhitespace(char)) {
          return Optional.none();
        }
        if (char === ch) {
          break;
        }
      }
      return Optional.some(i2);
    };
    var findStart = function(dom2, initRange, ch, minChars) {
      if (minChars === void 0) {
        minChars = 0;
      }
      if (!isValidTextRange(initRange)) {
        return Optional.none();
      }
      var findTriggerChIndex = function(element2, offset3, text2) {
        return findChar(text2, offset3, ch).getOr(offset3);
      };
      var root = dom2.getParent(initRange.startContainer, dom2.isBlock) || dom2.getRoot();
      return repeatLeft(dom2, initRange.startContainer, initRange.startOffset, findTriggerChIndex, root).bind(function(spot2) {
        var range2 = initRange.cloneRange();
        range2.setStart(spot2.container, spot2.offset);
        range2.setEnd(initRange.endContainer, initRange.endOffset);
        if (range2.collapsed) {
          return Optional.none();
        }
        var text2 = getText(range2);
        var triggerCharIndex = text2.lastIndexOf(ch);
        if (triggerCharIndex !== 0 || stripTriggerChar(text2, ch).length < minChars) {
          return Optional.none();
        } else {
          return Optional.some({
            text: stripTriggerChar(text2, ch),
            range: range2,
            triggerChar: ch
          });
        }
      });
    };
    var getContext = function(dom2, initRange, ch, minChars) {
      if (minChars === void 0) {
        minChars = 0;
      }
      return detect(SugarElement.fromDom(initRange.startContainer)).fold(function() {
        return findStart(dom2, initRange, ch, minChars);
      }, function(elm) {
        var range2 = dom2.createRng();
        range2.selectNode(elm.dom);
        var text2 = getText(range2);
        return Optional.some({
          range: range2,
          text: stripTriggerChar(text2, ch),
          triggerChar: ch
        });
      });
    };
    var setup$e = function(api2, editor) {
      editor.on("keypress compositionend", api2.onKeypress.throttle);
      editor.on("remove", api2.onKeypress.cancel);
      var redirectKeyToItem = function(item2, e2) {
        emitWith(item2, keydown(), { raw: e2 });
      };
      editor.on("keydown", function(e2) {
        var getItem = function() {
          return api2.getView().bind(Highlighting.getHighlighted);
        };
        if (e2.which === 8) {
          api2.onKeypress.throttle(e2);
        }
        if (api2.isActive()) {
          if (e2.which === 27) {
            api2.cancelIfNecessary();
          }
          if (api2.isMenuOpen()) {
            if (e2.which === 13) {
              getItem().each(emitExecute);
              e2.preventDefault();
            } else if (e2.which === 40) {
              getItem().fold(function() {
                api2.getView().each(Highlighting.highlightFirst);
              }, function(item2) {
                redirectKeyToItem(item2, e2);
              });
              e2.preventDefault();
              e2.stopImmediatePropagation();
            } else if (e2.which === 37 || e2.which === 38 || e2.which === 39) {
              getItem().each(function(item2) {
                redirectKeyToItem(item2, e2);
                e2.preventDefault();
                e2.stopImmediatePropagation();
              });
            }
          } else {
            if (e2.which === 13 || e2.which === 38 || e2.which === 40) {
              api2.cancelIfNecessary();
            }
          }
        }
      });
      editor.on("NodeChange", function(e2) {
        if (api2.isActive() && !api2.isProcessingAction() && detect(SugarElement.fromDom(e2.element)).isNone()) {
          api2.cancelIfNecessary();
        }
      });
    };
    var AutocompleterEditorEvents = { setup: setup$e };
    var global$c = tinymce.util.Tools.resolve("tinymce.util.Promise");
    var point = function(container, offset3) {
      return {
        container,
        offset: offset3
      };
    };
    var isText = function(node) {
      return node.nodeType === TEXT;
    };
    var isElement$1 = function(node) {
      return node.nodeType === ELEMENT;
    };
    var toLast = function(node) {
      if (isText(node)) {
        return point(node, node.data.length);
      } else {
        var children2 = node.childNodes;
        return children2.length > 0 ? toLast(children2[children2.length - 1]) : point(node, children2.length);
      }
    };
    var toLeaf = function(node, offset3) {
      var children2 = node.childNodes;
      if (children2.length > 0 && offset3 < children2.length) {
        return toLeaf(children2[offset3], 0);
      } else if (children2.length > 0 && isElement$1(node) && children2.length === offset3) {
        return toLast(children2[children2.length - 1]);
      } else {
        return point(node, offset3);
      }
    };
    var isPreviousCharContent = function(dom2, leaf2) {
      return repeatLeft(dom2, leaf2.container, leaf2.offset, function(element2, offset3) {
        return offset3 === 0 ? -1 : offset3;
      }, dom2.getRoot()).filter(function(spot2) {
        var char = spot2.container.data.charAt(spot2.offset - 1);
        return !isWhitespace(char);
      }).isSome();
    };
    var isStartOfWord = function(dom2) {
      return function(rng) {
        var leaf2 = toLeaf(rng.startContainer, rng.startOffset);
        return !isPreviousCharContent(dom2, leaf2);
      };
    };
    var getTriggerContext = function(dom2, initRange, database) {
      return findMap(database.triggerChars, function(ch) {
        return getContext(dom2, initRange, ch);
      });
    };
    var lookup$2 = function(editor, getDatabase) {
      var database = getDatabase();
      var rng = editor.selection.getRng();
      return getTriggerContext(editor.dom, rng, database).bind(function(context) {
        return lookupWithContext(editor, getDatabase, context);
      });
    };
    var lookupWithContext = function(editor, getDatabase, context, fetchOptions) {
      if (fetchOptions === void 0) {
        fetchOptions = {};
      }
      var database = getDatabase();
      var rng = editor.selection.getRng();
      var startText = rng.startContainer.nodeValue;
      var autocompleters = filter$2(database.lookupByChar(context.triggerChar), function(autocompleter) {
        return context.text.length >= autocompleter.minChars && autocompleter.matches.getOrThunk(function() {
          return isStartOfWord(editor.dom);
        })(context.range, startText, context.text);
      });
      if (autocompleters.length === 0) {
        return Optional.none();
      }
      var lookupData = global$c.all(map$2(autocompleters, function(ac) {
        var fetchResult = ac.fetch(context.text, ac.maxResults, fetchOptions);
        return fetchResult.then(function(results) {
          return {
            matchText: context.text,
            items: results,
            columns: ac.columns,
            onAction: ac.onAction,
            highlightOn: ac.highlightOn
          };
        });
      }));
      return Optional.some({
        lookupData,
        context
      });
    };
    var separatorMenuItemSchema = objOf([
      requiredString("type"),
      optionString("text")
    ]);
    var createSeparatorMenuItem = function(spec) {
      return asRaw("separatormenuitem", separatorMenuItemSchema, spec);
    };
    var autocompleterItemSchema = objOf([
      defaulted("type", "autocompleteitem"),
      defaulted("active", false),
      defaulted("disabled", false),
      defaulted("meta", {}),
      requiredString("value"),
      optionString("text"),
      optionString("icon")
    ]);
    var autocompleterSchema = objOf([
      requiredString("type"),
      requiredString("ch"),
      defaultedNumber("minChars", 1),
      defaulted("columns", 1),
      defaultedNumber("maxResults", 10),
      optionFunction("matches"),
      requiredFunction("fetch"),
      requiredFunction("onAction"),
      defaultedArrayOf("highlightOn", [], string)
    ]);
    var createSeparatorItem = function(spec) {
      return asRaw("Autocompleter.Separator", separatorMenuItemSchema, spec);
    };
    var createAutocompleterItem = function(spec) {
      return asRaw("Autocompleter.Item", autocompleterItemSchema, spec);
    };
    var createAutocompleter = function(spec) {
      return asRaw("Autocompleter", autocompleterSchema, spec);
    };
    var baseToolbarButtonFields = [
      defaultedBoolean("disabled", false),
      optionString("tooltip"),
      optionString("icon"),
      optionString("text"),
      defaultedFunction("onSetup", function() {
        return noop3;
      })
    ];
    var toolbarButtonSchema = objOf([
      requiredString("type"),
      requiredFunction("onAction")
    ].concat(baseToolbarButtonFields));
    var createToolbarButton = function(spec) {
      return asRaw("toolbarbutton", toolbarButtonSchema, spec);
    };
    var baseToolbarToggleButtonFields = [defaultedBoolean("active", false)].concat(baseToolbarButtonFields);
    var toggleButtonSchema = objOf(baseToolbarToggleButtonFields.concat([
      requiredString("type"),
      requiredFunction("onAction")
    ]));
    var createToggleButton = function(spec) {
      return asRaw("ToggleButton", toggleButtonSchema, spec);
    };
    var contextBarFields = [
      defaultedFunction("predicate", never),
      defaultedStringEnum("scope", "node", [
        "node",
        "editor"
      ]),
      defaultedStringEnum("position", "selection", [
        "node",
        "selection",
        "line"
      ])
    ];
    var contextButtonFields = baseToolbarButtonFields.concat([
      defaulted("type", "contextformbutton"),
      defaulted("primary", false),
      requiredFunction("onAction"),
      customField("original", identity$1)
    ]);
    var contextToggleButtonFields = baseToolbarToggleButtonFields.concat([
      defaulted("type", "contextformbutton"),
      defaulted("primary", false),
      requiredFunction("onAction"),
      customField("original", identity$1)
    ]);
    var launchButtonFields = baseToolbarButtonFields.concat([defaulted("type", "contextformbutton")]);
    var launchToggleButtonFields = baseToolbarToggleButtonFields.concat([defaulted("type", "contextformtogglebutton")]);
    var toggleOrNormal = choose$1("type", {
      contextformbutton: contextButtonFields,
      contextformtogglebutton: contextToggleButtonFields
    });
    var contextFormSchema = objOf([
      defaulted("type", "contextform"),
      defaultedFunction("initValue", constant$1("")),
      optionString("label"),
      requiredArrayOf("commands", toggleOrNormal),
      optionOf("launch", choose$1("type", {
        contextformbutton: launchButtonFields,
        contextformtogglebutton: launchToggleButtonFields
      }))
    ].concat(contextBarFields));
    var createContextForm = function(spec) {
      return asRaw("ContextForm", contextFormSchema, spec);
    };
    var contextToolbarSchema = objOf([
      defaulted("type", "contexttoolbar"),
      requiredString("items")
    ].concat(contextBarFields));
    var createContextToolbar = function(spec) {
      return asRaw("ContextToolbar", contextToolbarSchema, spec);
    };
    var stringArray = function(a2) {
      var all2 = {};
      each$1(a2, function(key) {
        all2[key] = {};
      });
      return keys(all2);
    };
    var register$b = function(editor) {
      var popups = editor.ui.registry.getAll().popups;
      var dataset2 = map$12(popups, function(popup) {
        return createAutocompleter(popup).fold(function(err) {
          throw new Error(formatError(err));
        }, identity$1);
      });
      var triggerChars = stringArray(mapToArray(dataset2, function(v2) {
        return v2.ch;
      }));
      var datasetValues = values(dataset2);
      var lookupByChar = function(ch) {
        return filter$2(datasetValues, function(dv) {
          return dv.ch === ch;
        });
      };
      return {
        dataset: dataset2,
        triggerChars,
        lookupByChar
      };
    };
    var ItemResponse;
    (function(ItemResponse2) {
      ItemResponse2[ItemResponse2["CLOSE_ON_EXECUTE"] = 0] = "CLOSE_ON_EXECUTE";
      ItemResponse2[ItemResponse2["BUBBLE_TO_SANDBOX"] = 1] = "BUBBLE_TO_SANDBOX";
    })(ItemResponse || (ItemResponse = {}));
    var ItemResponse$1 = ItemResponse;
    var navClass = "tox-menu-nav__js";
    var selectableClass = "tox-collection__item";
    var colorClass = "tox-swatch";
    var presetClasses = {
      normal: navClass,
      color: colorClass
    };
    var tickedClass = "tox-collection__item--enabled";
    var groupHeadingClass = "tox-collection__group-heading";
    var iconClass = "tox-collection__item-icon";
    var textClass = "tox-collection__item-label";
    var accessoryClass = "tox-collection__item-accessory";
    var caretClass = "tox-collection__item-caret";
    var checkmarkClass = "tox-collection__item-checkmark";
    var activeClass = "tox-collection__item--active";
    var containerClass = "tox-collection__item-container";
    var containerColumnClass = "tox-collection__item-container--column";
    var containerRowClass = "tox-collection__item-container--row";
    var containerAlignRightClass = "tox-collection__item-container--align-right";
    var containerAlignLeftClass = "tox-collection__item-container--align-left";
    var containerValignTopClass = "tox-collection__item-container--valign-top";
    var containerValignMiddleClass = "tox-collection__item-container--valign-middle";
    var containerValignBottomClass = "tox-collection__item-container--valign-bottom";
    var classForPreset = function(presets) {
      return get$e(presetClasses, presets).getOr(navClass);
    };
    var forMenu = function(presets) {
      if (presets === "color") {
        return "tox-swatches";
      } else {
        return "tox-menu";
      }
    };
    var classes = function(presets) {
      return {
        backgroundMenu: "tox-background-menu",
        selectedMenu: "tox-selected-menu",
        selectedItem: "tox-collection__item--active",
        hasIcons: "tox-menu--has-icons",
        menu: forMenu(presets),
        tieredMenu: "tox-tiered-menu"
      };
    };
    var markers = function(presets) {
      var menuClasses = classes(presets);
      return {
        backgroundMenu: menuClasses.backgroundMenu,
        selectedMenu: menuClasses.selectedMenu,
        menu: menuClasses.menu,
        selectedItem: menuClasses.selectedItem,
        item: classForPreset(presets)
      };
    };
    var dom$1 = function(hasIcons, columns, presets) {
      var menuClasses = classes(presets);
      return {
        tag: "div",
        classes: flatten([
          [
            menuClasses.menu,
            "tox-menu-" + columns + "-column"
          ],
          hasIcons ? [menuClasses.hasIcons] : []
        ])
      };
    };
    var components = [Menu.parts.items({})];
    var part = function(hasIcons, columns, presets) {
      var menuClasses = classes(presets);
      var d2 = {
        tag: "div",
        classes: flatten([[menuClasses.tieredMenu]])
      };
      return {
        dom: d2,
        markers: markers(presets)
      };
    };
    var chunk = function(rowDom, numColumns) {
      return function(items) {
        var chunks = chunk$1(items, numColumns);
        return map$2(chunks, function(c2) {
          return {
            dom: rowDom,
            components: c2
          };
        });
      };
    };
    var forSwatch = function(columns) {
      return {
        dom: {
          tag: "div",
          classes: [
            "tox-menu",
            "tox-swatches-menu"
          ]
        },
        components: [{
          dom: {
            tag: "div",
            classes: ["tox-swatches"]
          },
          components: [Menu.parts.items({
            preprocess: columns !== "auto" ? chunk({
              tag: "div",
              classes: ["tox-swatches__row"]
            }, columns) : identity$1
          })]
        }]
      };
    };
    var forToolbar = function(columns) {
      return {
        dom: {
          tag: "div",
          classes: [
            "tox-menu",
            "tox-collection",
            "tox-collection--toolbar",
            "tox-collection--toolbar-lg"
          ]
        },
        components: [Menu.parts.items({
          preprocess: chunk({
            tag: "div",
            classes: ["tox-collection__group"]
          }, columns)
        })]
      };
    };
    var preprocessCollection = function(items, isSeparator2) {
      var allSplits = [];
      var currentSplit = [];
      each$1(items, function(item2, i2) {
        if (isSeparator2(item2, i2)) {
          if (currentSplit.length > 0) {
            allSplits.push(currentSplit);
          }
          currentSplit = [];
          if (has$2(item2.dom, "innerHtml")) {
            currentSplit.push(item2);
          }
        } else {
          currentSplit.push(item2);
        }
      });
      if (currentSplit.length > 0) {
        allSplits.push(currentSplit);
      }
      return map$2(allSplits, function(s2) {
        return {
          dom: {
            tag: "div",
            classes: ["tox-collection__group"]
          },
          components: s2
        };
      });
    };
    var forCollection = function(columns, initItems, _hasIcons) {
      return {
        dom: {
          tag: "div",
          classes: [
            "tox-menu",
            "tox-collection"
          ].concat(columns === 1 ? ["tox-collection--list"] : ["tox-collection--grid"])
        },
        components: [Menu.parts.items({
          preprocess: function(items) {
            if (columns !== "auto" && columns > 1) {
              return chunk({
                tag: "div",
                classes: ["tox-collection__group"]
              }, columns)(items);
            } else {
              return preprocessCollection(items, function(_item, i2) {
                return initItems[i2].type === "separator";
              });
            }
          }
        })]
      };
    };
    var forHorizontalCollection = function(initItems, _hasIcons) {
      return {
        dom: {
          tag: "div",
          classes: [
            "tox-collection",
            "tox-collection--horizontal"
          ]
        },
        components: [Menu.parts.items({
          preprocess: function(items) {
            return preprocessCollection(items, function(_item, i2) {
              return initItems[i2].type === "separator";
            });
          }
        })]
      };
    };
    var menuHasIcons = function(xs) {
      return exists(xs, function(item2) {
        return "icon" in item2 && item2.icon !== void 0;
      });
    };
    var handleError = function(error4) {
      console.error(formatError(error4));
      console.log(error4);
      return Optional.none();
    };
    var createHorizontalPartialMenuWithAlloyItems = function(value2, _hasIcons, items, _columns, _presets) {
      var structure = forHorizontalCollection(items);
      return {
        value: value2,
        dom: structure.dom,
        components: structure.components,
        items
      };
    };
    var createPartialMenuWithAlloyItems = function(value2, hasIcons, items, columns, presets) {
      if (presets === "color") {
        var structure = forSwatch(columns);
        return {
          value: value2,
          dom: structure.dom,
          components: structure.components,
          items
        };
      }
      if (presets === "normal" && columns === "auto") {
        var structure = forCollection(columns, items);
        return {
          value: value2,
          dom: structure.dom,
          components: structure.components,
          items
        };
      }
      if (presets === "normal" && columns === 1) {
        var structure = forCollection(1, items);
        return {
          value: value2,
          dom: structure.dom,
          components: structure.components,
          items
        };
      }
      if (presets === "normal") {
        var structure = forCollection(columns, items);
        return {
          value: value2,
          dom: structure.dom,
          components: structure.components,
          items
        };
      }
      if (presets === "listpreview" && columns !== "auto") {
        var structure = forToolbar(columns);
        return {
          value: value2,
          dom: structure.dom,
          components: structure.components,
          items
        };
      }
      return {
        value: value2,
        dom: dom$1(hasIcons, columns, presets),
        components,
        items
      };
    };
    var cardImageFields = [
      requiredString("type"),
      requiredString("src"),
      optionString("alt"),
      defaultedArrayOf("classes", [], string)
    ];
    var cardImageSchema = objOf(cardImageFields);
    var cardTextFields = [
      requiredString("type"),
      requiredString("text"),
      optionString("name"),
      defaultedArrayOf("classes", ["tox-collection__item-label"], string)
    ];
    var cardTextSchema = objOf(cardTextFields);
    var itemSchema$1 = valueThunk(function() {
      return choose$2("type", {
        cardimage: cardImageSchema,
        cardtext: cardTextSchema,
        cardcontainer: cardContainerSchema
      });
    });
    var cardContainerSchema = objOf([
      requiredString("type"),
      defaultedString("direction", "horizontal"),
      defaultedString("align", "left"),
      defaultedString("valign", "middle"),
      requiredArrayOf("items", itemSchema$1)
    ]);
    var commonMenuItemFields = [
      defaultedBoolean("disabled", false),
      optionString("text"),
      optionString("shortcut"),
      field$1("value", "value", defaultedThunk(function() {
        return generate$6("menuitem-value");
      }), anyValue()),
      defaulted("meta", {})
    ];
    var cardMenuItemSchema = objOf([
      requiredString("type"),
      optionString("label"),
      requiredArrayOf("items", itemSchema$1),
      defaultedFunction("onSetup", function() {
        return noop3;
      }),
      defaultedFunction("onAction", noop3)
    ].concat(commonMenuItemFields));
    var createCardMenuItem = function(spec) {
      return asRaw("cardmenuitem", cardMenuItemSchema, spec);
    };
    var choiceMenuItemSchema = objOf([
      requiredString("type"),
      defaultedBoolean("active", false),
      optionString("icon")
    ].concat(commonMenuItemFields));
    var createChoiceMenuItem = function(spec) {
      return asRaw("choicemenuitem", choiceMenuItemSchema, spec);
    };
    var baseFields = [
      requiredString("type"),
      requiredString("fancytype"),
      defaultedFunction("onAction", noop3)
    ];
    var insertTableFields = [defaulted("initData", {})].concat(baseFields);
    var colorSwatchFields = [defaultedObjOf("initData", {}, [
      defaultedBoolean("allowCustomColors", true),
      optionArrayOf("colors", anyValue())
    ])].concat(baseFields);
    var fancyMenuItemSchema = choose$1("fancytype", {
      inserttable: insertTableFields,
      colorswatch: colorSwatchFields
    });
    var createFancyMenuItem = function(spec) {
      return asRaw("fancymenuitem", fancyMenuItemSchema, spec);
    };
    var menuItemSchema = objOf([
      requiredString("type"),
      defaultedFunction("onSetup", function() {
        return noop3;
      }),
      defaultedFunction("onAction", noop3),
      optionString("icon")
    ].concat(commonMenuItemFields));
    var createMenuItem = function(spec) {
      return asRaw("menuitem", menuItemSchema, spec);
    };
    var nestedMenuItemSchema = objOf([
      requiredString("type"),
      requiredFunction("getSubmenuItems"),
      defaultedFunction("onSetup", function() {
        return noop3;
      }),
      optionString("icon")
    ].concat(commonMenuItemFields));
    var createNestedMenuItem = function(spec) {
      return asRaw("nestedmenuitem", nestedMenuItemSchema, spec);
    };
    var toggleMenuItemSchema = objOf([
      requiredString("type"),
      optionString("icon"),
      defaultedBoolean("active", false),
      defaultedFunction("onSetup", function() {
        return noop3;
      }),
      requiredFunction("onAction")
    ].concat(commonMenuItemFields));
    var createToggleMenuItem = function(spec) {
      return asRaw("togglemenuitem", toggleMenuItemSchema, spec);
    };
    var detectSize = function(comp, margin, selectorClass) {
      var descendants$1 = descendants(comp.element, "." + selectorClass);
      if (descendants$1.length > 0) {
        var columnLength = findIndex$1(descendants$1, function(c2) {
          var thisTop = c2.dom.getBoundingClientRect().top;
          var cTop = descendants$1[0].dom.getBoundingClientRect().top;
          return Math.abs(thisTop - cTop) > margin;
        }).getOr(descendants$1.length);
        return Optional.some({
          numColumns: columnLength,
          numRows: Math.ceil(descendants$1.length / columnLength)
        });
      } else {
        return Optional.none();
      }
    };
    var namedEvents = function(name2, handlers2) {
      return derive$1([config(name2, handlers2)]);
    };
    var unnamedEvents = function(handlers2) {
      return namedEvents(generate$6("unnamed-events"), handlers2);
    };
    var SimpleBehaviours = {
      namedEvents,
      unnamedEvents
    };
    var ExclusivityChannel = generate$6("tooltip.exclusive");
    var ShowTooltipEvent = generate$6("tooltip.show");
    var HideTooltipEvent = generate$6("tooltip.hide");
    var hideAllExclusive = function(component, _tConfig, _tState) {
      component.getSystem().broadcastOn([ExclusivityChannel], {});
    };
    var setComponents = function(component, tConfig, tState, specs) {
      tState.getTooltip().each(function(tooltip) {
        if (tooltip.getSystem().isConnected()) {
          Replacing.set(tooltip, specs);
        }
      });
    };
    var TooltippingApis = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      hideAllExclusive,
      setComponents
    });
    var events$9 = function(tooltipConfig, state) {
      var hide2 = function(comp) {
        state.getTooltip().each(function(p2) {
          detach(p2);
          tooltipConfig.onHide(comp, p2);
          state.clearTooltip();
        });
        state.clearTimer();
      };
      var show2 = function(comp) {
        if (!state.isShowing()) {
          hideAllExclusive(comp);
          var sink = tooltipConfig.lazySink(comp).getOrDie();
          var popup = comp.getSystem().build({
            dom: tooltipConfig.tooltipDom,
            components: tooltipConfig.tooltipComponents,
            events: derive$2(tooltipConfig.mode === "normal" ? [
              run$1(mouseover(), function(_2) {
                emit(comp, ShowTooltipEvent);
              }),
              run$1(mouseout(), function(_2) {
                emit(comp, HideTooltipEvent);
              })
            ] : []),
            behaviours: derive$1([Replacing.config({})])
          });
          state.setTooltip(popup);
          attach(sink, popup);
          tooltipConfig.onShow(comp, popup);
          Positioning.position(sink, popup, { anchor: tooltipConfig.anchor(comp) });
        }
      };
      return derive$2(flatten([
        [
          run$1(ShowTooltipEvent, function(comp) {
            state.resetTimer(function() {
              show2(comp);
            }, tooltipConfig.delay);
          }),
          run$1(HideTooltipEvent, function(comp) {
            state.resetTimer(function() {
              hide2(comp);
            }, tooltipConfig.delay);
          }),
          run$1(receive(), function(comp, message) {
            var receivingData = message;
            if (!receivingData.universal) {
              if (contains$2(receivingData.channels, ExclusivityChannel)) {
                hide2(comp);
              }
            }
          }),
          runOnDetached(function(comp) {
            hide2(comp);
          })
        ],
        tooltipConfig.mode === "normal" ? [
          run$1(focusin(), function(comp) {
            emit(comp, ShowTooltipEvent);
          }),
          run$1(postBlur(), function(comp) {
            emit(comp, HideTooltipEvent);
          }),
          run$1(mouseover(), function(comp) {
            emit(comp, ShowTooltipEvent);
          }),
          run$1(mouseout(), function(comp) {
            emit(comp, HideTooltipEvent);
          })
        ] : [
          run$1(highlight$1(), function(comp, _se) {
            emit(comp, ShowTooltipEvent);
          }),
          run$1(dehighlight$1(), function(comp) {
            emit(comp, HideTooltipEvent);
          })
        ]
      ]));
    };
    var ActiveTooltipping = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      events: events$9
    });
    var TooltippingSchema = [
      required$1("lazySink"),
      required$1("tooltipDom"),
      defaulted("exclusive", true),
      defaulted("tooltipComponents", []),
      defaulted("delay", 300),
      defaultedStringEnum("mode", "normal", [
        "normal",
        "follow-highlight"
      ]),
      defaulted("anchor", function(comp) {
        return {
          type: "hotspot",
          hotspot: comp,
          layouts: {
            onLtr: constant$1([
              south$2,
              north$2,
              southeast$2,
              northeast$2,
              southwest$2,
              northwest$2
            ]),
            onRtl: constant$1([
              south$2,
              north$2,
              southeast$2,
              northeast$2,
              southwest$2,
              northwest$2
            ])
          }
        };
      }),
      onHandler("onHide"),
      onHandler("onShow")
    ];
    var init$b = function() {
      var timer = value$1();
      var popup = value$1();
      var clearTimer = function() {
        timer.on(clearTimeout);
      };
      var resetTimer = function(f2, delay) {
        clearTimer();
        timer.set(setTimeout(f2, delay));
      };
      var readState = constant$1("not-implemented");
      return nu$8({
        getTooltip: popup.get,
        isShowing: popup.isSet,
        setTooltip: popup.set,
        clearTooltip: popup.clear,
        clearTimer,
        resetTimer,
        readState
      });
    };
    var TooltippingState = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      init: init$b
    });
    var Tooltipping = create$7({
      fields: TooltippingSchema,
      name: "tooltipping",
      active: ActiveTooltipping,
      state: TooltippingState,
      apis: TooltippingApis
    });
    var escape2 = function(text2) {
      return text2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
    };
    var global$b = tinymce.util.Tools.resolve("tinymce.dom.DOMUtils");
    var global$a = tinymce.util.Tools.resolve("tinymce.EditorManager");
    var getSkinUrl = function(editor) {
      var skin = editor.getParam("skin");
      var skinUrl = editor.getParam("skin_url");
      if (skin !== false) {
        var skinName = skin ? skin : "oxide";
        if (skinUrl) {
          skinUrl = editor.documentBaseURI.toAbsolute(skinUrl);
        } else {
          skinUrl = global$a.baseURL + "/skins/ui/" + skinName;
        }
      }
      return skinUrl;
    };
    var isReadOnly = function(editor) {
      return editor.getParam("readonly", false, "boolean");
    };
    var isSkinDisabled = function(editor) {
      return editor.getParam("skin") === false;
    };
    var getHeightSetting = function(editor) {
      return editor.getParam("height", Math.max(editor.getElement().offsetHeight, 200));
    };
    var getWidthSetting = function(editor) {
      return editor.getParam("width", global$b.DOM.getStyle(editor.getElement(), "width"));
    };
    var getMinWidthSetting = function(editor) {
      return Optional.from(editor.getParam("min_width")).filter(isNumber2);
    };
    var getMinHeightSetting = function(editor) {
      return Optional.from(editor.getParam("min_height")).filter(isNumber2);
    };
    var getMaxWidthSetting = function(editor) {
      return Optional.from(editor.getParam("max_width")).filter(isNumber2);
    };
    var getMaxHeightSetting = function(editor) {
      return Optional.from(editor.getParam("max_height")).filter(isNumber2);
    };
    var getUserStyleFormats = function(editor) {
      return Optional.from(editor.getParam("style_formats")).filter(isArray2);
    };
    var isMergeStyleFormats = function(editor) {
      return editor.getParam("style_formats_merge", false, "boolean");
    };
    var getLineHeightFormats = function(editor) {
      return editor.getParam("lineheight_formats", "1 1.1 1.2 1.3 1.4 1.5 2", "string").split(" ");
    };
    var getContentLanguages = function(editor) {
      return editor.getParam("content_langs", void 0, "array");
    };
    var getRemovedMenuItems = function(editor) {
      return editor.getParam("removed_menuitems", "");
    };
    var isMenubarEnabled = function(editor) {
      return editor.getParam("menubar", true, "boolean") !== false;
    };
    var isToolbarEnabled = function(editor) {
      var toolbar = editor.getParam("toolbar", true);
      var isToolbarTrue = toolbar === true;
      var isToolbarString = isString(toolbar);
      var isToolbarObjectArray = isArray2(toolbar) && toolbar.length > 0;
      return !isMultipleToolbars(editor) && (isToolbarObjectArray || isToolbarString || isToolbarTrue);
    };
    var getMultipleToolbarsSetting = function(editor) {
      var toolbars = range$2(9, function(num) {
        return editor.getParam("toolbar" + (num + 1), false, "string");
      });
      var toolbarArray = filter$2(toolbars, function(toolbar) {
        return typeof toolbar === "string";
      });
      return toolbarArray.length > 0 ? Optional.some(toolbarArray) : Optional.none();
    };
    var isMultipleToolbars = function(editor) {
      return getMultipleToolbarsSetting(editor).fold(function() {
        var toolbar = editor.getParam("toolbar", [], "string[]");
        return toolbar.length > 0;
      }, always);
    };
    var ToolbarMode;
    (function(ToolbarMode2) {
      ToolbarMode2["default"] = "wrap";
      ToolbarMode2["floating"] = "floating";
      ToolbarMode2["sliding"] = "sliding";
      ToolbarMode2["scrolling"] = "scrolling";
    })(ToolbarMode || (ToolbarMode = {}));
    var getToolbarMode = function(editor) {
      return editor.getParam("toolbar_mode", "", "string");
    };
    var ToolbarLocation;
    (function(ToolbarLocation2) {
      ToolbarLocation2["auto"] = "auto";
      ToolbarLocation2["top"] = "top";
      ToolbarLocation2["bottom"] = "bottom";
    })(ToolbarLocation || (ToolbarLocation = {}));
    var getToolbarGroups = function(editor) {
      return editor.getParam("toolbar_groups", {}, "object");
    };
    var getToolbarLocation = function(editor) {
      return editor.getParam("toolbar_location", ToolbarLocation.auto, "string");
    };
    var isToolbarLocationBottom = function(editor) {
      return getToolbarLocation(editor) === ToolbarLocation.bottom;
    };
    var fixedContainerSelector = function(editor) {
      return editor.getParam("fixed_toolbar_container", "", "string");
    };
    var fixedToolbarContainerTarget = function(editor) {
      return editor.getParam("fixed_toolbar_container_target");
    };
    var isToolbarPersist = function(editor) {
      return editor.getParam("toolbar_persist", false, "boolean");
    };
    var fixedContainerTarget = function(editor) {
      if (!editor.inline) {
        return Optional.none();
      }
      var selector = fixedContainerSelector(editor);
      if (selector.length > 0) {
        return descendant(body(), selector);
      }
      var element2 = fixedToolbarContainerTarget(editor);
      if (isNonNullable(element2)) {
        return Optional.some(SugarElement.fromDom(element2));
      }
      return Optional.none();
    };
    var useFixedContainer = function(editor) {
      return editor.inline && fixedContainerTarget(editor).isSome();
    };
    var getUiContainer = function(editor) {
      var fixedContainer = fixedContainerTarget(editor);
      return fixedContainer.getOrThunk(function() {
        return getContentContainer(getRootNode(SugarElement.fromDom(editor.getElement())));
      });
    };
    var isDistractionFree = function(editor) {
      return editor.inline && !isMenubarEnabled(editor) && !isToolbarEnabled(editor) && !isMultipleToolbars(editor);
    };
    var isStickyToolbar = function(editor) {
      var isStickyToolbar2 = editor.getParam("toolbar_sticky", false, "boolean");
      return (isStickyToolbar2 || editor.inline) && !useFixedContainer(editor) && !isDistractionFree(editor);
    };
    var getStickyToolbarOffset = function(editor) {
      return editor.getParam("toolbar_sticky_offset", 0, "number");
    };
    var isDraggableModal$1 = function(editor) {
      return editor.getParam("draggable_modal", false, "boolean");
    };
    var getMenus = function(editor) {
      var menu2 = editor.getParam("menu");
      if (menu2) {
        return map$12(menu2, function(menu3) {
          return __assign(__assign({}, menu3), { items: menu3.items });
        });
      } else {
        return {};
      }
    };
    var getMenubar = function(editor) {
      return editor.getParam("menubar");
    };
    var getToolbar = function(editor) {
      return editor.getParam("toolbar", true);
    };
    var getFilePickerCallback = function(editor) {
      return editor.getParam("file_picker_callback");
    };
    var getFilePickerTypes = function(editor) {
      return editor.getParam("file_picker_types");
    };
    var getFileBrowserCallbackTypes = function(editor) {
      return editor.getParam("file_browser_callback_types");
    };
    var noTypeaheadUrls = function(editor) {
      return editor.getParam("typeahead_urls") === false;
    };
    var getAnchorTop = function(editor) {
      return editor.getParam("anchor_top", "#top");
    };
    var getAnchorBottom = function(editor) {
      return editor.getParam("anchor_bottom", "#bottom");
    };
    var getFilePickerValidatorHandler = function(editor) {
      var handler = editor.getParam("file_picker_validator_handler", void 0, "function");
      if (handler === void 0) {
        return editor.getParam("filepicker_validator_handler", void 0, "function");
      } else {
        return handler;
      }
    };
    var ReadOnlyChannel = "silver.readonly";
    var ReadOnlyDataSchema = objOf([requiredBoolean("readonly")]);
    var broadcastReadonly = function(uiComponents, readonly) {
      var outerContainer = uiComponents.outerContainer;
      var target = outerContainer.element;
      if (readonly) {
        uiComponents.mothership.broadcastOn([dismissPopups()], { target });
        uiComponents.uiMothership.broadcastOn([dismissPopups()], { target });
      }
      uiComponents.mothership.broadcastOn([ReadOnlyChannel], { readonly });
      uiComponents.uiMothership.broadcastOn([ReadOnlyChannel], { readonly });
    };
    var setupReadonlyModeSwitch = function(editor, uiComponents) {
      editor.on("init", function() {
        if (editor.mode.isReadOnly()) {
          broadcastReadonly(uiComponents, true);
        }
      });
      editor.on("SwitchMode", function() {
        return broadcastReadonly(uiComponents, editor.mode.isReadOnly());
      });
      if (isReadOnly(editor)) {
        editor.setMode("readonly");
      }
    };
    var receivingConfig = function() {
      var _a2;
      return Receiving.config({
        channels: (_a2 = {}, _a2[ReadOnlyChannel] = {
          schema: ReadOnlyDataSchema,
          onReceive: function(comp, data) {
            Disabling.set(comp, data.readonly);
          }
        }, _a2)
      });
    };
    var item = function(disabled) {
      return Disabling.config({
        disabled,
        disableClass: "tox-collection__item--state-disabled"
      });
    };
    var button = function(disabled) {
      return Disabling.config({ disabled });
    };
    var splitButton = function(disabled) {
      return Disabling.config({
        disabled,
        disableClass: "tox-tbtn--disabled"
      });
    };
    var toolbarButton = function(disabled) {
      return Disabling.config({
        disabled,
        disableClass: "tox-tbtn--disabled",
        useNative: false
      });
    };
    var DisablingConfigs = {
      item,
      button,
      splitButton,
      toolbarButton
    };
    var runWithApi = function(info, comp) {
      var api2 = info.getApi(comp);
      return function(f2) {
        f2(api2);
      };
    };
    var onControlAttached = function(info, editorOffCell) {
      return runOnAttached(function(comp) {
        var run2 = runWithApi(info, comp);
        run2(function(api2) {
          var onDestroy = info.onSetup(api2);
          if (isFunction2(onDestroy)) {
            editorOffCell.set(onDestroy);
          }
        });
      });
    };
    var onControlDetached = function(getApi2, editorOffCell) {
      return runOnDetached(function(comp) {
        return runWithApi(getApi2, comp)(editorOffCell.get());
      });
    };
    var _a$1;
    var onMenuItemExecute = function(info, itemResponse) {
      return runOnExecute$1(function(comp, simulatedEvent) {
        runWithApi(info, comp)(info.onAction);
        if (!info.triggersSubmenu && itemResponse === ItemResponse$1.CLOSE_ON_EXECUTE) {
          emit(comp, sandboxClose());
          simulatedEvent.stop();
        }
      });
    };
    var menuItemEventOrder = (_a$1 = {}, _a$1[execute$5()] = [
      "disabling",
      "alloy.base.behaviour",
      "toggling",
      "item-events"
    ], _a$1);
    var componentRenderPipeline = cat;
    var renderCommonItem = function(spec, structure, itemResponse, providersbackstage) {
      var editorOffCell = Cell(noop3);
      return {
        type: "item",
        dom: structure.dom,
        components: componentRenderPipeline(structure.optComponents),
        data: spec.data,
        eventOrder: menuItemEventOrder,
        hasSubmenu: spec.triggersSubmenu,
        itemBehaviours: derive$1([
          config("item-events", [
            onMenuItemExecute(spec, itemResponse),
            onControlAttached(spec, editorOffCell),
            onControlDetached(spec, editorOffCell)
          ]),
          DisablingConfigs.item(function() {
            return spec.disabled || providersbackstage.isDisabled();
          }),
          receivingConfig(),
          Replacing.config({})
        ].concat(spec.itemBehaviours))
      };
    };
    var buildData = function(source) {
      return {
        value: source.value,
        meta: __assign({ text: source.text.getOr("") }, source.meta)
      };
    };
    var global$9 = tinymce.util.Tools.resolve("tinymce.Env");
    var convertText = function(source) {
      var mac = {
        alt: "&#x2325;",
        ctrl: "&#x2303;",
        shift: "&#x21E7;",
        meta: "&#x2318;",
        access: "&#x2303;&#x2325;"
      };
      var other = {
        meta: "Ctrl",
        access: "Shift+Alt"
      };
      var replace = global$9.mac ? mac : other;
      var shortcut = source.split("+");
      var updated = map$2(shortcut, function(segment) {
        var search2 = segment.toLowerCase().trim();
        return has$2(replace, search2) ? replace[search2] : segment;
      });
      return global$9.mac ? updated.join("") : updated.join("+");
    };
    var renderIcon$1 = function(name2, icons, classes2) {
      if (classes2 === void 0) {
        classes2 = [iconClass];
      }
      return render$3(name2, {
        tag: "div",
        classes: classes2
      }, icons);
    };
    var renderText2 = function(text$1) {
      return {
        dom: {
          tag: "div",
          classes: [textClass]
        },
        components: [text(global$e.translate(text$1))]
      };
    };
    var renderHtml = function(html, classes2) {
      return {
        dom: {
          tag: "div",
          classes: classes2,
          innerHtml: html
        }
      };
    };
    var renderStyledText = function(style, text$1) {
      return {
        dom: {
          tag: "div",
          classes: [textClass]
        },
        components: [{
          dom: {
            tag: style.tag,
            styles: style.styles
          },
          components: [text(global$e.translate(text$1))]
        }]
      };
    };
    var renderShortcut = function(shortcut) {
      return {
        dom: {
          tag: "div",
          classes: [accessoryClass],
          innerHtml: convertText(shortcut)
        }
      };
    };
    var renderCheckmark = function(icons) {
      return renderIcon$1("checkmark", icons, [checkmarkClass]);
    };
    var renderSubmenuCaret = function(icons) {
      return renderIcon$1("chevron-right", icons, [caretClass]);
    };
    var renderDownwardsCaret = function(icons) {
      return renderIcon$1("chevron-down", icons, [caretClass]);
    };
    var renderContainer = function(container, components2) {
      var directionClass = container.direction === "vertical" ? containerColumnClass : containerRowClass;
      var alignClass = container.align === "left" ? containerAlignLeftClass : containerAlignRightClass;
      var getValignClass = function() {
        switch (container.valign) {
          case "top":
            return containerValignTopClass;
          case "middle":
            return containerValignMiddleClass;
          case "bottom":
            return containerValignBottomClass;
        }
      };
      return {
        dom: {
          tag: "div",
          classes: [
            containerClass,
            directionClass,
            alignClass,
            getValignClass()
          ]
        },
        components: components2
      };
    };
    var renderImage = function(src, classes2, alt) {
      return {
        dom: {
          tag: "img",
          classes: classes2,
          attributes: {
            src,
            alt: alt.getOr("")
          }
        }
      };
    };
    var renderColorStructure = function(item2, providerBackstage, fallbackIcon) {
      var colorPickerCommand = "custom";
      var removeColorCommand = "remove";
      var itemText = item2.ariaLabel;
      var itemValue = item2.value;
      var iconSvg = item2.iconContent.map(function(name2) {
        return getOr(name2, providerBackstage.icons, fallbackIcon);
      });
      var getDom = function() {
        var common = colorClass;
        var icon = iconSvg.getOr("");
        var attributes = itemText.map(function(text2) {
          return { title: providerBackstage.translate(text2) };
        }).getOr({});
        var baseDom = {
          tag: "div",
          attributes,
          classes: [common]
        };
        if (itemValue === colorPickerCommand) {
          return __assign(__assign({}, baseDom), {
            tag: "button",
            classes: __spreadArray(__spreadArray([], baseDom.classes, true), ["tox-swatches__picker-btn"], false),
            innerHtml: icon
          });
        } else if (itemValue === removeColorCommand) {
          return __assign(__assign({}, baseDom), {
            classes: __spreadArray(__spreadArray([], baseDom.classes, true), ["tox-swatch--remove"], false),
            innerHtml: icon
          });
        } else {
          return __assign(__assign({}, baseDom), {
            attributes: __assign(__assign({}, baseDom.attributes), { "data-mce-color": itemValue }),
            styles: { "background-color": itemValue }
          });
        }
      };
      return {
        dom: getDom(),
        optComponents: []
      };
    };
    var renderItemDomStructure = function(ariaLabel) {
      var domTitle = ariaLabel.map(function(label) {
        return { attributes: { title: global$e.translate(label) } };
      }).getOr({});
      return __assign({
        tag: "div",
        classes: [
          navClass,
          selectableClass
        ]
      }, domTitle);
    };
    var renderNormalItemStructure = function(info, providersBackstage, renderIcons, fallbackIcon) {
      var iconSpec = {
        tag: "div",
        classes: [iconClass]
      };
      var renderIcon2 = function(iconName) {
        return render$3(iconName, iconSpec, providersBackstage.icons, fallbackIcon);
      };
      var renderEmptyIcon = function() {
        return Optional.some({ dom: iconSpec });
      };
      var leftIcon = renderIcons ? info.iconContent.map(renderIcon2).orThunk(renderEmptyIcon) : Optional.none();
      var checkmark = info.checkMark;
      var textRender = Optional.from(info.meta).fold(function() {
        return renderText2;
      }, function(meta) {
        return has$2(meta, "style") ? curry(renderStyledText, meta.style) : renderText2;
      });
      var content = info.htmlContent.fold(function() {
        return info.textContent.map(textRender);
      }, function(html) {
        return Optional.some(renderHtml(html, [textClass]));
      });
      var menuItem = {
        dom: renderItemDomStructure(info.ariaLabel),
        optComponents: [
          leftIcon,
          content,
          info.shortcutContent.map(renderShortcut),
          checkmark,
          info.caret
        ]
      };
      return menuItem;
    };
    var renderItemStructure = function(info, providersBackstage, renderIcons, fallbackIcon) {
      if (fallbackIcon === void 0) {
        fallbackIcon = Optional.none();
      }
      if (info.presets === "color") {
        return renderColorStructure(info, providersBackstage, fallbackIcon);
      } else {
        return renderNormalItemStructure(info, providersBackstage, renderIcons, fallbackIcon);
      }
    };
    var tooltipBehaviour = function(meta, sharedBackstage) {
      return get$e(meta, "tooltipWorker").map(function(tooltipWorker) {
        return [Tooltipping.config({
          lazySink: sharedBackstage.getSink,
          tooltipDom: {
            tag: "div",
            classes: ["tox-tooltip-worker-container"]
          },
          tooltipComponents: [],
          anchor: function(comp) {
            return {
              type: "submenu",
              item: comp,
              overrides: { maxHeightFunction: expandable$1 }
            };
          },
          mode: "follow-highlight",
          onShow: function(component, _tooltip) {
            tooltipWorker(function(elm) {
              Tooltipping.setComponents(component, [external$2({ element: SugarElement.fromDom(elm) })]);
            });
          }
        })];
      }).getOr([]);
    };
    var encodeText = function(text2) {
      return global$b.DOM.encode(text2);
    };
    var replaceText = function(text2, matchText) {
      var translated = global$e.translate(text2);
      var encoded = encodeText(translated);
      if (matchText.length > 0) {
        var escapedMatchRegex = new RegExp(escape2(matchText), "gi");
        return encoded.replace(escapedMatchRegex, function(match2) {
          return '<span class="tox-autocompleter-highlight">' + match2 + "</span>";
        });
      } else {
        return encoded;
      }
    };
    var renderAutocompleteItem = function(spec, matchText, useText, presets, onItemValueHandler, itemResponse, sharedBackstage, renderIcons) {
      if (renderIcons === void 0) {
        renderIcons = true;
      }
      var structure = renderItemStructure({
        presets,
        textContent: Optional.none(),
        htmlContent: useText ? spec.text.map(function(text2) {
          return replaceText(text2, matchText);
        }) : Optional.none(),
        ariaLabel: spec.text,
        iconContent: spec.icon,
        shortcutContent: Optional.none(),
        checkMark: Optional.none(),
        caret: Optional.none(),
        value: spec.value
      }, sharedBackstage.providers, renderIcons, spec.icon);
      return renderCommonItem({
        data: buildData(spec),
        disabled: spec.disabled,
        getApi: constant$1({}),
        onAction: function(_api) {
          return onItemValueHandler(spec.value, spec.meta);
        },
        onSetup: constant$1(noop3),
        triggersSubmenu: false,
        itemBehaviours: tooltipBehaviour(spec.meta, sharedBackstage)
      }, structure, itemResponse, sharedBackstage.providers);
    };
    var render$2 = function(items, extras) {
      return map$2(items, function(item2) {
        switch (item2.type) {
          case "cardcontainer":
            return renderContainer(item2, render$2(item2.items, extras));
          case "cardimage":
            return renderImage(item2.src, item2.classes, item2.alt);
          case "cardtext":
            var shouldHighlight = item2.name.exists(function(name2) {
              return contains$2(extras.cardText.highlightOn, name2);
            });
            var matchText = shouldHighlight ? Optional.from(extras.cardText.matchText).getOr("") : "";
            return renderHtml(replaceText(item2.text, matchText), item2.classes);
        }
      });
    };
    var renderCardMenuItem = function(spec, itemResponse, sharedBackstage, extras) {
      var getApi2 = function(component) {
        return {
          isDisabled: function() {
            return Disabling.isDisabled(component);
          },
          setDisabled: function(state) {
            Disabling.set(component, state);
            each$1(descendants(component.element, "*"), function(elm) {
              component.getSystem().getByDom(elm).each(function(comp) {
                if (comp.hasConfigured(Disabling)) {
                  Disabling.set(comp, state);
                }
              });
            });
          }
        };
      };
      var structure = {
        dom: renderItemDomStructure(spec.label),
        optComponents: [Optional.some({
          dom: {
            tag: "div",
            classes: [
              containerClass,
              containerRowClass
            ]
          },
          components: render$2(spec.items, extras)
        })]
      };
      return renderCommonItem({
        data: buildData(__assign({ text: Optional.none() }, spec)),
        disabled: spec.disabled,
        getApi: getApi2,
        onAction: spec.onAction,
        onSetup: spec.onSetup,
        triggersSubmenu: false,
        itemBehaviours: Optional.from(extras.itemBehaviours).getOr([])
      }, structure, itemResponse, sharedBackstage.providers);
    };
    var renderChoiceItem = function(spec, useText, presets, onItemValueHandler, isSelected, itemResponse, providersBackstage, renderIcons) {
      if (renderIcons === void 0) {
        renderIcons = true;
      }
      var getApi2 = function(component) {
        return {
          setActive: function(state) {
            Toggling.set(component, state);
          },
          isActive: function() {
            return Toggling.isOn(component);
          },
          isDisabled: function() {
            return Disabling.isDisabled(component);
          },
          setDisabled: function(state) {
            return Disabling.set(component, state);
          }
        };
      };
      var structure = renderItemStructure({
        presets,
        textContent: useText ? spec.text : Optional.none(),
        htmlContent: Optional.none(),
        ariaLabel: spec.text,
        iconContent: spec.icon,
        shortcutContent: useText ? spec.shortcut : Optional.none(),
        checkMark: useText ? Optional.some(renderCheckmark(providersBackstage.icons)) : Optional.none(),
        caret: Optional.none(),
        value: spec.value
      }, providersBackstage, renderIcons);
      return deepMerge(renderCommonItem({
        data: buildData(spec),
        disabled: spec.disabled,
        getApi: getApi2,
        onAction: function(_api) {
          return onItemValueHandler(spec.value);
        },
        onSetup: function(api2) {
          api2.setActive(isSelected);
          return noop3;
        },
        triggersSubmenu: false,
        itemBehaviours: []
      }, structure, itemResponse, providersBackstage), {
        toggling: {
          toggleClass: tickedClass,
          toggleOnExecute: false,
          selected: spec.active
        }
      });
    };
    var parts$f = generate$3(owner$2(), parts$h());
    var hexColour = function(value2) {
      return { value: value2 };
    };
    var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
    var longformRegex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
    var isHexString = function(hex2) {
      return shorthandRegex.test(hex2) || longformRegex.test(hex2);
    };
    var normalizeHex = function(hex2) {
      return removeLeading(hex2, "#").toUpperCase();
    };
    var fromString$1 = function(hex2) {
      return isHexString(hex2) ? Optional.some({ value: normalizeHex(hex2) }) : Optional.none();
    };
    var getLongForm = function(hex2) {
      var hexString2 = hex2.value.replace(shorthandRegex, function(m2, r3, g2, b3) {
        return r3 + r3 + g2 + g2 + b3 + b3;
      });
      return { value: hexString2 };
    };
    var extractValues = function(hex2) {
      var longForm = getLongForm(hex2);
      var splitForm = longformRegex.exec(longForm.value);
      return splitForm === null ? [
        "FFFFFF",
        "FF",
        "FF",
        "FF"
      ] : splitForm;
    };
    var toHex = function(component) {
      var hex2 = component.toString(16);
      return (hex2.length === 1 ? "0" + hex2 : hex2).toUpperCase();
    };
    var fromRgba = function(rgbaColour2) {
      var value2 = toHex(rgbaColour2.red) + toHex(rgbaColour2.green) + toHex(rgbaColour2.blue);
      return hexColour(value2);
    };
    var min2 = Math.min;
    var max2 = Math.max;
    var round$1 = Math.round;
    var rgbRegex = /^rgb\((\d+),\s*(\d+),\s*(\d+)\)/;
    var rgbaRegex = /^rgba\((\d+),\s*(\d+),\s*(\d+),\s*(\d?(?:\.\d+)?)\)/;
    var rgbaColour = function(red2, green, blue, alpha) {
      return {
        red: red2,
        green,
        blue,
        alpha
      };
    };
    var isRgbaComponent = function(value2) {
      var num = parseInt(value2, 10);
      return num.toString() === value2 && num >= 0 && num <= 255;
    };
    var fromHsv = function(hsv) {
      var r3;
      var g2;
      var b3;
      var hue2 = (hsv.hue || 0) % 360;
      var saturation = hsv.saturation / 100;
      var brightness2 = hsv.value / 100;
      saturation = max2(0, min2(saturation, 1));
      brightness2 = max2(0, min2(brightness2, 1));
      if (saturation === 0) {
        r3 = g2 = b3 = round$1(255 * brightness2);
        return rgbaColour(r3, g2, b3, 1);
      }
      var side = hue2 / 60;
      var chroma = brightness2 * saturation;
      var x2 = chroma * (1 - Math.abs(side % 2 - 1));
      var match2 = brightness2 - chroma;
      switch (Math.floor(side)) {
        case 0:
          r3 = chroma;
          g2 = x2;
          b3 = 0;
          break;
        case 1:
          r3 = x2;
          g2 = chroma;
          b3 = 0;
          break;
        case 2:
          r3 = 0;
          g2 = chroma;
          b3 = x2;
          break;
        case 3:
          r3 = 0;
          g2 = x2;
          b3 = chroma;
          break;
        case 4:
          r3 = x2;
          g2 = 0;
          b3 = chroma;
          break;
        case 5:
          r3 = chroma;
          g2 = 0;
          b3 = x2;
          break;
        default:
          r3 = g2 = b3 = 0;
      }
      r3 = round$1(255 * (r3 + match2));
      g2 = round$1(255 * (g2 + match2));
      b3 = round$1(255 * (b3 + match2));
      return rgbaColour(r3, g2, b3, 1);
    };
    var fromHex = function(hexColour2) {
      var result = extractValues(hexColour2);
      var red2 = parseInt(result[1], 16);
      var green = parseInt(result[2], 16);
      var blue = parseInt(result[3], 16);
      return rgbaColour(red2, green, blue, 1);
    };
    var fromStringValues = function(red2, green, blue, alpha) {
      var r3 = parseInt(red2, 10);
      var g2 = parseInt(green, 10);
      var b3 = parseInt(blue, 10);
      var a2 = parseFloat(alpha);
      return rgbaColour(r3, g2, b3, a2);
    };
    var fromString = function(rgbaString) {
      if (rgbaString === "transparent") {
        return Optional.some(rgbaColour(0, 0, 0, 0));
      }
      var rgbMatch = rgbRegex.exec(rgbaString);
      if (rgbMatch !== null) {
        return Optional.some(fromStringValues(rgbMatch[1], rgbMatch[2], rgbMatch[3], "1"));
      }
      var rgbaMatch = rgbaRegex.exec(rgbaString);
      if (rgbaMatch !== null) {
        return Optional.some(fromStringValues(rgbaMatch[1], rgbaMatch[2], rgbaMatch[3], rgbaMatch[4]));
      }
      return Optional.none();
    };
    var toString = function(rgba) {
      return "rgba(" + rgba.red + "," + rgba.green + "," + rgba.blue + "," + rgba.alpha + ")";
    };
    var red = rgbaColour(255, 0, 0, 1);
    var fireSkinLoaded$1 = function(editor) {
      return editor.fire("SkinLoaded");
    };
    var fireSkinLoadError$1 = function(editor, error4) {
      return editor.fire("SkinLoadError", error4);
    };
    var fireResizeEditor = function(editor) {
      return editor.fire("ResizeEditor");
    };
    var fireResizeContent = function(editor, e2) {
      return editor.fire("ResizeContent", e2);
    };
    var fireScrollContent = function(editor, e2) {
      return editor.fire("ScrollContent", e2);
    };
    var fireTextColorChange = function(editor, data) {
      return editor.fire("TextColorChange", data);
    };
    var hsvColour = function(hue2, saturation, value2) {
      return {
        hue: hue2,
        saturation,
        value: value2
      };
    };
    var fromRgb = function(rgbaColour2) {
      var h3 = 0;
      var s2 = 0;
      var v2 = 0;
      var r3 = rgbaColour2.red / 255;
      var g2 = rgbaColour2.green / 255;
      var b3 = rgbaColour2.blue / 255;
      var minRGB = Math.min(r3, Math.min(g2, b3));
      var maxRGB = Math.max(r3, Math.max(g2, b3));
      if (minRGB === maxRGB) {
        v2 = minRGB;
        return hsvColour(0, 0, v2 * 100);
      }
      var d2 = r3 === minRGB ? g2 - b3 : b3 === minRGB ? r3 - g2 : b3 - r3;
      h3 = r3 === minRGB ? 3 : b3 === minRGB ? 1 : 5;
      h3 = 60 * (h3 - d2 / (maxRGB - minRGB));
      s2 = (maxRGB - minRGB) / maxRGB;
      v2 = maxRGB;
      return hsvColour(Math.round(h3), Math.round(s2 * 100), Math.round(v2 * 100));
    };
    var hexToHsv = function(hex2) {
      return fromRgb(fromHex(hex2));
    };
    var hsvToHex = function(hsv) {
      return fromRgba(fromHsv(hsv));
    };
    var anyToHex = function(color2) {
      return fromString$1(color2).orThunk(function() {
        return fromString(color2).map(fromRgba);
      }).getOrThunk(function() {
        var canvas = document.createElement("canvas");
        canvas.height = 1;
        canvas.width = 1;
        var canvasContext = canvas.getContext("2d");
        canvasContext.clearRect(0, 0, canvas.width, canvas.height);
        canvasContext.fillStyle = "#FFFFFF";
        canvasContext.fillStyle = color2;
        canvasContext.fillRect(0, 0, 1, 1);
        var rgba = canvasContext.getImageData(0, 0, 1, 1).data;
        var r3 = rgba[0];
        var g2 = rgba[1];
        var b3 = rgba[2];
        var a2 = rgba[3];
        return fromRgba(rgbaColour(r3, g2, b3, a2));
      });
    };
    var global$8 = tinymce.util.Tools.resolve("tinymce.util.LocalStorage");
    var storageName = "tinymce-custom-colors";
    function ColorCache(max3) {
      if (max3 === void 0) {
        max3 = 10;
      }
      var storageString = global$8.getItem(storageName);
      var localstorage = isString(storageString) ? JSON.parse(storageString) : [];
      var prune3 = function(list) {
        var diff = max3 - list.length;
        return diff < 0 ? list.slice(0, max3) : list;
      };
      var cache2 = prune3(localstorage);
      var add4 = function(key) {
        indexOf2(cache2, key).each(remove2);
        cache2.unshift(key);
        if (cache2.length > max3) {
          cache2.pop();
        }
        global$8.setItem(storageName, JSON.stringify(cache2));
      };
      var remove2 = function(idx) {
        cache2.splice(idx, 1);
      };
      var state = function() {
        return cache2.slice(0);
      };
      return {
        add: add4,
        state
      };
    }
    var choiceItem = "choiceitem";
    var defaultColors = [
      {
        type: choiceItem,
        text: "Light Green",
        value: "#BFEDD2"
      },
      {
        type: choiceItem,
        text: "Light Yellow",
        value: "#FBEEB8"
      },
      {
        type: choiceItem,
        text: "Light Red",
        value: "#F8CAC6"
      },
      {
        type: choiceItem,
        text: "Light Purple",
        value: "#ECCAFA"
      },
      {
        type: choiceItem,
        text: "Light Blue",
        value: "#C2E0F4"
      },
      {
        type: choiceItem,
        text: "Green",
        value: "#2DC26B"
      },
      {
        type: choiceItem,
        text: "Yellow",
        value: "#F1C40F"
      },
      {
        type: choiceItem,
        text: "Red",
        value: "#E03E2D"
      },
      {
        type: choiceItem,
        text: "Purple",
        value: "#B96AD9"
      },
      {
        type: choiceItem,
        text: "Blue",
        value: "#3598DB"
      },
      {
        type: choiceItem,
        text: "Dark Turquoise",
        value: "#169179"
      },
      {
        type: choiceItem,
        text: "Orange",
        value: "#E67E23"
      },
      {
        type: choiceItem,
        text: "Dark Red",
        value: "#BA372A"
      },
      {
        type: choiceItem,
        text: "Dark Purple",
        value: "#843FA1"
      },
      {
        type: choiceItem,
        text: "Dark Blue",
        value: "#236FA1"
      },
      {
        type: choiceItem,
        text: "Light Gray",
        value: "#ECF0F1"
      },
      {
        type: choiceItem,
        text: "Medium Gray",
        value: "#CED4D9"
      },
      {
        type: choiceItem,
        text: "Gray",
        value: "#95A5A6"
      },
      {
        type: choiceItem,
        text: "Dark Gray",
        value: "#7E8C8D"
      },
      {
        type: choiceItem,
        text: "Navy Blue",
        value: "#34495E"
      },
      {
        type: choiceItem,
        text: "Black",
        value: "#000000"
      },
      {
        type: choiceItem,
        text: "White",
        value: "#ffffff"
      }
    ];
    var colorCache = ColorCache(10);
    var mapColors = function(colorMap) {
      var colors2 = [];
      for (var i2 = 0; i2 < colorMap.length; i2 += 2) {
        colors2.push({
          text: colorMap[i2 + 1],
          value: "#" + anyToHex(colorMap[i2]).value,
          type: "choiceitem"
        });
      }
      return colors2;
    };
    var getColorCols$2 = function(editor, defaultCols) {
      return editor.getParam("color_cols", defaultCols, "number");
    };
    var hasCustomColors$1 = function(editor) {
      return editor.getParam("custom_colors") !== false;
    };
    var getColorMap = function(editor) {
      return editor.getParam("color_map");
    };
    var getColors$2 = function(editor) {
      var unmapped = getColorMap(editor);
      return unmapped !== void 0 ? mapColors(unmapped) : defaultColors;
    };
    var getCurrentColors = function() {
      return map$2(colorCache.state(), function(color2) {
        return {
          type: choiceItem,
          text: color2,
          value: color2
        };
      });
    };
    var addColor = function(color2) {
      colorCache.add(color2);
    };
    var fallbackColor = "#000000";
    var getCurrentColor = function(editor, format3) {
      var color2;
      editor.dom.getParents(editor.selection.getStart(), function(elm) {
        var value2;
        if (value2 = elm.style[format3 === "forecolor" ? "color" : "background-color"]) {
          color2 = color2 ? color2 : value2;
        }
      });
      return Optional.from(color2);
    };
    var applyFormat = function(editor, format3, value2) {
      editor.undoManager.transact(function() {
        editor.focus();
        editor.formatter.apply(format3, { value: value2 });
        editor.nodeChanged();
      });
    };
    var removeFormat = function(editor, format3) {
      editor.undoManager.transact(function() {
        editor.focus();
        editor.formatter.remove(format3, { value: null }, null, true);
        editor.nodeChanged();
      });
    };
    var registerCommands = function(editor) {
      editor.addCommand("mceApplyTextcolor", function(format3, value2) {
        applyFormat(editor, format3, value2);
      });
      editor.addCommand("mceRemoveTextcolor", function(format3) {
        removeFormat(editor, format3);
      });
    };
    var calcCols = function(colors2) {
      return Math.max(5, Math.ceil(Math.sqrt(colors2)));
    };
    var getColorCols$1 = function(editor) {
      var colors2 = getColors$2(editor);
      var defaultCols = calcCols(colors2.length);
      return getColorCols$2(editor, defaultCols);
    };
    var getAdditionalColors = function(hasCustom) {
      var type2 = "choiceitem";
      var remove2 = {
        type: type2,
        text: "Remove color",
        icon: "color-swatch-remove-color",
        value: "remove"
      };
      var custom2 = {
        type: type2,
        text: "Custom color",
        icon: "color-picker",
        value: "custom"
      };
      return hasCustom ? [
        remove2,
        custom2
      ] : [remove2];
    };
    var applyColor = function(editor, format3, value2, onChoice) {
      if (value2 === "custom") {
        var dialog = colorPickerDialog(editor);
        dialog(function(colorOpt) {
          colorOpt.each(function(color2) {
            addColor(color2);
            editor.execCommand("mceApplyTextcolor", format3, color2);
            onChoice(color2);
          });
        }, fallbackColor);
      } else if (value2 === "remove") {
        onChoice("");
        editor.execCommand("mceRemoveTextcolor", format3);
      } else {
        onChoice(value2);
        editor.execCommand("mceApplyTextcolor", format3, value2);
      }
    };
    var getColors$1 = function(colors2, hasCustom) {
      return colors2.concat(getCurrentColors().concat(getAdditionalColors(hasCustom)));
    };
    var getFetch$1 = function(colors2, hasCustom) {
      return function(callback2) {
        callback2(getColors$1(colors2, hasCustom));
      };
    };
    var setIconColor = function(splitButtonApi, name2, newColor) {
      var id2 = name2 === "forecolor" ? "tox-icon-text-color__color" : "tox-icon-highlight-bg-color__color";
      splitButtonApi.setIconFill(id2, newColor);
    };
    var registerTextColorButton = function(editor, name2, format3, tooltip, lastColor) {
      editor.ui.registry.addSplitButton(name2, {
        tooltip,
        presets: "color",
        icon: name2 === "forecolor" ? "text-color" : "highlight-bg-color",
        select: function(value2) {
          var optCurrentRgb = getCurrentColor(editor, format3);
          return optCurrentRgb.bind(function(currentRgb) {
            return fromString(currentRgb).map(function(rgba) {
              var currentHex = fromRgba(rgba).value;
              return contains$1(value2.toLowerCase(), currentHex);
            });
          }).getOr(false);
        },
        columns: getColorCols$1(editor),
        fetch: getFetch$1(getColors$2(editor), hasCustomColors$1(editor)),
        onAction: function(_splitButtonApi) {
          applyColor(editor, format3, lastColor.get(), noop3);
        },
        onItemAction: function(_splitButtonApi, value2) {
          applyColor(editor, format3, value2, function(newColor) {
            lastColor.set(newColor);
            fireTextColorChange(editor, {
              name: name2,
              color: newColor
            });
          });
        },
        onSetup: function(splitButtonApi) {
          setIconColor(splitButtonApi, name2, lastColor.get());
          var handler = function(e2) {
            if (e2.name === name2) {
              setIconColor(splitButtonApi, e2.name, e2.color);
            }
          };
          editor.on("TextColorChange", handler);
          return function() {
            editor.off("TextColorChange", handler);
          };
        }
      });
    };
    var registerTextColorMenuItem = function(editor, name2, format3, text2) {
      editor.ui.registry.addNestedMenuItem(name2, {
        text: text2,
        icon: name2 === "forecolor" ? "text-color" : "highlight-bg-color",
        getSubmenuItems: function() {
          return [{
            type: "fancymenuitem",
            fancytype: "colorswatch",
            onAction: function(data) {
              applyColor(editor, format3, data.value, noop3);
            }
          }];
        }
      });
    };
    var colorPickerDialog = function(editor) {
      return function(callback2, value2) {
        var isValid2 = false;
        var onSubmit = function(api2) {
          var data = api2.getData();
          var hex2 = data.colorpicker;
          if (isValid2) {
            callback2(Optional.from(hex2));
            api2.close();
          } else {
            editor.windowManager.alert(editor.translate([
              "Invalid hex color code: {0}",
              hex2
            ]));
          }
        };
        var onAction = function(_api, details) {
          if (details.name === "hex-valid") {
            isValid2 = details.value;
          }
        };
        var initialData = { colorpicker: value2 };
        editor.windowManager.open({
          title: "Color Picker",
          size: "normal",
          body: {
            type: "panel",
            items: [{
              type: "colorpicker",
              name: "colorpicker",
              label: "Color"
            }]
          },
          buttons: [
            {
              type: "cancel",
              name: "cancel",
              text: "Cancel"
            },
            {
              type: "submit",
              name: "save",
              text: "Save",
              primary: true
            }
          ],
          initialData,
          onAction,
          onSubmit,
          onClose: noop3,
          onCancel: function() {
            callback2(Optional.none());
          }
        });
      };
    };
    var register$a = function(editor) {
      registerCommands(editor);
      var lastForeColor = Cell(fallbackColor);
      var lastBackColor = Cell(fallbackColor);
      registerTextColorButton(editor, "forecolor", "forecolor", "Text color", lastForeColor);
      registerTextColorButton(editor, "backcolor", "hilitecolor", "Background color", lastBackColor);
      registerTextColorMenuItem(editor, "forecolor", "forecolor", "Text color");
      registerTextColorMenuItem(editor, "backcolor", "hilitecolor", "Background color");
    };
    var createPartialChoiceMenu = function(value2, items, onItemValueHandler, columns, presets, itemResponse, select2, providersBackstage) {
      var hasIcons = menuHasIcons(items);
      var presetItemTypes = presets !== "color" ? "normal" : "color";
      var alloyItems = createChoiceItems(items, onItemValueHandler, columns, presetItemTypes, itemResponse, select2, providersBackstage);
      return createPartialMenuWithAlloyItems(value2, hasIcons, alloyItems, columns, presets);
    };
    var createChoiceItems = function(items, onItemValueHandler, columns, itemPresets, itemResponse, select2, providersBackstage) {
      return cat(map$2(items, function(item2) {
        if (item2.type === "choiceitem") {
          return createChoiceMenuItem(item2).fold(handleError, function(d2) {
            return Optional.some(renderChoiceItem(d2, columns === 1, itemPresets, onItemValueHandler, select2(item2.value), itemResponse, providersBackstage, menuHasIcons(items)));
          });
        } else {
          return Optional.none();
        }
      }));
    };
    var deriveMenuMovement = function(columns, presets) {
      var menuMarkers = markers(presets);
      if (columns === 1) {
        return {
          mode: "menu",
          moveOnTab: true
        };
      } else if (columns === "auto") {
        return {
          mode: "grid",
          selector: "." + menuMarkers.item,
          initSize: {
            numColumns: 1,
            numRows: 1
          }
        };
      } else {
        var rowClass = presets === "color" ? "tox-swatches__row" : "tox-collection__group";
        return {
          mode: "matrix",
          rowSelector: "." + rowClass
        };
      }
    };
    var deriveCollectionMovement = function(columns, presets) {
      if (columns === 1) {
        return {
          mode: "menu",
          moveOnTab: false,
          selector: ".tox-collection__item"
        };
      } else if (columns === "auto") {
        return {
          mode: "flatgrid",
          selector: ".tox-collection__item",
          initSize: {
            numColumns: 1,
            numRows: 1
          }
        };
      } else {
        return {
          mode: "matrix",
          selectors: {
            row: presets === "color" ? ".tox-swatches__row" : ".tox-collection__group",
            cell: presets === "color" ? "." + colorClass : "." + selectableClass
          }
        };
      }
    };
    var renderColorSwatchItem = function(spec, backstage) {
      var items = getColorItems(spec, backstage);
      var columns = backstage.colorinput.getColorCols();
      var presets = "color";
      var menuSpec = createPartialChoiceMenu(generate$6("menu-value"), items, function(value2) {
        spec.onAction({ value: value2 });
      }, columns, presets, ItemResponse$1.CLOSE_ON_EXECUTE, never, backstage.shared.providers);
      var widgetSpec = __assign(__assign({}, menuSpec), {
        markers: markers(presets),
        movement: deriveMenuMovement(columns, presets)
      });
      return {
        type: "widget",
        data: { value: generate$6("widget-id") },
        dom: {
          tag: "div",
          classes: ["tox-fancymenuitem"]
        },
        autofocus: true,
        components: [parts$f.widget(Menu.sketch(widgetSpec))]
      };
    };
    var getColorItems = function(spec, backstage) {
      var useCustomColors = spec.initData.allowCustomColors && backstage.colorinput.hasCustomColors();
      return spec.initData.colors.fold(function() {
        return getColors$1(backstage.colorinput.getColors(), useCustomColors);
      }, function(colors2) {
        return colors2.concat(getAdditionalColors(useCustomColors));
      });
    };
    var cellOverEvent = generate$6("cell-over");
    var cellExecuteEvent = generate$6("cell-execute");
    var makeCell = function(row, col, labelId) {
      var _a2;
      var emitCellOver = function(c2) {
        return emitWith(c2, cellOverEvent, {
          row,
          col
        });
      };
      var emitExecute2 = function(c2) {
        return emitWith(c2, cellExecuteEvent, {
          row,
          col
        });
      };
      var onClick = function(c2, se2) {
        se2.stop();
        emitExecute2(c2);
      };
      return build$1({
        dom: {
          tag: "div",
          attributes: (_a2 = { role: "button" }, _a2["aria-labelledby"] = labelId, _a2)
        },
        behaviours: derive$1([
          config("insert-table-picker-cell", [
            run$1(mouseover(), Focusing.focus),
            run$1(execute$5(), emitExecute2),
            run$1(click(), onClick),
            run$1(tap(), onClick)
          ]),
          Toggling.config({
            toggleClass: "tox-insert-table-picker__selected",
            toggleOnExecute: false
          }),
          Focusing.config({ onFocus: emitCellOver })
        ])
      });
    };
    var makeCells = function(labelId, numRows, numCols) {
      var cells = [];
      for (var i2 = 0; i2 < numRows; i2++) {
        var row = [];
        for (var j2 = 0; j2 < numCols; j2++) {
          row.push(makeCell(i2, j2, labelId));
        }
        cells.push(row);
      }
      return cells;
    };
    var selectCells = function(cells, selectedRow, selectedColumn, numRows, numColumns) {
      for (var i2 = 0; i2 < numRows; i2++) {
        for (var j2 = 0; j2 < numColumns; j2++) {
          Toggling.set(cells[i2][j2], i2 <= selectedRow && j2 <= selectedColumn);
        }
      }
    };
    var makeComponents = function(cells) {
      return bind$3(cells, function(cellRow) {
        return map$2(cellRow, premade);
      });
    };
    var makeLabelText = function(row, col) {
      return text(col + "x" + row);
    };
    var renderInsertTableMenuItem = function(spec) {
      var numRows = 10;
      var numColumns = 10;
      var sizeLabelId = generate$6("size-label");
      var cells = makeCells(sizeLabelId, numRows, numColumns);
      var emptyLabelText = makeLabelText(0, 0);
      var memLabel = record({
        dom: {
          tag: "span",
          classes: ["tox-insert-table-picker__label"],
          attributes: { id: sizeLabelId }
        },
        components: [emptyLabelText],
        behaviours: derive$1([Replacing.config({})])
      });
      return {
        type: "widget",
        data: { value: generate$6("widget-id") },
        dom: {
          tag: "div",
          classes: ["tox-fancymenuitem"]
        },
        autofocus: true,
        components: [parts$f.widget({
          dom: {
            tag: "div",
            classes: ["tox-insert-table-picker"]
          },
          components: makeComponents(cells).concat(memLabel.asSpec()),
          behaviours: derive$1([
            config("insert-table-picker", [
              runOnAttached(function(c2) {
                Replacing.set(memLabel.get(c2), [emptyLabelText]);
              }),
              runWithTarget(cellOverEvent, function(c2, t3, e2) {
                var _a2 = e2.event, row = _a2.row, col = _a2.col;
                selectCells(cells, row, col, numRows, numColumns);
                Replacing.set(memLabel.get(c2), [makeLabelText(row + 1, col + 1)]);
              }),
              runWithTarget(cellExecuteEvent, function(c2, _2, e2) {
                var _a2 = e2.event, row = _a2.row, col = _a2.col;
                spec.onAction({
                  numRows: row + 1,
                  numColumns: col + 1
                });
                emit(c2, sandboxClose());
              })
            ]),
            Keying.config({
              initSize: {
                numRows,
                numColumns
              },
              mode: "flatgrid",
              selector: '[role="button"]'
            })
          ])
        })]
      };
    };
    var fancyMenuItems = {
      inserttable: renderInsertTableMenuItem,
      colorswatch: renderColorSwatchItem
    };
    var renderFancyMenuItem = function(spec, backstage) {
      return get$e(fancyMenuItems, spec.fancytype).map(function(render2) {
        return render2(spec, backstage);
      });
    };
    var renderNestedItem = function(spec, itemResponse, providersBackstage, renderIcons, downwardsCaret) {
      if (renderIcons === void 0) {
        renderIcons = true;
      }
      if (downwardsCaret === void 0) {
        downwardsCaret = false;
      }
      var caret = downwardsCaret ? renderDownwardsCaret(providersBackstage.icons) : renderSubmenuCaret(providersBackstage.icons);
      var getApi2 = function(component) {
        return {
          isDisabled: function() {
            return Disabling.isDisabled(component);
          },
          setDisabled: function(state) {
            return Disabling.set(component, state);
          }
        };
      };
      var structure = renderItemStructure({
        presets: "normal",
        iconContent: spec.icon,
        textContent: spec.text,
        htmlContent: Optional.none(),
        ariaLabel: spec.text,
        caret: Optional.some(caret),
        checkMark: Optional.none(),
        shortcutContent: spec.shortcut
      }, providersBackstage, renderIcons);
      return renderCommonItem({
        data: buildData(spec),
        getApi: getApi2,
        disabled: spec.disabled,
        onAction: noop3,
        onSetup: spec.onSetup,
        triggersSubmenu: true,
        itemBehaviours: []
      }, structure, itemResponse, providersBackstage);
    };
    var renderNormalItem = function(spec, itemResponse, providersBackstage, renderIcons) {
      if (renderIcons === void 0) {
        renderIcons = true;
      }
      var getApi2 = function(component) {
        return {
          isDisabled: function() {
            return Disabling.isDisabled(component);
          },
          setDisabled: function(state) {
            return Disabling.set(component, state);
          }
        };
      };
      var structure = renderItemStructure({
        presets: "normal",
        iconContent: spec.icon,
        textContent: spec.text,
        htmlContent: Optional.none(),
        ariaLabel: spec.text,
        caret: Optional.none(),
        checkMark: Optional.none(),
        shortcutContent: spec.shortcut
      }, providersBackstage, renderIcons);
      return renderCommonItem({
        data: buildData(spec),
        getApi: getApi2,
        disabled: spec.disabled,
        onAction: spec.onAction,
        onSetup: spec.onSetup,
        triggersSubmenu: false,
        itemBehaviours: []
      }, structure, itemResponse, providersBackstage);
    };
    var renderSeparatorItem = function(spec) {
      var innerHtml = spec.text.fold(function() {
        return {};
      }, function(text2) {
        return { innerHtml: text2 };
      });
      return {
        type: "separator",
        dom: __assign({
          tag: "div",
          classes: [
            selectableClass,
            groupHeadingClass
          ]
        }, innerHtml),
        components: []
      };
    };
    var renderToggleMenuItem = function(spec, itemResponse, providersBackstage, renderIcons) {
      if (renderIcons === void 0) {
        renderIcons = true;
      }
      var getApi2 = function(component) {
        return {
          setActive: function(state) {
            Toggling.set(component, state);
          },
          isActive: function() {
            return Toggling.isOn(component);
          },
          isDisabled: function() {
            return Disabling.isDisabled(component);
          },
          setDisabled: function(state) {
            return Disabling.set(component, state);
          }
        };
      };
      var structure = renderItemStructure({
        iconContent: spec.icon,
        textContent: spec.text,
        htmlContent: Optional.none(),
        ariaLabel: spec.text,
        checkMark: Optional.some(renderCheckmark(providersBackstage.icons)),
        caret: Optional.none(),
        shortcutContent: spec.shortcut,
        presets: "normal",
        meta: spec.meta
      }, providersBackstage, renderIcons);
      return deepMerge(renderCommonItem({
        data: buildData(spec),
        disabled: spec.disabled,
        getApi: getApi2,
        onAction: spec.onAction,
        onSetup: spec.onSetup,
        triggersSubmenu: false,
        itemBehaviours: []
      }, structure, itemResponse, providersBackstage), {
        toggling: {
          toggleClass: tickedClass,
          toggleOnExecute: false,
          selected: spec.active
        }
      });
    };
    var autocomplete = renderAutocompleteItem;
    var separator$3 = renderSeparatorItem;
    var normal = renderNormalItem;
    var nested = renderNestedItem;
    var toggle$1 = renderToggleMenuItem;
    var fancy = renderFancyMenuItem;
    var card = renderCardMenuItem;
    var FocusMode;
    (function(FocusMode2) {
      FocusMode2[FocusMode2["ContentFocus"] = 0] = "ContentFocus";
      FocusMode2[FocusMode2["UiFocus"] = 1] = "UiFocus";
    })(FocusMode || (FocusMode = {}));
    var createMenuItemFromBridge = function(item2, itemResponse, backstage, menuHasIcons2, isHorizontalMenu) {
      var providersBackstage = backstage.shared.providers;
      var parseForHorizontalMenu = function(menuitem) {
        return !isHorizontalMenu ? menuitem : __assign(__assign({}, menuitem), {
          shortcut: Optional.none(),
          icon: menuitem.text.isSome() ? Optional.none() : menuitem.icon
        });
      };
      switch (item2.type) {
        case "menuitem":
          return createMenuItem(item2).fold(handleError, function(d2) {
            return Optional.some(normal(parseForHorizontalMenu(d2), itemResponse, providersBackstage, menuHasIcons2));
          });
        case "nestedmenuitem":
          return createNestedMenuItem(item2).fold(handleError, function(d2) {
            return Optional.some(nested(parseForHorizontalMenu(d2), itemResponse, providersBackstage, menuHasIcons2, isHorizontalMenu));
          });
        case "togglemenuitem":
          return createToggleMenuItem(item2).fold(handleError, function(d2) {
            return Optional.some(toggle$1(parseForHorizontalMenu(d2), itemResponse, providersBackstage, menuHasIcons2));
          });
        case "separator":
          return createSeparatorMenuItem(item2).fold(handleError, function(d2) {
            return Optional.some(separator$3(d2));
          });
        case "fancymenuitem":
          return createFancyMenuItem(item2).fold(handleError, function(d2) {
            return fancy(parseForHorizontalMenu(d2), backstage);
          });
        default: {
          console.error("Unknown item in general menu", item2);
          return Optional.none();
        }
      }
    };
    var createAutocompleteItems = function(items, matchText, onItemValueHandler, columns, itemResponse, sharedBackstage, highlightOn) {
      var renderText3 = columns === 1;
      var renderIcons = !renderText3 || menuHasIcons(items);
      return cat(map$2(items, function(item2) {
        switch (item2.type) {
          case "separator":
            return createSeparatorItem(item2).fold(handleError, function(d2) {
              return Optional.some(separator$3(d2));
            });
          case "cardmenuitem":
            return createCardMenuItem(item2).fold(handleError, function(d2) {
              return Optional.some(card(__assign(__assign({}, d2), {
                onAction: function(api2) {
                  d2.onAction(api2);
                  onItemValueHandler(d2.value, d2.meta);
                }
              }), itemResponse, sharedBackstage, {
                itemBehaviours: tooltipBehaviour(d2.meta, sharedBackstage),
                cardText: {
                  matchText,
                  highlightOn
                }
              }));
            });
          case "autocompleteitem":
          default:
            return createAutocompleterItem(item2).fold(handleError, function(d2) {
              return Optional.some(autocomplete(d2, matchText, renderText3, "normal", onItemValueHandler, itemResponse, sharedBackstage, renderIcons));
            });
        }
      }));
    };
    var createPartialMenu = function(value2, items, itemResponse, backstage, isHorizontalMenu) {
      var hasIcons = menuHasIcons(items);
      var alloyItems = cat(map$2(items, function(item2) {
        var itemHasIcon = function(i2) {
          return isHorizontalMenu ? !has$2(i2, "text") : hasIcons;
        };
        var createItem = function(i2) {
          return createMenuItemFromBridge(i2, itemResponse, backstage, itemHasIcon(i2), isHorizontalMenu);
        };
        if (item2.type === "nestedmenuitem" && item2.getSubmenuItems().length <= 0) {
          return createItem(__assign(__assign({}, item2), { disabled: true }));
        } else {
          return createItem(item2);
        }
      }));
      var createPartial = isHorizontalMenu ? createHorizontalPartialMenuWithAlloyItems : createPartialMenuWithAlloyItems;
      return createPartial(value2, hasIcons, alloyItems, 1, "normal");
    };
    var createTieredDataFrom = function(partialMenu) {
      return tieredMenu.singleData(partialMenu.value, partialMenu);
    };
    var createMenuFrom = function(partialMenu, columns, focusMode, presets) {
      var focusManager = focusMode === FocusMode.ContentFocus ? highlights() : dom$2();
      var movement = deriveMenuMovement(columns, presets);
      var menuMarkers = markers(presets);
      return {
        dom: partialMenu.dom,
        components: partialMenu.components,
        items: partialMenu.items,
        value: partialMenu.value,
        markers: {
          selectedItem: menuMarkers.selectedItem,
          item: menuMarkers.item
        },
        movement,
        fakeFocus: focusMode === FocusMode.ContentFocus,
        focusManager,
        menuBehaviours: SimpleBehaviours.unnamedEvents(columns !== "auto" ? [] : [runOnAttached(function(comp, _se) {
          detectSize(comp, 4, menuMarkers.item).each(function(_a2) {
            var numColumns = _a2.numColumns, numRows = _a2.numRows;
            Keying.setGridSize(comp, numRows, numColumns);
          });
        })])
      };
    };
    var register$9 = function(editor, sharedBackstage) {
      var activeAutocompleter = value$1();
      var processingAction = Cell(false);
      var autocompleter = build$1(InlineView.sketch({
        dom: {
          tag: "div",
          classes: ["tox-autocompleter"]
        },
        components: [],
        fireDismissalEventInstead: {},
        inlineBehaviours: derive$1([config("dismissAutocompleter", [run$1(dismissRequested(), function() {
          return cancelIfNecessary();
        })])]),
        lazySink: sharedBackstage.getSink
      }));
      var isMenuOpen = function() {
        return InlineView.isOpen(autocompleter);
      };
      var isActive = function() {
        return activeAutocompleter.get().isSome();
      };
      var hideIfNecessary = function() {
        if (isActive()) {
          InlineView.hide(autocompleter);
        }
      };
      var cancelIfNecessary = function() {
        if (isActive()) {
          var lastElement = activeAutocompleter.get().map(function(ac) {
            return ac.element;
          });
          detect(lastElement.getOr(SugarElement.fromDom(editor.selection.getNode()))).each(unwrap);
          hideIfNecessary();
          activeAutocompleter.clear();
          processingAction.set(false);
        }
      };
      var getAutocompleters = cached(function() {
        return register$b(editor);
      });
      var getCombinedItems = function(triggerChar, matches) {
        var columns = findMap(matches, function(m2) {
          return Optional.from(m2.columns);
        }).getOr(1);
        return bind$3(matches, function(match2) {
          var choices = match2.items;
          return createAutocompleteItems(choices, match2.matchText, function(itemValue, itemMeta) {
            var nr = editor.selection.getRng();
            getContext(editor.dom, nr, triggerChar).fold(function() {
              return console.error("Lost context. Cursor probably moved");
            }, function(_a2) {
              var range2 = _a2.range;
              var autocompleterApi = {
                hide: function() {
                  cancelIfNecessary();
                },
                reload: function(fetchOptions) {
                  hideIfNecessary();
                  load(fetchOptions);
                }
              };
              processingAction.set(true);
              match2.onAction(autocompleterApi, range2, itemValue, itemMeta);
              processingAction.set(false);
            });
          }, columns, ItemResponse$1.BUBBLE_TO_SANDBOX, sharedBackstage, match2.highlightOn);
        });
      };
      var commenceIfNecessary = function(context) {
        if (!isActive()) {
          var wrapper = create$4(editor, context.range);
          activeAutocompleter.set({
            triggerChar: context.triggerChar,
            element: wrapper,
            matchLength: context.text.length
          });
          processingAction.set(false);
        }
      };
      var display = function(ac, context, lookupData, items) {
        ac.matchLength = context.text.length;
        var columns = findMap(lookupData, function(ld) {
          return Optional.from(ld.columns);
        }).getOr(1);
        InlineView.showAt(autocompleter, Menu.sketch(createMenuFrom(createPartialMenuWithAlloyItems("autocompleter-value", true, items, columns, "normal"), columns, FocusMode.ContentFocus, "normal")), {
          anchor: {
            type: "node",
            root: SugarElement.fromDom(editor.getBody()),
            node: Optional.from(ac.element)
          }
        });
        InlineView.getContent(autocompleter).each(Highlighting.highlightFirst);
      };
      var doLookup = function(fetchOptions) {
        return activeAutocompleter.get().map(function(ac) {
          return getContext(editor.dom, editor.selection.getRng(), ac.triggerChar).bind(function(newContext) {
            return lookupWithContext(editor, getAutocompleters, newContext, fetchOptions);
          });
        }).getOrThunk(function() {
          return lookup$2(editor, getAutocompleters);
        });
      };
      var load = function(fetchOptions) {
        doLookup(fetchOptions).fold(cancelIfNecessary, function(lookupInfo) {
          commenceIfNecessary(lookupInfo.context);
          lookupInfo.lookupData.then(function(lookupData) {
            activeAutocompleter.get().map(function(ac) {
              var context = lookupInfo.context;
              if (ac.triggerChar === context.triggerChar) {
                var combinedItems = getCombinedItems(context.triggerChar, lookupData);
                if (combinedItems.length > 0) {
                  display(ac, context, lookupData, combinedItems);
                } else if (context.text.length - ac.matchLength >= 10) {
                  cancelIfNecessary();
                } else {
                  hideIfNecessary();
                }
              }
            });
          });
        });
      };
      var onKeypress = last(function(e2) {
        if (e2.which === 27) {
          return;
        }
        load();
      }, 50);
      var autocompleterUiApi = {
        onKeypress,
        cancelIfNecessary,
        isMenuOpen,
        isActive,
        isProcessingAction: processingAction.get,
        getView: function() {
          return InlineView.getContent(autocompleter);
        }
      };
      if (editor.hasPlugin("rtc") === false) {
        AutocompleterEditorEvents.setup(autocompleterUiApi, editor);
      }
    };
    var Autocompleter = { register: register$9 };
    var closest = function(scope, selector, isRoot) {
      return closest$1(scope, selector, isRoot).isSome();
    };
    var DelayedFunction = function(fun, delay) {
      var ref = null;
      var schedule = function() {
        var args = [];
        for (var _i2 = 0; _i2 < arguments.length; _i2++) {
          args[_i2] = arguments[_i2];
        }
        ref = setTimeout(function() {
          fun.apply(null, args);
          ref = null;
        }, delay);
      };
      var cancel = function() {
        if (ref !== null) {
          clearTimeout(ref);
          ref = null;
        }
      };
      return {
        cancel,
        schedule
      };
    };
    var SIGNIFICANT_MOVE = 5;
    var LONGPRESS_DELAY = 400;
    var getTouch = function(event) {
      var raw = event.raw;
      if (raw.touches === void 0 || raw.touches.length !== 1) {
        return Optional.none();
      }
      return Optional.some(raw.touches[0]);
    };
    var isFarEnough = function(touch2, data) {
      var distX = Math.abs(touch2.clientX - data.x);
      var distY = Math.abs(touch2.clientY - data.y);
      return distX > SIGNIFICANT_MOVE || distY > SIGNIFICANT_MOVE;
    };
    var monitor = function(settings) {
      var startData = value$1();
      var longpressFired = Cell(false);
      var longpress$1 = DelayedFunction(function(event) {
        settings.triggerEvent(longpress(), event);
        longpressFired.set(true);
      }, LONGPRESS_DELAY);
      var handleTouchstart = function(event) {
        getTouch(event).each(function(touch2) {
          longpress$1.cancel();
          var data = {
            x: touch2.clientX,
            y: touch2.clientY,
            target: event.target
          };
          longpress$1.schedule(event);
          longpressFired.set(false);
          startData.set(data);
        });
        return Optional.none();
      };
      var handleTouchmove = function(event) {
        longpress$1.cancel();
        getTouch(event).each(function(touch2) {
          startData.on(function(data) {
            if (isFarEnough(touch2, data)) {
              startData.clear();
            }
          });
        });
        return Optional.none();
      };
      var handleTouchend = function(event) {
        longpress$1.cancel();
        var isSame = function(data) {
          return eq2(data.target, event.target);
        };
        return startData.get().filter(isSame).map(function(_data) {
          if (longpressFired.get()) {
            event.prevent();
            return false;
          } else {
            return settings.triggerEvent(tap(), event);
          }
        });
      };
      var handlers2 = wrapAll([
        {
          key: touchstart(),
          value: handleTouchstart
        },
        {
          key: touchmove(),
          value: handleTouchmove
        },
        {
          key: touchend(),
          value: handleTouchend
        }
      ]);
      var fireIfReady = function(event, type2) {
        return get$e(handlers2, type2).bind(function(handler) {
          return handler(event);
        });
      };
      return { fireIfReady };
    };
    var isDangerous = function(event) {
      var keyEv = event.raw;
      return keyEv.which === BACKSPACE[0] && !contains$2([
        "input",
        "textarea"
      ], name$2(event.target)) && !closest(event.target, '[contenteditable="true"]');
    };
    var isFirefox = function() {
      return detect$1().browser.isFirefox();
    };
    var bindFocus = function(container, handler) {
      if (isFirefox()) {
        return capture(container, "focus", handler);
      } else {
        return bind(container, "focusin", handler);
      }
    };
    var bindBlur = function(container, handler) {
      if (isFirefox()) {
        return capture(container, "blur", handler);
      } else {
        return bind(container, "focusout", handler);
      }
    };
    var setup$d = function(container, rawSettings) {
      var settings = __assign({ stopBackspace: true }, rawSettings);
      var pointerEvents2 = [
        "touchstart",
        "touchmove",
        "touchend",
        "touchcancel",
        "gesturestart",
        "mousedown",
        "mouseup",
        "mouseover",
        "mousemove",
        "mouseout",
        "click"
      ];
      var tapEvent = monitor(settings);
      var simpleEvents = map$2(pointerEvents2.concat([
        "selectstart",
        "input",
        "contextmenu",
        "change",
        "transitionend",
        "transitioncancel",
        "drag",
        "dragstart",
        "dragend",
        "dragenter",
        "dragleave",
        "dragover",
        "drop",
        "keyup"
      ]), function(type2) {
        return bind(container, type2, function(event) {
          tapEvent.fireIfReady(event, type2).each(function(tapStopped) {
            if (tapStopped) {
              event.kill();
            }
          });
          var stopped = settings.triggerEvent(type2, event);
          if (stopped) {
            event.kill();
          }
        });
      });
      var pasteTimeout = value$1();
      var onPaste = bind(container, "paste", function(event) {
        tapEvent.fireIfReady(event, "paste").each(function(tapStopped) {
          if (tapStopped) {
            event.kill();
          }
        });
        var stopped = settings.triggerEvent("paste", event);
        if (stopped) {
          event.kill();
        }
        pasteTimeout.set(setTimeout(function() {
          settings.triggerEvent(postPaste(), event);
        }, 0));
      });
      var onKeydown = bind(container, "keydown", function(event) {
        var stopped = settings.triggerEvent("keydown", event);
        if (stopped) {
          event.kill();
        } else if (settings.stopBackspace && isDangerous(event)) {
          event.prevent();
        }
      });
      var onFocusIn = bindFocus(container, function(event) {
        var stopped = settings.triggerEvent("focusin", event);
        if (stopped) {
          event.kill();
        }
      });
      var focusoutTimeout = value$1();
      var onFocusOut = bindBlur(container, function(event) {
        var stopped = settings.triggerEvent("focusout", event);
        if (stopped) {
          event.kill();
        }
        focusoutTimeout.set(setTimeout(function() {
          settings.triggerEvent(postBlur(), event);
        }, 0));
      });
      var unbind2 = function() {
        each$1(simpleEvents, function(e2) {
          e2.unbind();
        });
        onKeydown.unbind();
        onFocusIn.unbind();
        onFocusOut.unbind();
        onPaste.unbind();
        pasteTimeout.on(clearTimeout);
        focusoutTimeout.on(clearTimeout);
      };
      return { unbind: unbind2 };
    };
    var derive = function(rawEvent, rawTarget) {
      var source = get$e(rawEvent, "target").getOr(rawTarget);
      return Cell(source);
    };
    var fromSource = function(event, source) {
      var stopper2 = Cell(false);
      var cutter2 = Cell(false);
      var stop2 = function() {
        stopper2.set(true);
      };
      var cut = function() {
        cutter2.set(true);
      };
      return {
        stop: stop2,
        cut,
        isStopped: stopper2.get,
        isCut: cutter2.get,
        event,
        setSource: source.set,
        getSource: source.get
      };
    };
    var fromExternal = function(event) {
      var stopper2 = Cell(false);
      var stop2 = function() {
        stopper2.set(true);
      };
      return {
        stop: stop2,
        cut: noop3,
        isStopped: stopper2.get,
        isCut: never,
        event,
        setSource: die("Cannot set source of a broadcasted event"),
        getSource: die("Cannot get source of a broadcasted event")
      };
    };
    var adt$1 = Adt.generate([
      { stopped: [] },
      { resume: ["element"] },
      { complete: [] }
    ]);
    var doTriggerHandler = function(lookup2, eventType, rawEvent, target, source, logger) {
      var handler = lookup2(eventType, target);
      var simulatedEvent = fromSource(rawEvent, source);
      return handler.fold(function() {
        logger.logEventNoHandlers(eventType, target);
        return adt$1.complete();
      }, function(handlerInfo) {
        var descHandler = handlerInfo.descHandler;
        var eventHandler2 = getCurried(descHandler);
        eventHandler2(simulatedEvent);
        if (simulatedEvent.isStopped()) {
          logger.logEventStopped(eventType, handlerInfo.element, descHandler.purpose);
          return adt$1.stopped();
        } else if (simulatedEvent.isCut()) {
          logger.logEventCut(eventType, handlerInfo.element, descHandler.purpose);
          return adt$1.complete();
        } else {
          return parent(handlerInfo.element).fold(function() {
            logger.logNoParent(eventType, handlerInfo.element, descHandler.purpose);
            return adt$1.complete();
          }, function(parent2) {
            logger.logEventResponse(eventType, handlerInfo.element, descHandler.purpose);
            return adt$1.resume(parent2);
          });
        }
      });
    };
    var doTriggerOnUntilStopped = function(lookup2, eventType, rawEvent, rawTarget, source, logger) {
      return doTriggerHandler(lookup2, eventType, rawEvent, rawTarget, source, logger).fold(always, function(parent2) {
        return doTriggerOnUntilStopped(lookup2, eventType, rawEvent, parent2, source, logger);
      }, never);
    };
    var triggerHandler = function(lookup2, eventType, rawEvent, target, logger) {
      var source = derive(rawEvent, target);
      return doTriggerHandler(lookup2, eventType, rawEvent, target, source, logger);
    };
    var broadcast = function(listeners, rawEvent, _logger) {
      var simulatedEvent = fromExternal(rawEvent);
      each$1(listeners, function(listener) {
        var descHandler = listener.descHandler;
        var handler = getCurried(descHandler);
        handler(simulatedEvent);
      });
      return simulatedEvent.isStopped();
    };
    var triggerUntilStopped = function(lookup2, eventType, rawEvent, logger) {
      return triggerOnUntilStopped(lookup2, eventType, rawEvent, rawEvent.target, logger);
    };
    var triggerOnUntilStopped = function(lookup2, eventType, rawEvent, rawTarget, logger) {
      var source = derive(rawEvent, rawTarget);
      return doTriggerOnUntilStopped(lookup2, eventType, rawEvent, rawTarget, source, logger);
    };
    var eventHandler = function(element2, descHandler) {
      return {
        element: element2,
        descHandler
      };
    };
    var broadcastHandler = function(id2, handler) {
      return {
        id: id2,
        descHandler: handler
      };
    };
    var EventRegistry = function() {
      var registry2 = {};
      var registerId = function(extraArgs, id2, events2) {
        each2(events2, function(v2, k2) {
          var handlers2 = registry2[k2] !== void 0 ? registry2[k2] : {};
          handlers2[id2] = curryArgs(v2, extraArgs);
          registry2[k2] = handlers2;
        });
      };
      var findHandler2 = function(handlers2, elem) {
        return read$1(elem).bind(function(id2) {
          return get$e(handlers2, id2);
        }).map(function(descHandler) {
          return eventHandler(elem, descHandler);
        });
      };
      var filterByType = function(type2) {
        return get$e(registry2, type2).map(function(handlers2) {
          return mapToArray(handlers2, function(f2, id2) {
            return broadcastHandler(id2, f2);
          });
        }).getOr([]);
      };
      var find2 = function(isAboveRoot, type2, target) {
        return get$e(registry2, type2).bind(function(handlers2) {
          return closest$4(target, function(elem) {
            return findHandler2(handlers2, elem);
          }, isAboveRoot);
        });
      };
      var unregisterId = function(id2) {
        each2(registry2, function(handlersById, _eventName) {
          if (has$2(handlersById, id2)) {
            delete handlersById[id2];
          }
        });
      };
      return {
        registerId,
        unregisterId,
        filterByType,
        find: find2
      };
    };
    var Registry2 = function() {
      var events2 = EventRegistry();
      var components2 = {};
      var readOrTag = function(component) {
        var elem = component.element;
        return read$1(elem).getOrThunk(function() {
          return write2("uid-", component.element);
        });
      };
      var failOnDuplicate = function(component, tagId) {
        var conflict = components2[tagId];
        if (conflict === component) {
          unregister(component);
        } else {
          throw new Error('The tagId "' + tagId + '" is already used by: ' + element(conflict.element) + "\nCannot use it for: " + element(component.element) + "\nThe conflicting element is" + (inBody(conflict.element) ? " " : " not ") + "already in the DOM");
        }
      };
      var register2 = function(component) {
        var tagId = readOrTag(component);
        if (hasNonNullableKey(components2, tagId)) {
          failOnDuplicate(component, tagId);
        }
        var extraArgs = [component];
        events2.registerId(extraArgs, tagId, component.events);
        components2[tagId] = component;
      };
      var unregister = function(component) {
        read$1(component.element).each(function(tagId) {
          delete components2[tagId];
          events2.unregisterId(tagId);
        });
      };
      var filter2 = function(type2) {
        return events2.filterByType(type2);
      };
      var find2 = function(isAboveRoot, type2, target) {
        return events2.find(isAboveRoot, type2, target);
      };
      var getById = function(id2) {
        return get$e(components2, id2);
      };
      return {
        find: find2,
        filter: filter2,
        register: register2,
        unregister,
        getById
      };
    };
    var factory$j = function(detail) {
      var _a2 = detail.dom, attributes = _a2.attributes, domWithoutAttributes = __rest(_a2, ["attributes"]);
      return {
        uid: detail.uid,
        dom: __assign({
          tag: "div",
          attributes: __assign({ role: "presentation" }, attributes)
        }, domWithoutAttributes),
        components: detail.components,
        behaviours: get$2(detail.containerBehaviours),
        events: detail.events,
        domModification: detail.domModification,
        eventOrder: detail.eventOrder
      };
    };
    var Container = single({
      name: "Container",
      factory: factory$j,
      configFields: [
        defaulted("components", []),
        field("containerBehaviours", []),
        defaulted("events", {}),
        defaulted("domModification", {}),
        defaulted("eventOrder", {})
      ]
    });
    var takeover = function(root) {
      var isAboveRoot = function(el) {
        return parent(root.element).fold(always, function(parent2) {
          return eq2(el, parent2);
        });
      };
      var registry2 = Registry2();
      var lookup2 = function(eventName, target) {
        return registry2.find(isAboveRoot, eventName, target);
      };
      var domEvents = setup$d(root.element, {
        triggerEvent: function(eventName, event) {
          return monitorEvent(eventName, event.target, function(logger) {
            return triggerUntilStopped(lookup2, eventName, event, logger);
          });
        }
      });
      var systemApi = {
        debugInfo: constant$1("real"),
        triggerEvent: function(eventName, target, data) {
          monitorEvent(eventName, target, function(logger) {
            return triggerOnUntilStopped(lookup2, eventName, data, target, logger);
          });
        },
        triggerFocus: function(target, originator) {
          read$1(target).fold(function() {
            focus$3(target);
          }, function(_alloyId) {
            monitorEvent(focus$4(), target, function(logger) {
              triggerHandler(lookup2, focus$4(), {
                originator,
                kill: noop3,
                prevent: noop3,
                target
              }, target, logger);
              return false;
            });
          });
        },
        triggerEscape: function(comp, simulatedEvent) {
          systemApi.triggerEvent("keydown", comp.element, simulatedEvent.event);
        },
        getByUid: function(uid2) {
          return getByUid(uid2);
        },
        getByDom: function(elem) {
          return getByDom(elem);
        },
        build: build$1,
        addToGui: function(c2) {
          add4(c2);
        },
        removeFromGui: function(c2) {
          remove2(c2);
        },
        addToWorld: function(c2) {
          addToWorld(c2);
        },
        removeFromWorld: function(c2) {
          removeFromWorld(c2);
        },
        broadcast: function(message) {
          broadcast$1(message);
        },
        broadcastOn: function(channels, message) {
          broadcastOn(channels, message);
        },
        broadcastEvent: function(eventName, event) {
          broadcastEvent(eventName, event);
        },
        isConnected: always
      };
      var addToWorld = function(component) {
        component.connect(systemApi);
        if (!isText$1(component.element)) {
          registry2.register(component);
          each$1(component.components(), addToWorld);
          systemApi.triggerEvent(systemInit(), component.element, { target: component.element });
        }
      };
      var removeFromWorld = function(component) {
        if (!isText$1(component.element)) {
          each$1(component.components(), removeFromWorld);
          registry2.unregister(component);
        }
        component.disconnect();
      };
      var add4 = function(component) {
        attach(root, component);
      };
      var remove2 = function(component) {
        detach(component);
      };
      var destroy = function() {
        domEvents.unbind();
        remove$5(root.element);
      };
      var broadcastData = function(data) {
        var receivers = registry2.filter(receive());
        each$1(receivers, function(receiver) {
          var descHandler = receiver.descHandler;
          var handler = getCurried(descHandler);
          handler(data);
        });
      };
      var broadcast$1 = function(message) {
        broadcastData({
          universal: true,
          data: message
        });
      };
      var broadcastOn = function(channels, message) {
        broadcastData({
          universal: false,
          channels,
          data: message
        });
      };
      var broadcastEvent = function(eventName, event) {
        var listeners = registry2.filter(eventName);
        return broadcast(listeners, event);
      };
      var getByUid = function(uid2) {
        return registry2.getById(uid2).fold(function() {
          return Result.error(new Error('Could not find component with uid: "' + uid2 + '" in system.'));
        }, Result.value);
      };
      var getByDom = function(elem) {
        var uid2 = read$1(elem).getOr("not found");
        return getByUid(uid2);
      };
      addToWorld(root);
      return {
        root,
        element: root.element,
        destroy,
        add: add4,
        remove: remove2,
        getByUid,
        getByDom,
        addToWorld,
        removeFromWorld,
        broadcast: broadcast$1,
        broadcastOn,
        broadcastEvent
      };
    };
    var renderBar = function(spec, backstage) {
      return {
        dom: {
          tag: "div",
          classes: [
            "tox-bar",
            "tox-form__controls-h-stack"
          ]
        },
        components: map$2(spec.items, backstage.interpreter)
      };
    };
    var schema$l = constant$1([
      defaulted("prefix", "form-field"),
      field("fieldBehaviours", [
        Composing,
        Representing
      ])
    ]);
    var parts$e = constant$1([
      optional({
        schema: [required$1("dom")],
        name: "label"
      }),
      optional({
        factory: {
          sketch: function(spec) {
            return {
              uid: spec.uid,
              dom: {
                tag: "span",
                styles: { display: "none" },
                attributes: { "aria-hidden": "true" },
                innerHtml: spec.text
              }
            };
          }
        },
        schema: [required$1("text")],
        name: "aria-descriptor"
      }),
      required({
        factory: {
          sketch: function(spec) {
            var excludeFactory = exclude(spec, ["factory"]);
            return spec.factory.sketch(excludeFactory);
          }
        },
        schema: [required$1("factory")],
        name: "field"
      })
    ]);
    var factory$i = function(detail, components2, _spec, _externals) {
      var behaviours2 = augment(detail.fieldBehaviours, [
        Composing.config({
          find: function(container) {
            return getPart(container, detail, "field");
          }
        }),
        Representing.config({
          store: {
            mode: "manual",
            getValue: function(field2) {
              return Composing.getCurrent(field2).bind(Representing.getValue);
            },
            setValue: function(field2, value2) {
              Composing.getCurrent(field2).each(function(current) {
                Representing.setValue(current, value2);
              });
            }
          }
        })
      ]);
      var events2 = derive$2([runOnAttached(function(component, _simulatedEvent) {
        var ps = getParts(component, detail, [
          "label",
          "field",
          "aria-descriptor"
        ]);
        ps.field().each(function(field2) {
          var id2 = generate$6(detail.prefix);
          ps.label().each(function(label) {
            set$8(label.element, "for", id2);
            set$8(field2.element, "id", id2);
          });
          ps["aria-descriptor"]().each(function(descriptor) {
            var descriptorId = generate$6(detail.prefix);
            set$8(descriptor.element, "id", descriptorId);
            set$8(field2.element, "aria-describedby", descriptorId);
          });
        });
      })]);
      var apis = {
        getField: function(container) {
          return getPart(container, detail, "field");
        },
        getLabel: function(container) {
          return getPart(container, detail, "label");
        }
      };
      return {
        uid: detail.uid,
        dom: detail.dom,
        components: components2,
        behaviours: behaviours2,
        events: events2,
        apis
      };
    };
    var FormField = composite({
      name: "FormField",
      configFields: schema$l(),
      partFields: parts$e(),
      factory: factory$i,
      apis: {
        getField: function(apis, comp) {
          return apis.getField(comp);
        },
        getLabel: function(apis, comp) {
          return apis.getLabel(comp);
        }
      }
    });
    var exhibit$2 = function(base2, tabConfig) {
      return nu$7({
        attributes: wrapAll([{
          key: tabConfig.tabAttr,
          value: "true"
        }])
      });
    };
    var ActiveTabstopping = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      exhibit: exhibit$2
    });
    var TabstopSchema = [defaulted("tabAttr", "data-alloy-tabstop")];
    var Tabstopping = create$7({
      fields: TabstopSchema,
      name: "tabstopping",
      active: ActiveTabstopping
    });
    var global$7 = tinymce.util.Tools.resolve("tinymce.html.Entities");
    var renderFormFieldWith = function(pLabel, pField, extraClasses, extraBehaviours) {
      var spec = renderFormFieldSpecWith(pLabel, pField, extraClasses, extraBehaviours);
      return FormField.sketch(spec);
    };
    var renderFormField = function(pLabel, pField) {
      return renderFormFieldWith(pLabel, pField, [], []);
    };
    var renderFormFieldSpecWith = function(pLabel, pField, extraClasses, extraBehaviours) {
      return {
        dom: renderFormFieldDomWith(extraClasses),
        components: pLabel.toArray().concat([pField]),
        fieldBehaviours: derive$1(extraBehaviours)
      };
    };
    var renderFormFieldDom = function() {
      return renderFormFieldDomWith([]);
    };
    var renderFormFieldDomWith = function(extraClasses) {
      return {
        tag: "div",
        classes: ["tox-form__group"].concat(extraClasses)
      };
    };
    var renderLabel$2 = function(label, providersBackstage) {
      return FormField.parts.label({
        dom: {
          tag: "label",
          classes: ["tox-label"],
          innerHtml: providersBackstage.translate(label)
        }
      });
    };
    var formChangeEvent = generate$6("form-component-change");
    var formCloseEvent = generate$6("form-close");
    var formCancelEvent = generate$6("form-cancel");
    var formActionEvent = generate$6("form-action");
    var formSubmitEvent = generate$6("form-submit");
    var formBlockEvent = generate$6("form-block");
    var formUnblockEvent = generate$6("form-unblock");
    var formTabChangeEvent = generate$6("form-tabchange");
    var formResizeEvent = generate$6("form-resize");
    var renderCollection = function(spec, providersBackstage) {
      var _a2;
      var pLabel = spec.label.map(function(label) {
        return renderLabel$2(label, providersBackstage);
      });
      var runOnItem = function(f2) {
        return function(comp, se2) {
          closest$1(se2.event.target, "[data-collection-item-value]").each(function(target) {
            f2(comp, se2, target, get$d(target, "data-collection-item-value"));
          });
        };
      };
      var setContents = function(comp, items) {
        var htmlLines = map$2(items, function(item2) {
          var itemText = global$e.translate(item2.text);
          var textContent = spec.columns === 1 ? '<div class="tox-collection__item-label">' + itemText + "</div>" : "";
          var iconContent = '<div class="tox-collection__item-icon">' + item2.icon + "</div>";
          var mapItemName = {
            "_": " ",
            " - ": " ",
            "-": " "
          };
          var ariaLabel = itemText.replace(/\_| \- |\-/g, function(match2) {
            return mapItemName[match2];
          });
          var disabledClass = providersBackstage.isDisabled() ? " tox-collection__item--state-disabled" : "";
          return '<div class="tox-collection__item' + disabledClass + '" tabindex="-1" data-collection-item-value="' + global$7.encodeAllRaw(item2.value) + '" title="' + ariaLabel + '" aria-label="' + ariaLabel + '">' + iconContent + textContent + "</div>";
        });
        var chunks = spec.columns !== "auto" && spec.columns > 1 ? chunk$1(htmlLines, spec.columns) : [htmlLines];
        var html = map$2(chunks, function(ch) {
          return '<div class="tox-collection__group">' + ch.join("") + "</div>";
        });
        set$5(comp.element, html.join(""));
      };
      var onClick = runOnItem(function(comp, se2, tgt, itemValue) {
        se2.stop();
        if (!providersBackstage.isDisabled()) {
          emitWith(comp, formActionEvent, {
            name: spec.name,
            value: itemValue
          });
        }
      });
      var collectionEvents = [
        run$1(mouseover(), runOnItem(function(comp, se2, tgt) {
          focus$3(tgt);
        })),
        run$1(click(), onClick),
        run$1(tap(), onClick),
        run$1(focusin(), runOnItem(function(comp, se2, tgt) {
          descendant(comp.element, "." + activeClass).each(function(currentActive) {
            remove$2(currentActive, activeClass);
          });
          add$2(tgt, activeClass);
        })),
        run$1(focusout(), runOnItem(function(comp) {
          descendant(comp.element, "." + activeClass).each(function(currentActive) {
            remove$2(currentActive, activeClass);
          });
        })),
        runOnExecute$1(runOnItem(function(comp, se2, tgt, itemValue) {
          emitWith(comp, formActionEvent, {
            name: spec.name,
            value: itemValue
          });
        }))
      ];
      var iterCollectionItems = function(comp, applyAttributes) {
        return map$2(descendants(comp.element, ".tox-collection__item"), applyAttributes);
      };
      var pField = FormField.parts.field({
        dom: {
          tag: "div",
          classes: ["tox-collection"].concat(spec.columns !== 1 ? ["tox-collection--grid"] : ["tox-collection--list"])
        },
        components: [],
        factory: { sketch: identity$1 },
        behaviours: derive$1([
          Disabling.config({
            disabled: providersBackstage.isDisabled,
            onDisabled: function(comp) {
              iterCollectionItems(comp, function(childElm) {
                add$2(childElm, "tox-collection__item--state-disabled");
                set$8(childElm, "aria-disabled", true);
              });
            },
            onEnabled: function(comp) {
              iterCollectionItems(comp, function(childElm) {
                remove$2(childElm, "tox-collection__item--state-disabled");
                remove$7(childElm, "aria-disabled");
              });
            }
          }),
          receivingConfig(),
          Replacing.config({}),
          Representing.config({
            store: {
              mode: "memory",
              initialValue: []
            },
            onSetValue: function(comp, items) {
              setContents(comp, items);
              if (spec.columns === "auto") {
                detectSize(comp, 5, "tox-collection__item").each(function(_a3) {
                  var numRows = _a3.numRows, numColumns = _a3.numColumns;
                  Keying.setGridSize(comp, numRows, numColumns);
                });
              }
              emit(comp, formResizeEvent);
            }
          }),
          Tabstopping.config({}),
          Keying.config(deriveCollectionMovement(spec.columns, "normal")),
          config("collection-events", collectionEvents)
        ]),
        eventOrder: (_a2 = {}, _a2[execute$5()] = [
          "disabling",
          "alloy.base.behaviour",
          "collection-events"
        ], _a2)
      });
      var extraClasses = ["tox-form__group--collection"];
      return renderFormFieldWith(pLabel, pField, extraClasses, []);
    };
    var schema$k = constant$1([
      option("data"),
      defaulted("inputAttributes", {}),
      defaulted("inputStyles", {}),
      defaulted("tag", "input"),
      defaulted("inputClasses", []),
      onHandler("onSetValue"),
      defaulted("styles", {}),
      defaulted("eventOrder", {}),
      field("inputBehaviours", [
        Representing,
        Focusing
      ]),
      defaulted("selectOnFocus", true)
    ]);
    var focusBehaviours = function(detail) {
      return derive$1([Focusing.config({
        onFocus: !detail.selectOnFocus ? noop3 : function(component) {
          var input2 = component.element;
          var value2 = get$5(input2);
          input2.dom.setSelectionRange(0, value2.length);
        }
      })]);
    };
    var behaviours = function(detail) {
      return __assign(__assign({}, focusBehaviours(detail)), augment(detail.inputBehaviours, [Representing.config({
        store: __assign(__assign({ mode: "manual" }, detail.data.map(function(data) {
          return { initialValue: data };
        }).getOr({})), {
          getValue: function(input2) {
            return get$5(input2.element);
          },
          setValue: function(input2, data) {
            var current = get$5(input2.element);
            if (current !== data) {
              set$4(input2.element, data);
            }
          }
        }),
        onSetValue: detail.onSetValue
      })]));
    };
    var dom = function(detail) {
      return {
        tag: detail.tag,
        attributes: __assign({ type: "text" }, detail.inputAttributes),
        styles: detail.inputStyles,
        classes: detail.inputClasses
      };
    };
    var factory$h = function(detail, _spec) {
      return {
        uid: detail.uid,
        dom: dom(detail),
        components: [],
        behaviours: behaviours(detail),
        eventOrder: detail.eventOrder
      };
    };
    var Input = single({
      name: "Input",
      configFields: schema$k(),
      factory: factory$h
    });
    var exports$1 = {}, module = { exports: exports$1 };
    (function(define2, exports, module2, require2) {
      (function(global2, factory2) {
        typeof exports === "object" && typeof module2 !== "undefined" ? module2.exports = factory2() : typeof define2 === "function" && define2.amd ? define2(factory2) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, global2.EphoxContactWrapper = factory2());
      })(this, function() {
        var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
        var promise = { exports: {} };
        (function(module3) {
          (function(root) {
            var setTimeoutFunc = setTimeout;
            function noop4() {
            }
            function bind2(fn3, thisArg) {
              return function() {
                fn3.apply(thisArg, arguments);
              };
            }
            function Promise2(fn3) {
              if (typeof this !== "object")
                throw new TypeError("Promises must be constructed via new");
              if (typeof fn3 !== "function")
                throw new TypeError("not a function");
              this._state = 0;
              this._handled = false;
              this._value = void 0;
              this._deferreds = [];
              doResolve(fn3, this);
            }
            function handle2(self2, deferred) {
              while (self2._state === 3) {
                self2 = self2._value;
              }
              if (self2._state === 0) {
                self2._deferreds.push(deferred);
                return;
              }
              self2._handled = true;
              Promise2._immediateFn(function() {
                var cb = self2._state === 1 ? deferred.onFulfilled : deferred.onRejected;
                if (cb === null) {
                  (self2._state === 1 ? resolve2 : reject)(deferred.promise, self2._value);
                  return;
                }
                var ret;
                try {
                  ret = cb(self2._value);
                } catch (e2) {
                  reject(deferred.promise, e2);
                  return;
                }
                resolve2(deferred.promise, ret);
              });
            }
            function resolve2(self2, newValue) {
              try {
                if (newValue === self2)
                  throw new TypeError("A promise cannot be resolved with itself.");
                if (newValue && (typeof newValue === "object" || typeof newValue === "function")) {
                  var then = newValue.then;
                  if (newValue instanceof Promise2) {
                    self2._state = 3;
                    self2._value = newValue;
                    finale(self2);
                    return;
                  } else if (typeof then === "function") {
                    doResolve(bind2(then, newValue), self2);
                    return;
                  }
                }
                self2._state = 1;
                self2._value = newValue;
                finale(self2);
              } catch (e2) {
                reject(self2, e2);
              }
            }
            function reject(self2, newValue) {
              self2._state = 2;
              self2._value = newValue;
              finale(self2);
            }
            function finale(self2) {
              if (self2._state === 2 && self2._deferreds.length === 0) {
                Promise2._immediateFn(function() {
                  if (!self2._handled) {
                    Promise2._unhandledRejectionFn(self2._value);
                  }
                });
              }
              for (var i2 = 0, len = self2._deferreds.length; i2 < len; i2++) {
                handle2(self2, self2._deferreds[i2]);
              }
              self2._deferreds = null;
            }
            function Handler(onFulfilled, onRejected, promise2) {
              this.onFulfilled = typeof onFulfilled === "function" ? onFulfilled : null;
              this.onRejected = typeof onRejected === "function" ? onRejected : null;
              this.promise = promise2;
            }
            function doResolve(fn3, self2) {
              var done = false;
              try {
                fn3(function(value2) {
                  if (done)
                    return;
                  done = true;
                  resolve2(self2, value2);
                }, function(reason) {
                  if (done)
                    return;
                  done = true;
                  reject(self2, reason);
                });
              } catch (ex) {
                if (done)
                  return;
                done = true;
                reject(self2, ex);
              }
            }
            Promise2.prototype["catch"] = function(onRejected) {
              return this.then(null, onRejected);
            };
            Promise2.prototype.then = function(onFulfilled, onRejected) {
              var prom = new this.constructor(noop4);
              handle2(this, new Handler(onFulfilled, onRejected, prom));
              return prom;
            };
            Promise2.all = function(arr) {
              var args = Array.prototype.slice.call(arr);
              return new Promise2(function(resolve3, reject2) {
                if (args.length === 0)
                  return resolve3([]);
                var remaining = args.length;
                function res(i3, val) {
                  try {
                    if (val && (typeof val === "object" || typeof val === "function")) {
                      var then = val.then;
                      if (typeof then === "function") {
                        then.call(val, function(val2) {
                          res(i3, val2);
                        }, reject2);
                        return;
                      }
                    }
                    args[i3] = val;
                    if (--remaining === 0) {
                      resolve3(args);
                    }
                  } catch (ex) {
                    reject2(ex);
                  }
                }
                for (var i2 = 0; i2 < args.length; i2++) {
                  res(i2, args[i2]);
                }
              });
            };
            Promise2.resolve = function(value2) {
              if (value2 && typeof value2 === "object" && value2.constructor === Promise2) {
                return value2;
              }
              return new Promise2(function(resolve3) {
                resolve3(value2);
              });
            };
            Promise2.reject = function(value2) {
              return new Promise2(function(resolve3, reject2) {
                reject2(value2);
              });
            };
            Promise2.race = function(values2) {
              return new Promise2(function(resolve3, reject2) {
                for (var i2 = 0, len = values2.length; i2 < len; i2++) {
                  values2[i2].then(resolve3, reject2);
                }
              });
            };
            Promise2._immediateFn = typeof setImmediate === "function" ? function(fn3) {
              setImmediate(fn3);
            } : function(fn3) {
              setTimeoutFunc(fn3, 0);
            };
            Promise2._unhandledRejectionFn = function _unhandledRejectionFn(err) {
              if (typeof console !== "undefined" && console) {
                console.warn("Possible Unhandled Promise Rejection:", err);
              }
            };
            Promise2._setImmediateFn = function _setImmediateFn(fn3) {
              Promise2._immediateFn = fn3;
            };
            Promise2._setUnhandledRejectionFn = function _setUnhandledRejectionFn(fn3) {
              Promise2._unhandledRejectionFn = fn3;
            };
            if (module3.exports) {
              module3.exports = Promise2;
            } else if (!root.Promise) {
              root.Promise = Promise2;
            }
          })(commonjsGlobal);
        })(promise);
        var promisePolyfill = promise.exports;
        var Global = function() {
          if (typeof window !== "undefined") {
            return window;
          } else {
            return Function("return this;")();
          }
        }();
        var promisePolyfill_1 = { boltExport: Global.Promise || promisePolyfill };
        return promisePolyfill_1;
      });
    })(void 0, exports$1, module);
    var Promise$1 = module.exports.boltExport;
    var nu$3 = function(baseFn) {
      var data = Optional.none();
      var callbacks = [];
      var map4 = function(f2) {
        return nu$3(function(nCallback) {
          get2(function(data2) {
            nCallback(f2(data2));
          });
        });
      };
      var get2 = function(nCallback) {
        if (isReady()) {
          call(nCallback);
        } else {
          callbacks.push(nCallback);
        }
      };
      var set3 = function(x2) {
        if (!isReady()) {
          data = Optional.some(x2);
          run2(callbacks);
          callbacks = [];
        }
      };
      var isReady = function() {
        return data.isSome();
      };
      var run2 = function(cbs) {
        each$1(cbs, call);
      };
      var call = function(cb) {
        data.each(function(x2) {
          setTimeout(function() {
            cb(x2);
          }, 0);
        });
      };
      baseFn(set3);
      return {
        get: get2,
        map: map4,
        isReady
      };
    };
    var pure$1 = function(a2) {
      return nu$3(function(callback2) {
        callback2(a2);
      });
    };
    var LazyValue = {
      nu: nu$3,
      pure: pure$1
    };
    var errorReporter = function(err) {
      setTimeout(function() {
        throw err;
      }, 0);
    };
    var make$5 = function(run2) {
      var get2 = function(callback2) {
        run2().then(callback2, errorReporter);
      };
      var map4 = function(fab) {
        return make$5(function() {
          return run2().then(fab);
        });
      };
      var bind2 = function(aFutureB) {
        return make$5(function() {
          return run2().then(function(v2) {
            return aFutureB(v2).toPromise();
          });
        });
      };
      var anonBind = function(futureB) {
        return make$5(function() {
          return run2().then(function() {
            return futureB.toPromise();
          });
        });
      };
      var toLazy = function() {
        return LazyValue.nu(get2);
      };
      var toCached = function() {
        var cache2 = null;
        return make$5(function() {
          if (cache2 === null) {
            cache2 = run2();
          }
          return cache2;
        });
      };
      var toPromise = run2;
      return {
        map: map4,
        bind: bind2,
        anonBind,
        toLazy,
        toCached,
        toPromise,
        get: get2
      };
    };
    var nu$2 = function(baseFn) {
      return make$5(function() {
        return new Promise$1(baseFn);
      });
    };
    var pure = function(a2) {
      return make$5(function() {
        return Promise$1.resolve(a2);
      });
    };
    var Future = {
      nu: nu$2,
      pure
    };
    var ariaElements = [
      "input",
      "textarea"
    ];
    var isAriaElement = function(elem) {
      var name2 = name$2(elem);
      return contains$2(ariaElements, name2);
    };
    var markValid = function(component, invalidConfig) {
      var elem = invalidConfig.getRoot(component).getOr(component.element);
      remove$2(elem, invalidConfig.invalidClass);
      invalidConfig.notify.each(function(notifyInfo) {
        if (isAriaElement(component.element)) {
          set$8(component.element, "aria-invalid", false);
        }
        notifyInfo.getContainer(component).each(function(container) {
          set$5(container, notifyInfo.validHtml);
        });
        notifyInfo.onValid(component);
      });
    };
    var markInvalid = function(component, invalidConfig, invalidState, text2) {
      var elem = invalidConfig.getRoot(component).getOr(component.element);
      add$2(elem, invalidConfig.invalidClass);
      invalidConfig.notify.each(function(notifyInfo) {
        if (isAriaElement(component.element)) {
          set$8(component.element, "aria-invalid", true);
        }
        notifyInfo.getContainer(component).each(function(container) {
          set$5(container, text2);
        });
        notifyInfo.onInvalid(component, text2);
      });
    };
    var query = function(component, invalidConfig, _invalidState) {
      return invalidConfig.validator.fold(function() {
        return Future.pure(Result.value(true));
      }, function(validatorInfo) {
        return validatorInfo.validate(component);
      });
    };
    var run = function(component, invalidConfig, invalidState) {
      invalidConfig.notify.each(function(notifyInfo) {
        notifyInfo.onValidate(component);
      });
      return query(component, invalidConfig).map(function(valid) {
        if (component.getSystem().isConnected()) {
          return valid.fold(function(err) {
            markInvalid(component, invalidConfig, invalidState, err);
            return Result.error(err);
          }, function(v2) {
            markValid(component, invalidConfig);
            return Result.value(v2);
          });
        } else {
          return Result.error("No longer in system");
        }
      });
    };
    var isInvalid = function(component, invalidConfig) {
      var elem = invalidConfig.getRoot(component).getOr(component.element);
      return has(elem, invalidConfig.invalidClass);
    };
    var InvalidateApis = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      markValid,
      markInvalid,
      query,
      run,
      isInvalid
    });
    var events$8 = function(invalidConfig, invalidState) {
      return invalidConfig.validator.map(function(validatorInfo) {
        return derive$2([run$1(validatorInfo.onEvent, function(component) {
          run(component, invalidConfig, invalidState).get(identity$1);
        })].concat(validatorInfo.validateOnLoad ? [runOnAttached(function(component) {
          run(component, invalidConfig, invalidState).get(noop3);
        })] : []));
      }).getOr({});
    };
    var ActiveInvalidate = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      events: events$8
    });
    var InvalidateSchema = [
      required$1("invalidClass"),
      defaulted("getRoot", Optional.none),
      optionObjOf("notify", [
        defaulted("aria", "alert"),
        defaulted("getContainer", Optional.none),
        defaulted("validHtml", ""),
        onHandler("onValid"),
        onHandler("onInvalid"),
        onHandler("onValidate")
      ]),
      optionObjOf("validator", [
        required$1("validate"),
        defaulted("onEvent", "input"),
        defaulted("validateOnLoad", true)
      ])
    ];
    var Invalidating = create$7({
      fields: InvalidateSchema,
      name: "invalidating",
      active: ActiveInvalidate,
      apis: InvalidateApis,
      extra: {
        validation: function(validator) {
          return function(component) {
            var v2 = Representing.getValue(component);
            return Future.pure(validator(v2));
          };
        }
      }
    });
    var getCoupled = function(component, coupleConfig, coupleState, name2) {
      return coupleState.getOrCreate(component, coupleConfig, name2);
    };
    var CouplingApis = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      getCoupled
    });
    var CouplingSchema = [requiredOf("others", setOf(Result.value, anyValue()))];
    var init$a = function() {
      var coupled = {};
      var getOrCreate = function(component, coupleConfig, name2) {
        var available = keys(coupleConfig.others);
        if (!available) {
          throw new Error("Cannot find coupled component: " + name2 + ". Known coupled components: " + JSON.stringify(available, null, 2));
        } else {
          return get$e(coupled, name2).getOrThunk(function() {
            var builder2 = get$e(coupleConfig.others, name2).getOrDie("No information found for coupled component: " + name2);
            var spec = builder2(component);
            var built = component.getSystem().build(spec);
            coupled[name2] = built;
            return built;
          });
        }
      };
      var readState = constant$1({});
      return nu$8({
        readState,
        getOrCreate
      });
    };
    var CouplingState = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      init: init$a
    });
    var Coupling = create$7({
      fields: CouplingSchema,
      name: "coupling",
      apis: CouplingApis,
      state: CouplingState
    });
    var suffix = constant$1("sink");
    var partType$1 = constant$1(optional({
      name: suffix(),
      overrides: constant$1({
        dom: { tag: "div" },
        behaviours: derive$1([Positioning.config({ useFixed: always })]),
        events: derive$2([
          cutter(keydown()),
          cutter(mousedown()),
          cutter(click())
        ])
      })
    }));
    var HighlightOnOpen;
    (function(HighlightOnOpen2) {
      HighlightOnOpen2[HighlightOnOpen2["HighlightFirst"] = 0] = "HighlightFirst";
      HighlightOnOpen2[HighlightOnOpen2["HighlightNone"] = 1] = "HighlightNone";
    })(HighlightOnOpen || (HighlightOnOpen = {}));
    var getAnchor2 = function(detail, component) {
      var hotspot = detail.getHotspot(component).getOr(component);
      var type2 = "hotspot";
      var overrides2 = detail.getAnchorOverrides();
      return detail.layouts.fold(function() {
        return {
          type: type2,
          hotspot,
          overrides: overrides2
        };
      }, function(layouts3) {
        return {
          type: type2,
          hotspot,
          overrides: overrides2,
          layouts: layouts3
        };
      });
    };
    var fetch4 = function(detail, mapFetch, component) {
      var fetcher = detail.fetch;
      return fetcher(component).map(mapFetch);
    };
    var openF = function(detail, mapFetch, anchor2, component, sandbox, externals, highlightOnOpen) {
      var futureData = fetch4(detail, mapFetch, component);
      var getLazySink = getSink(component, detail);
      return futureData.map(function(tdata) {
        return tdata.bind(function(data) {
          return Optional.from(tieredMenu.sketch(__assign(__assign({}, externals.menu()), {
            uid: generate$5(""),
            data,
            highlightImmediately: highlightOnOpen === HighlightOnOpen.HighlightFirst,
            onOpenMenu: function(tmenu, menu2) {
              var sink = getLazySink().getOrDie();
              Positioning.position(sink, menu2, { anchor: anchor2 });
              Sandboxing.decloak(sandbox);
            },
            onOpenSubmenu: function(tmenu, item2, submenu) {
              var sink = getLazySink().getOrDie();
              Positioning.position(sink, submenu, {
                anchor: {
                  type: "submenu",
                  item: item2
                }
              });
              Sandboxing.decloak(sandbox);
            },
            onRepositionMenu: function(tmenu, primaryMenu, submenuTriggers) {
              var sink = getLazySink().getOrDie();
              Positioning.position(sink, primaryMenu, { anchor: anchor2 });
              each$1(submenuTriggers, function(st2) {
                Positioning.position(sink, st2.triggeredMenu, {
                  anchor: {
                    type: "submenu",
                    item: st2.triggeringItem
                  }
                });
              });
            },
            onEscape: function() {
              Focusing.focus(component);
              Sandboxing.close(sandbox);
              return Optional.some(true);
            }
          })));
        });
      });
    };
    var open = function(detail, mapFetch, hotspot, sandbox, externals, onOpenSync, highlightOnOpen) {
      var anchor2 = getAnchor2(detail, hotspot);
      var processed = openF(detail, mapFetch, anchor2, hotspot, sandbox, externals, highlightOnOpen);
      return processed.map(function(tdata) {
        tdata.fold(function() {
          if (Sandboxing.isOpen(sandbox)) {
            Sandboxing.close(sandbox);
          }
        }, function(data) {
          Sandboxing.cloak(sandbox);
          Sandboxing.open(sandbox, data);
          onOpenSync(sandbox);
        });
        return sandbox;
      });
    };
    var close = function(detail, mapFetch, component, sandbox, _externals, _onOpenSync, _highlightOnOpen) {
      Sandboxing.close(sandbox);
      return Future.pure(sandbox);
    };
    var togglePopup = function(detail, mapFetch, hotspot, externals, onOpenSync, highlightOnOpen) {
      var sandbox = Coupling.getCoupled(hotspot, "sandbox");
      var showing = Sandboxing.isOpen(sandbox);
      var action = showing ? close : open;
      return action(detail, mapFetch, hotspot, sandbox, externals, onOpenSync, highlightOnOpen);
    };
    var matchWidth = function(hotspot, container, useMinWidth) {
      var menu2 = Composing.getCurrent(container).getOr(container);
      var buttonWidth = get$a(hotspot.element);
      if (useMinWidth) {
        set$7(menu2.element, "min-width", buttonWidth + "px");
      } else {
        set$6(menu2.element, buttonWidth);
      }
    };
    var getSink = function(anyInSystem, sinkDetail) {
      return anyInSystem.getSystem().getByUid(sinkDetail.uid + "-" + suffix()).map(function(internalSink) {
        return function() {
          return Result.value(internalSink);
        };
      }).getOrThunk(function() {
        return sinkDetail.lazySink.fold(function() {
          return function() {
            return Result.error(new Error("No internal sink is specified, nor could an external sink be found"));
          };
        }, function(lazySinkFn) {
          return function() {
            return lazySinkFn(anyInSystem);
          };
        });
      });
    };
    var doRepositionMenus = function(sandbox) {
      Sandboxing.getState(sandbox).each(function(tmenu) {
        tieredMenu.repositionMenus(tmenu);
      });
    };
    var makeSandbox$1 = function(detail, hotspot, extras) {
      var ariaOwner = manager();
      var onOpen = function(component, menu2) {
        var anchor2 = getAnchor2(detail, hotspot);
        ariaOwner.link(hotspot.element);
        if (detail.matchWidth) {
          matchWidth(anchor2.hotspot, menu2, detail.useMinWidth);
        }
        detail.onOpen(anchor2, component, menu2);
        if (extras !== void 0 && extras.onOpen !== void 0) {
          extras.onOpen(component, menu2);
        }
      };
      var onClose = function(component, menu2) {
        ariaOwner.unlink(hotspot.element);
        if (extras !== void 0 && extras.onClose !== void 0) {
          extras.onClose(component, menu2);
        }
      };
      var lazySink = getSink(hotspot, detail);
      return {
        dom: {
          tag: "div",
          classes: detail.sandboxClasses,
          attributes: {
            id: ariaOwner.id,
            role: "listbox"
          }
        },
        behaviours: SketchBehaviours.augment(detail.sandboxBehaviours, [
          Representing.config({
            store: {
              mode: "memory",
              initialValue: hotspot
            }
          }),
          Sandboxing.config({
            onOpen,
            onClose,
            isPartOf: function(container, data, queryElem) {
              return isPartOf$1(data, queryElem) || isPartOf$1(hotspot, queryElem);
            },
            getAttachPoint: function() {
              return lazySink().getOrDie();
            }
          }),
          Composing.config({
            find: function(sandbox) {
              return Sandboxing.getState(sandbox).bind(function(menu2) {
                return Composing.getCurrent(menu2);
              });
            }
          }),
          Receiving.config({ channels: __assign(__assign({}, receivingChannel$1({ isExtraPart: never })), receivingChannel({ doReposition: doRepositionMenus })) })
        ])
      };
    };
    var repositionMenus = function(comp) {
      var sandbox = Coupling.getCoupled(comp, "sandbox");
      doRepositionMenus(sandbox);
    };
    var sandboxFields = function() {
      return [
        defaulted("sandboxClasses", []),
        SketchBehaviours.field("sandboxBehaviours", [
          Composing,
          Receiving,
          Sandboxing,
          Representing
        ])
      ];
    };
    var schema$j = constant$1([
      required$1("dom"),
      required$1("fetch"),
      onHandler("onOpen"),
      onKeyboardHandler("onExecute"),
      defaulted("getHotspot", Optional.some),
      defaulted("getAnchorOverrides", constant$1({})),
      schema$y(),
      field("dropdownBehaviours", [
        Toggling,
        Coupling,
        Keying,
        Focusing
      ]),
      required$1("toggleClass"),
      defaulted("eventOrder", {}),
      option("lazySink"),
      defaulted("matchWidth", false),
      defaulted("useMinWidth", false),
      option("role")
    ].concat(sandboxFields()));
    var parts$d = constant$1([
      external$1({
        schema: [tieredMenuMarkers()],
        name: "menu",
        defaults: function(detail) {
          return { onExecute: detail.onExecute };
        }
      }),
      partType$1()
    ]);
    var factory$g = function(detail, components2, _spec, externals) {
      var _a2;
      var lookupAttr = function(attr) {
        return get$e(detail.dom, "attributes").bind(function(attrs) {
          return get$e(attrs, attr);
        });
      };
      var switchToMenu = function(sandbox) {
        Sandboxing.getState(sandbox).each(function(tmenu) {
          tieredMenu.highlightPrimary(tmenu);
        });
      };
      var action = function(component) {
        var onOpenSync = switchToMenu;
        togglePopup(detail, identity$1, component, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop3);
      };
      var apis = {
        expand: function(comp) {
          if (!Toggling.isOn(comp)) {
            togglePopup(detail, identity$1, comp, externals, noop3, HighlightOnOpen.HighlightNone).get(noop3);
          }
        },
        open: function(comp) {
          if (!Toggling.isOn(comp)) {
            togglePopup(detail, identity$1, comp, externals, noop3, HighlightOnOpen.HighlightFirst).get(noop3);
          }
        },
        isOpen: Toggling.isOn,
        close: function(comp) {
          if (Toggling.isOn(comp)) {
            togglePopup(detail, identity$1, comp, externals, noop3, HighlightOnOpen.HighlightFirst).get(noop3);
          }
        },
        repositionMenus: function(comp) {
          if (Toggling.isOn(comp)) {
            repositionMenus(comp);
          }
        }
      };
      var triggerExecute = function(comp, _se) {
        emitExecute(comp);
        return Optional.some(true);
      };
      return {
        uid: detail.uid,
        dom: detail.dom,
        components: components2,
        behaviours: augment(detail.dropdownBehaviours, [
          Toggling.config({
            toggleClass: detail.toggleClass,
            aria: { mode: "expanded" }
          }),
          Coupling.config({
            others: {
              sandbox: function(hotspot) {
                return makeSandbox$1(detail, hotspot, {
                  onOpen: function() {
                    return Toggling.on(hotspot);
                  },
                  onClose: function() {
                    return Toggling.off(hotspot);
                  }
                });
              }
            }
          }),
          Keying.config({
            mode: "special",
            onSpace: triggerExecute,
            onEnter: triggerExecute,
            onDown: function(comp, _se) {
              if (Dropdown2.isOpen(comp)) {
                var sandbox = Coupling.getCoupled(comp, "sandbox");
                switchToMenu(sandbox);
              } else {
                Dropdown2.open(comp);
              }
              return Optional.some(true);
            },
            onEscape: function(comp, _se) {
              if (Dropdown2.isOpen(comp)) {
                Dropdown2.close(comp);
                return Optional.some(true);
              } else {
                return Optional.none();
              }
            }
          }),
          Focusing.config({})
        ]),
        events: events$a(Optional.some(action)),
        eventOrder: __assign(__assign({}, detail.eventOrder), (_a2 = {}, _a2[execute$5()] = [
          "disabling",
          "toggling",
          "alloy.base.behaviour"
        ], _a2)),
        apis,
        domModification: {
          attributes: __assign(__assign({ "aria-haspopup": "true" }, detail.role.fold(function() {
            return {};
          }, function(role) {
            return { role };
          })), detail.dom.tag === "button" ? { type: lookupAttr("type").getOr("button") } : {})
        }
      };
    };
    var Dropdown2 = composite({
      name: "Dropdown",
      configFields: schema$j(),
      partFields: parts$d(),
      factory: factory$g,
      apis: {
        open: function(apis, comp) {
          return apis.open(comp);
        },
        expand: function(apis, comp) {
          return apis.expand(comp);
        },
        close: function(apis, comp) {
          return apis.close(comp);
        },
        isOpen: function(apis, comp) {
          return apis.isOpen(comp);
        },
        repositionMenus: function(apis, comp) {
          return apis.repositionMenus(comp);
        }
      }
    });
    var exhibit$1 = function() {
      return nu$7({
        styles: {
          "-webkit-user-select": "none",
          "user-select": "none",
          "-ms-user-select": "none",
          "-moz-user-select": "-moz-none"
        },
        attributes: { unselectable: "on" }
      });
    };
    var events$7 = function() {
      return derive$2([abort(selectstart(), always)]);
    };
    var ActiveUnselecting = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      events: events$7,
      exhibit: exhibit$1
    });
    var Unselecting = create$7({
      fields: [],
      name: "unselecting",
      active: ActiveUnselecting
    });
    var renderPanelButton = function(spec, sharedBackstage) {
      return Dropdown2.sketch({
        dom: spec.dom,
        components: spec.components,
        toggleClass: "mce-active",
        dropdownBehaviours: derive$1([
          DisablingConfigs.button(sharedBackstage.providers.isDisabled),
          receivingConfig(),
          Unselecting.config({}),
          Tabstopping.config({})
        ]),
        layouts: spec.layouts,
        sandboxClasses: ["tox-dialog__popups"],
        lazySink: sharedBackstage.getSink,
        fetch: function(comp) {
          return Future.nu(function(callback2) {
            return spec.fetch(callback2);
          }).map(function(items) {
            return Optional.from(createTieredDataFrom(deepMerge(createPartialChoiceMenu(generate$6("menu-value"), items, function(value2) {
              spec.onItemAction(comp, value2);
            }, spec.columns, spec.presets, ItemResponse$1.CLOSE_ON_EXECUTE, never, sharedBackstage.providers), { movement: deriveMenuMovement(spec.columns, spec.presets) })));
          });
        },
        parts: { menu: part(false, 1, spec.presets) }
      });
    };
    var colorInputChangeEvent = generate$6("color-input-change");
    var colorSwatchChangeEvent = generate$6("color-swatch-change");
    var colorPickerCancelEvent = generate$6("color-picker-cancel");
    var renderColorInput = function(spec, sharedBackstage, colorInputBackstage) {
      var pField = FormField.parts.field({
        factory: Input,
        inputClasses: ["tox-textfield"],
        onSetValue: function(c2) {
          return Invalidating.run(c2).get(noop3);
        },
        inputBehaviours: derive$1([
          Disabling.config({ disabled: sharedBackstage.providers.isDisabled }),
          receivingConfig(),
          Tabstopping.config({}),
          Invalidating.config({
            invalidClass: "tox-textbox-field-invalid",
            getRoot: function(comp) {
              return parent(comp.element);
            },
            notify: {
              onValid: function(comp) {
                var val = Representing.getValue(comp);
                emitWith(comp, colorInputChangeEvent, { color: val });
              }
            },
            validator: {
              validateOnLoad: false,
              validate: function(input2) {
                var inputValue = Representing.getValue(input2);
                if (inputValue.length === 0) {
                  return Future.pure(Result.value(true));
                } else {
                  var span = SugarElement.fromTag("span");
                  set$7(span, "background-color", inputValue);
                  var res = getRaw(span, "background-color").fold(function() {
                    return Result.error("blah");
                  }, function(_2) {
                    return Result.value(inputValue);
                  });
                  return Future.pure(res);
                }
              }
            }
          })
        ]),
        selectOnFocus: false
      });
      var pLabel = spec.label.map(function(label) {
        return renderLabel$2(label, sharedBackstage.providers);
      });
      var emitSwatchChange = function(colorBit, value2) {
        emitWith(colorBit, colorSwatchChangeEvent, { value: value2 });
      };
      var onItemAction = function(comp, value2) {
        memColorButton.getOpt(comp).each(function(colorBit) {
          if (value2 === "custom") {
            colorInputBackstage.colorPicker(function(valueOpt) {
              valueOpt.fold(function() {
                return emit(colorBit, colorPickerCancelEvent);
              }, function(value3) {
                emitSwatchChange(colorBit, value3);
                addColor(value3);
              });
            }, "#ffffff");
          } else if (value2 === "remove") {
            emitSwatchChange(colorBit, "");
          } else {
            emitSwatchChange(colorBit, value2);
          }
        });
      };
      var memColorButton = record(renderPanelButton({
        dom: {
          tag: "span",
          attributes: { "aria-label": sharedBackstage.providers.translate("Color swatch") }
        },
        layouts: {
          onRtl: function() {
            return [
              southwest$2,
              southeast$2,
              south$2
            ];
          },
          onLtr: function() {
            return [
              southeast$2,
              southwest$2,
              south$2
            ];
          }
        },
        components: [],
        fetch: getFetch$1(colorInputBackstage.getColors(), colorInputBackstage.hasCustomColors()),
        columns: colorInputBackstage.getColorCols(),
        presets: "color",
        onItemAction
      }, sharedBackstage));
      return FormField.sketch({
        dom: {
          tag: "div",
          classes: ["tox-form__group"]
        },
        components: pLabel.toArray().concat([{
          dom: {
            tag: "div",
            classes: ["tox-color-input"]
          },
          components: [
            pField,
            memColorButton.asSpec()
          ]
        }]),
        fieldBehaviours: derive$1([config("form-field-events", [
          run$1(colorInputChangeEvent, function(comp, se2) {
            memColorButton.getOpt(comp).each(function(colorButton) {
              set$7(colorButton.element, "background-color", se2.event.color);
            });
            emitWith(comp, formChangeEvent, { name: spec.name });
          }),
          run$1(colorSwatchChangeEvent, function(comp, se2) {
            FormField.getField(comp).each(function(field2) {
              Representing.setValue(field2, se2.event.value);
              Composing.getCurrent(comp).each(Focusing.focus);
            });
          }),
          run$1(colorPickerCancelEvent, function(comp, _se) {
            FormField.getField(comp).each(function(_field) {
              Composing.getCurrent(comp).each(Focusing.focus);
            });
          })
        ])])
      });
    };
    var labelPart = optional({
      schema: [required$1("dom")],
      name: "label"
    });
    var edgePart = function(name2) {
      return optional({
        name: "" + name2 + "-edge",
        overrides: function(detail) {
          var action = detail.model.manager.edgeActions[name2];
          return action.fold(function() {
            return {};
          }, function(a2) {
            return {
              events: derive$2([
                runActionExtra(touchstart(), function(comp, se2, d2) {
                  return a2(comp, d2);
                }, [detail]),
                runActionExtra(mousedown(), function(comp, se2, d2) {
                  return a2(comp, d2);
                }, [detail]),
                runActionExtra(mousemove(), function(comp, se2, det) {
                  if (det.mouseIsDown.get()) {
                    a2(comp, det);
                  }
                }, [detail])
              ])
            };
          });
        }
      });
    };
    var tlEdgePart = edgePart("top-left");
    var tedgePart = edgePart("top");
    var trEdgePart = edgePart("top-right");
    var redgePart = edgePart("right");
    var brEdgePart = edgePart("bottom-right");
    var bedgePart = edgePart("bottom");
    var blEdgePart = edgePart("bottom-left");
    var ledgePart = edgePart("left");
    var thumbPart = required({
      name: "thumb",
      defaults: constant$1({ dom: { styles: { position: "absolute" } } }),
      overrides: function(detail) {
        return {
          events: derive$2([
            redirectToPart(touchstart(), detail, "spectrum"),
            redirectToPart(touchmove(), detail, "spectrum"),
            redirectToPart(touchend(), detail, "spectrum"),
            redirectToPart(mousedown(), detail, "spectrum"),
            redirectToPart(mousemove(), detail, "spectrum"),
            redirectToPart(mouseup(), detail, "spectrum")
          ])
        };
      }
    });
    var spectrumPart = required({
      schema: [customField("mouseIsDown", function() {
        return Cell(false);
      })],
      name: "spectrum",
      overrides: function(detail) {
        var modelDetail = detail.model;
        var model = modelDetail.manager;
        var setValueFrom2 = function(component, simulatedEvent) {
          return model.getValueFromEvent(simulatedEvent).map(function(value2) {
            return model.setValueFrom(component, detail, value2);
          });
        };
        return {
          behaviours: derive$1([
            Keying.config({
              mode: "special",
              onLeft: function(spectrum) {
                return model.onLeft(spectrum, detail);
              },
              onRight: function(spectrum) {
                return model.onRight(spectrum, detail);
              },
              onUp: function(spectrum) {
                return model.onUp(spectrum, detail);
              },
              onDown: function(spectrum) {
                return model.onDown(spectrum, detail);
              }
            }),
            Focusing.config({})
          ]),
          events: derive$2([
            run$1(touchstart(), setValueFrom2),
            run$1(touchmove(), setValueFrom2),
            run$1(mousedown(), setValueFrom2),
            run$1(mousemove(), function(spectrum, se2) {
              if (detail.mouseIsDown.get()) {
                setValueFrom2(spectrum, se2);
              }
            })
          ])
        };
      }
    });
    var SliderParts = [
      labelPart,
      ledgePart,
      redgePart,
      tedgePart,
      bedgePart,
      tlEdgePart,
      trEdgePart,
      blEdgePart,
      brEdgePart,
      thumbPart,
      spectrumPart
    ];
    var _sliderChangeEvent = "slider.change.value";
    var sliderChangeEvent = constant$1(_sliderChangeEvent);
    var isTouchEvent$2 = function(evt) {
      return evt.type.indexOf("touch") !== -1;
    };
    var getEventSource = function(simulatedEvent) {
      var evt = simulatedEvent.event.raw;
      if (isTouchEvent$2(evt)) {
        var touchEvent = evt;
        return touchEvent.touches !== void 0 && touchEvent.touches.length === 1 ? Optional.some(touchEvent.touches[0]).map(function(t3) {
          return SugarPosition(t3.clientX, t3.clientY);
        }) : Optional.none();
      } else {
        var mouseEvent = evt;
        return mouseEvent.clientX !== void 0 ? Optional.some(mouseEvent).map(function(me2) {
          return SugarPosition(me2.clientX, me2.clientY);
        }) : Optional.none();
      }
    };
    var t2 = "top", r2 = "right", b2 = "bottom", l2 = "left";
    var minX = function(detail) {
      return detail.model.minX;
    };
    var minY = function(detail) {
      return detail.model.minY;
    };
    var min1X = function(detail) {
      return detail.model.minX - 1;
    };
    var min1Y = function(detail) {
      return detail.model.minY - 1;
    };
    var maxX = function(detail) {
      return detail.model.maxX;
    };
    var maxY = function(detail) {
      return detail.model.maxY;
    };
    var max1X = function(detail) {
      return detail.model.maxX + 1;
    };
    var max1Y = function(detail) {
      return detail.model.maxY + 1;
    };
    var range = function(detail, max3, min3) {
      return max3(detail) - min3(detail);
    };
    var xRange = function(detail) {
      return range(detail, maxX, minX);
    };
    var yRange = function(detail) {
      return range(detail, maxY, minY);
    };
    var halfX = function(detail) {
      return xRange(detail) / 2;
    };
    var halfY = function(detail) {
      return yRange(detail) / 2;
    };
    var step = function(detail) {
      return detail.stepSize;
    };
    var snap = function(detail) {
      return detail.snapToGrid;
    };
    var snapStart = function(detail) {
      return detail.snapStart;
    };
    var rounded = function(detail) {
      return detail.rounded;
    };
    var hasEdge = function(detail, edgeName) {
      return detail[edgeName + "-edge"] !== void 0;
    };
    var hasLEdge = function(detail) {
      return hasEdge(detail, l2);
    };
    var hasREdge = function(detail) {
      return hasEdge(detail, r2);
    };
    var hasTEdge = function(detail) {
      return hasEdge(detail, t2);
    };
    var hasBEdge = function(detail) {
      return hasEdge(detail, b2);
    };
    var currentValue = function(detail) {
      return detail.model.value.get();
    };
    var xValue = function(x2) {
      return { x: x2 };
    };
    var yValue = function(y2) {
      return { y: y2 };
    };
    var xyValue = function(x2, y2) {
      return {
        x: x2,
        y: y2
      };
    };
    var fireSliderChange$3 = function(component, value2) {
      emitWith(component, sliderChangeEvent(), { value: value2 });
    };
    var setToTLEdgeXY = function(edge2, detail) {
      fireSliderChange$3(edge2, xyValue(min1X(detail), min1Y(detail)));
    };
    var setToTEdge = function(edge2, detail) {
      fireSliderChange$3(edge2, yValue(min1Y(detail)));
    };
    var setToTEdgeXY = function(edge2, detail) {
      fireSliderChange$3(edge2, xyValue(halfX(detail), min1Y(detail)));
    };
    var setToTREdgeXY = function(edge2, detail) {
      fireSliderChange$3(edge2, xyValue(max1X(detail), min1Y(detail)));
    };
    var setToREdge = function(edge2, detail) {
      fireSliderChange$3(edge2, xValue(max1X(detail)));
    };
    var setToREdgeXY = function(edge2, detail) {
      fireSliderChange$3(edge2, xyValue(max1X(detail), halfY(detail)));
    };
    var setToBREdgeXY = function(edge2, detail) {
      fireSliderChange$3(edge2, xyValue(max1X(detail), max1Y(detail)));
    };
    var setToBEdge = function(edge2, detail) {
      fireSliderChange$3(edge2, yValue(max1Y(detail)));
    };
    var setToBEdgeXY = function(edge2, detail) {
      fireSliderChange$3(edge2, xyValue(halfX(detail), max1Y(detail)));
    };
    var setToBLEdgeXY = function(edge2, detail) {
      fireSliderChange$3(edge2, xyValue(min1X(detail), max1Y(detail)));
    };
    var setToLEdge = function(edge2, detail) {
      fireSliderChange$3(edge2, xValue(min1X(detail)));
    };
    var setToLEdgeXY = function(edge2, detail) {
      fireSliderChange$3(edge2, xyValue(min1X(detail), halfY(detail)));
    };
    var reduceBy = function(value2, min3, max3, step2) {
      if (value2 < min3) {
        return value2;
      } else if (value2 > max3) {
        return max3;
      } else if (value2 === min3) {
        return min3 - 1;
      } else {
        return Math.max(min3, value2 - step2);
      }
    };
    var increaseBy = function(value2, min3, max3, step2) {
      if (value2 > max3) {
        return value2;
      } else if (value2 < min3) {
        return min3;
      } else if (value2 === max3) {
        return max3 + 1;
      } else {
        return Math.min(max3, value2 + step2);
      }
    };
    var capValue = function(value2, min3, max3) {
      return Math.max(min3, Math.min(max3, value2));
    };
    var snapValueOf = function(value2, min3, max3, step2, snapStart2) {
      return snapStart2.fold(function() {
        var initValue = value2 - min3;
        var extraValue = Math.round(initValue / step2) * step2;
        return capValue(min3 + extraValue, min3 - 1, max3 + 1);
      }, function(start4) {
        var remainder = (value2 - start4) % step2;
        var adjustment = Math.round(remainder / step2);
        var rawSteps = Math.floor((value2 - start4) / step2);
        var maxSteps = Math.floor((max3 - start4) / step2);
        var numSteps = Math.min(maxSteps, rawSteps + adjustment);
        var r3 = start4 + numSteps * step2;
        return Math.max(start4, r3);
      });
    };
    var findOffsetOf = function(value2, min3, max3) {
      return Math.min(max3, Math.max(value2, min3)) - min3;
    };
    var findValueOf = function(args) {
      var min3 = args.min, max3 = args.max, range2 = args.range, value2 = args.value, step2 = args.step, snap2 = args.snap, snapStart2 = args.snapStart, rounded2 = args.rounded, hasMinEdge = args.hasMinEdge, hasMaxEdge = args.hasMaxEdge, minBound = args.minBound, maxBound = args.maxBound, screenRange = args.screenRange;
      var capMin = hasMinEdge ? min3 - 1 : min3;
      var capMax = hasMaxEdge ? max3 + 1 : max3;
      if (value2 < minBound) {
        return capMin;
      } else if (value2 > maxBound) {
        return capMax;
      } else {
        var offset3 = findOffsetOf(value2, minBound, maxBound);
        var newValue = capValue(offset3 / screenRange * range2 + min3, capMin, capMax);
        if (snap2 && newValue >= min3 && newValue <= max3) {
          return snapValueOf(newValue, min3, max3, step2, snapStart2);
        } else if (rounded2) {
          return Math.round(newValue);
        } else {
          return newValue;
        }
      }
    };
    var findOffsetOfValue$2 = function(args) {
      var min3 = args.min, max3 = args.max, range2 = args.range, value2 = args.value, hasMinEdge = args.hasMinEdge, hasMaxEdge = args.hasMaxEdge, maxBound = args.maxBound, maxOffset = args.maxOffset, centerMinEdge = args.centerMinEdge, centerMaxEdge = args.centerMaxEdge;
      if (value2 < min3) {
        return hasMinEdge ? 0 : centerMinEdge;
      } else if (value2 > max3) {
        return hasMaxEdge ? maxBound : centerMaxEdge;
      } else {
        return (value2 - min3) / range2 * maxOffset;
      }
    };
    var top2 = "top", right2 = "right", bottom2 = "bottom", left2 = "left", width = "width", height = "height";
    var getBounds2 = function(component) {
      return component.element.dom.getBoundingClientRect();
    };
    var getBoundsProperty = function(bounds2, property) {
      return bounds2[property];
    };
    var getMinXBounds = function(component) {
      var bounds2 = getBounds2(component);
      return getBoundsProperty(bounds2, left2);
    };
    var getMaxXBounds = function(component) {
      var bounds2 = getBounds2(component);
      return getBoundsProperty(bounds2, right2);
    };
    var getMinYBounds = function(component) {
      var bounds2 = getBounds2(component);
      return getBoundsProperty(bounds2, top2);
    };
    var getMaxYBounds = function(component) {
      var bounds2 = getBounds2(component);
      return getBoundsProperty(bounds2, bottom2);
    };
    var getXScreenRange = function(component) {
      var bounds2 = getBounds2(component);
      return getBoundsProperty(bounds2, width);
    };
    var getYScreenRange = function(component) {
      var bounds2 = getBounds2(component);
      return getBoundsProperty(bounds2, height);
    };
    var getCenterOffsetOf = function(componentMinEdge, componentMaxEdge, spectrumMinEdge) {
      return (componentMinEdge + componentMaxEdge) / 2 - spectrumMinEdge;
    };
    var getXCenterOffSetOf = function(component, spectrum) {
      var componentBounds = getBounds2(component);
      var spectrumBounds = getBounds2(spectrum);
      var componentMinEdge = getBoundsProperty(componentBounds, left2);
      var componentMaxEdge = getBoundsProperty(componentBounds, right2);
      var spectrumMinEdge = getBoundsProperty(spectrumBounds, left2);
      return getCenterOffsetOf(componentMinEdge, componentMaxEdge, spectrumMinEdge);
    };
    var getYCenterOffSetOf = function(component, spectrum) {
      var componentBounds = getBounds2(component);
      var spectrumBounds = getBounds2(spectrum);
      var componentMinEdge = getBoundsProperty(componentBounds, top2);
      var componentMaxEdge = getBoundsProperty(componentBounds, bottom2);
      var spectrumMinEdge = getBoundsProperty(spectrumBounds, top2);
      return getCenterOffsetOf(componentMinEdge, componentMaxEdge, spectrumMinEdge);
    };
    var fireSliderChange$2 = function(spectrum, value2) {
      emitWith(spectrum, sliderChangeEvent(), { value: value2 });
    };
    var sliderValue$2 = function(x2) {
      return { x: x2 };
    };
    var findValueOfOffset$1 = function(spectrum, detail, left3) {
      var args = {
        min: minX(detail),
        max: maxX(detail),
        range: xRange(detail),
        value: left3,
        step: step(detail),
        snap: snap(detail),
        snapStart: snapStart(detail),
        rounded: rounded(detail),
        hasMinEdge: hasLEdge(detail),
        hasMaxEdge: hasREdge(detail),
        minBound: getMinXBounds(spectrum),
        maxBound: getMaxXBounds(spectrum),
        screenRange: getXScreenRange(spectrum)
      };
      return findValueOf(args);
    };
    var setValueFrom$2 = function(spectrum, detail, value2) {
      var xValue2 = findValueOfOffset$1(spectrum, detail, value2);
      var sliderVal = sliderValue$2(xValue2);
      fireSliderChange$2(spectrum, sliderVal);
      return xValue2;
    };
    var setToMin$2 = function(spectrum, detail) {
      var min3 = minX(detail);
      fireSliderChange$2(spectrum, sliderValue$2(min3));
    };
    var setToMax$2 = function(spectrum, detail) {
      var max3 = maxX(detail);
      fireSliderChange$2(spectrum, sliderValue$2(max3));
    };
    var moveBy$2 = function(direction, spectrum, detail) {
      var f2 = direction > 0 ? increaseBy : reduceBy;
      var xValue2 = f2(currentValue(detail).x, minX(detail), maxX(detail), step(detail));
      fireSliderChange$2(spectrum, sliderValue$2(xValue2));
      return Optional.some(xValue2);
    };
    var handleMovement$2 = function(direction) {
      return function(spectrum, detail) {
        return moveBy$2(direction, spectrum, detail).map(always);
      };
    };
    var getValueFromEvent$2 = function(simulatedEvent) {
      var pos = getEventSource(simulatedEvent);
      return pos.map(function(p2) {
        return p2.left;
      });
    };
    var findOffsetOfValue$1 = function(spectrum, detail, value2, minEdge, maxEdge) {
      var minOffset = 0;
      var maxOffset = getXScreenRange(spectrum);
      var centerMinEdge = minEdge.bind(function(edge2) {
        return Optional.some(getXCenterOffSetOf(edge2, spectrum));
      }).getOr(minOffset);
      var centerMaxEdge = maxEdge.bind(function(edge2) {
        return Optional.some(getXCenterOffSetOf(edge2, spectrum));
      }).getOr(maxOffset);
      var args = {
        min: minX(detail),
        max: maxX(detail),
        range: xRange(detail),
        value: value2,
        hasMinEdge: hasLEdge(detail),
        hasMaxEdge: hasREdge(detail),
        minBound: getMinXBounds(spectrum),
        minOffset,
        maxBound: getMaxXBounds(spectrum),
        maxOffset,
        centerMinEdge,
        centerMaxEdge
      };
      return findOffsetOfValue$2(args);
    };
    var findPositionOfValue$1 = function(slider, spectrum, value2, minEdge, maxEdge, detail) {
      var offset3 = findOffsetOfValue$1(spectrum, detail, value2, minEdge, maxEdge);
      return getMinXBounds(spectrum) - getMinXBounds(slider) + offset3;
    };
    var setPositionFromValue$2 = function(slider, thumb, detail, edges) {
      var value2 = currentValue(detail);
      var pos = findPositionOfValue$1(slider, edges.getSpectrum(slider), value2.x, edges.getLeftEdge(slider), edges.getRightEdge(slider), detail);
      var thumbRadius = get$a(thumb.element) / 2;
      set$7(thumb.element, "left", pos - thumbRadius + "px");
    };
    var onLeft$2 = handleMovement$2(-1);
    var onRight$2 = handleMovement$2(1);
    var onUp$2 = Optional.none;
    var onDown$2 = Optional.none;
    var edgeActions$2 = {
      "top-left": Optional.none(),
      "top": Optional.none(),
      "top-right": Optional.none(),
      "right": Optional.some(setToREdge),
      "bottom-right": Optional.none(),
      "bottom": Optional.none(),
      "bottom-left": Optional.none(),
      "left": Optional.some(setToLEdge)
    };
    var HorizontalModel = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      setValueFrom: setValueFrom$2,
      setToMin: setToMin$2,
      setToMax: setToMax$2,
      findValueOfOffset: findValueOfOffset$1,
      getValueFromEvent: getValueFromEvent$2,
      findPositionOfValue: findPositionOfValue$1,
      setPositionFromValue: setPositionFromValue$2,
      onLeft: onLeft$2,
      onRight: onRight$2,
      onUp: onUp$2,
      onDown: onDown$2,
      edgeActions: edgeActions$2
    });
    var fireSliderChange$1 = function(spectrum, value2) {
      emitWith(spectrum, sliderChangeEvent(), { value: value2 });
    };
    var sliderValue$1 = function(y2) {
      return { y: y2 };
    };
    var findValueOfOffset = function(spectrum, detail, top3) {
      var args = {
        min: minY(detail),
        max: maxY(detail),
        range: yRange(detail),
        value: top3,
        step: step(detail),
        snap: snap(detail),
        snapStart: snapStart(detail),
        rounded: rounded(detail),
        hasMinEdge: hasTEdge(detail),
        hasMaxEdge: hasBEdge(detail),
        minBound: getMinYBounds(spectrum),
        maxBound: getMaxYBounds(spectrum),
        screenRange: getYScreenRange(spectrum)
      };
      return findValueOf(args);
    };
    var setValueFrom$1 = function(spectrum, detail, value2) {
      var yValue2 = findValueOfOffset(spectrum, detail, value2);
      var sliderVal = sliderValue$1(yValue2);
      fireSliderChange$1(spectrum, sliderVal);
      return yValue2;
    };
    var setToMin$1 = function(spectrum, detail) {
      var min3 = minY(detail);
      fireSliderChange$1(spectrum, sliderValue$1(min3));
    };
    var setToMax$1 = function(spectrum, detail) {
      var max3 = maxY(detail);
      fireSliderChange$1(spectrum, sliderValue$1(max3));
    };
    var moveBy$1 = function(direction, spectrum, detail) {
      var f2 = direction > 0 ? increaseBy : reduceBy;
      var yValue2 = f2(currentValue(detail).y, minY(detail), maxY(detail), step(detail));
      fireSliderChange$1(spectrum, sliderValue$1(yValue2));
      return Optional.some(yValue2);
    };
    var handleMovement$1 = function(direction) {
      return function(spectrum, detail) {
        return moveBy$1(direction, spectrum, detail).map(always);
      };
    };
    var getValueFromEvent$1 = function(simulatedEvent) {
      var pos = getEventSource(simulatedEvent);
      return pos.map(function(p2) {
        return p2.top;
      });
    };
    var findOffsetOfValue = function(spectrum, detail, value2, minEdge, maxEdge) {
      var minOffset = 0;
      var maxOffset = getYScreenRange(spectrum);
      var centerMinEdge = minEdge.bind(function(edge2) {
        return Optional.some(getYCenterOffSetOf(edge2, spectrum));
      }).getOr(minOffset);
      var centerMaxEdge = maxEdge.bind(function(edge2) {
        return Optional.some(getYCenterOffSetOf(edge2, spectrum));
      }).getOr(maxOffset);
      var args = {
        min: minY(detail),
        max: maxY(detail),
        range: yRange(detail),
        value: value2,
        hasMinEdge: hasTEdge(detail),
        hasMaxEdge: hasBEdge(detail),
        minBound: getMinYBounds(spectrum),
        minOffset,
        maxBound: getMaxYBounds(spectrum),
        maxOffset,
        centerMinEdge,
        centerMaxEdge
      };
      return findOffsetOfValue$2(args);
    };
    var findPositionOfValue = function(slider, spectrum, value2, minEdge, maxEdge, detail) {
      var offset3 = findOffsetOfValue(spectrum, detail, value2, minEdge, maxEdge);
      return getMinYBounds(spectrum) - getMinYBounds(slider) + offset3;
    };
    var setPositionFromValue$1 = function(slider, thumb, detail, edges) {
      var value2 = currentValue(detail);
      var pos = findPositionOfValue(slider, edges.getSpectrum(slider), value2.y, edges.getTopEdge(slider), edges.getBottomEdge(slider), detail);
      var thumbRadius = get$b(thumb.element) / 2;
      set$7(thumb.element, "top", pos - thumbRadius + "px");
    };
    var onLeft$1 = Optional.none;
    var onRight$1 = Optional.none;
    var onUp$1 = handleMovement$1(-1);
    var onDown$1 = handleMovement$1(1);
    var edgeActions$1 = {
      "top-left": Optional.none(),
      "top": Optional.some(setToTEdge),
      "top-right": Optional.none(),
      "right": Optional.none(),
      "bottom-right": Optional.none(),
      "bottom": Optional.some(setToBEdge),
      "bottom-left": Optional.none(),
      "left": Optional.none()
    };
    var VerticalModel = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      setValueFrom: setValueFrom$1,
      setToMin: setToMin$1,
      setToMax: setToMax$1,
      findValueOfOffset,
      getValueFromEvent: getValueFromEvent$1,
      findPositionOfValue,
      setPositionFromValue: setPositionFromValue$1,
      onLeft: onLeft$1,
      onRight: onRight$1,
      onUp: onUp$1,
      onDown: onDown$1,
      edgeActions: edgeActions$1
    });
    var fireSliderChange = function(spectrum, value2) {
      emitWith(spectrum, sliderChangeEvent(), { value: value2 });
    };
    var sliderValue = function(x2, y2) {
      return {
        x: x2,
        y: y2
      };
    };
    var setValueFrom = function(spectrum, detail, value2) {
      var xValue2 = findValueOfOffset$1(spectrum, detail, value2.left);
      var yValue2 = findValueOfOffset(spectrum, detail, value2.top);
      var val = sliderValue(xValue2, yValue2);
      fireSliderChange(spectrum, val);
      return val;
    };
    var moveBy = function(direction, isVerticalMovement, spectrum, detail) {
      var f2 = direction > 0 ? increaseBy : reduceBy;
      var xValue2 = isVerticalMovement ? currentValue(detail).x : f2(currentValue(detail).x, minX(detail), maxX(detail), step(detail));
      var yValue2 = !isVerticalMovement ? currentValue(detail).y : f2(currentValue(detail).y, minY(detail), maxY(detail), step(detail));
      fireSliderChange(spectrum, sliderValue(xValue2, yValue2));
      return Optional.some(xValue2);
    };
    var handleMovement = function(direction, isVerticalMovement) {
      return function(spectrum, detail) {
        return moveBy(direction, isVerticalMovement, spectrum, detail).map(always);
      };
    };
    var setToMin = function(spectrum, detail) {
      var mX = minX(detail);
      var mY = minY(detail);
      fireSliderChange(spectrum, sliderValue(mX, mY));
    };
    var setToMax = function(spectrum, detail) {
      var mX = maxX(detail);
      var mY = maxY(detail);
      fireSliderChange(spectrum, sliderValue(mX, mY));
    };
    var getValueFromEvent = function(simulatedEvent) {
      return getEventSource(simulatedEvent);
    };
    var setPositionFromValue = function(slider, thumb, detail, edges) {
      var value2 = currentValue(detail);
      var xPos = findPositionOfValue$1(slider, edges.getSpectrum(slider), value2.x, edges.getLeftEdge(slider), edges.getRightEdge(slider), detail);
      var yPos = findPositionOfValue(slider, edges.getSpectrum(slider), value2.y, edges.getTopEdge(slider), edges.getBottomEdge(slider), detail);
      var thumbXRadius = get$a(thumb.element) / 2;
      var thumbYRadius = get$b(thumb.element) / 2;
      set$7(thumb.element, "left", xPos - thumbXRadius + "px");
      set$7(thumb.element, "top", yPos - thumbYRadius + "px");
    };
    var onLeft = handleMovement(-1, false);
    var onRight = handleMovement(1, false);
    var onUp = handleMovement(-1, true);
    var onDown = handleMovement(1, true);
    var edgeActions = {
      "top-left": Optional.some(setToTLEdgeXY),
      "top": Optional.some(setToTEdgeXY),
      "top-right": Optional.some(setToTREdgeXY),
      "right": Optional.some(setToREdgeXY),
      "bottom-right": Optional.some(setToBREdgeXY),
      "bottom": Optional.some(setToBEdgeXY),
      "bottom-left": Optional.some(setToBLEdgeXY),
      "left": Optional.some(setToLEdgeXY)
    };
    var TwoDModel = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      setValueFrom,
      setToMin,
      setToMax,
      getValueFromEvent,
      setPositionFromValue,
      onLeft,
      onRight,
      onUp,
      onDown,
      edgeActions
    });
    var SliderSchema = [
      defaulted("stepSize", 1),
      defaulted("onChange", noop3),
      defaulted("onChoose", noop3),
      defaulted("onInit", noop3),
      defaulted("onDragStart", noop3),
      defaulted("onDragEnd", noop3),
      defaulted("snapToGrid", false),
      defaulted("rounded", true),
      option("snapStart"),
      requiredOf("model", choose$1("mode", {
        x: [
          defaulted("minX", 0),
          defaulted("maxX", 100),
          customField("value", function(spec) {
            return Cell(spec.mode.minX);
          }),
          required$1("getInitialValue"),
          output$1("manager", HorizontalModel)
        ],
        y: [
          defaulted("minY", 0),
          defaulted("maxY", 100),
          customField("value", function(spec) {
            return Cell(spec.mode.minY);
          }),
          required$1("getInitialValue"),
          output$1("manager", VerticalModel)
        ],
        xy: [
          defaulted("minX", 0),
          defaulted("maxX", 100),
          defaulted("minY", 0),
          defaulted("maxY", 100),
          customField("value", function(spec) {
            return Cell({
              x: spec.mode.minX,
              y: spec.mode.minY
            });
          }),
          required$1("getInitialValue"),
          output$1("manager", TwoDModel)
        ]
      })),
      field("sliderBehaviours", [
        Keying,
        Representing
      ]),
      customField("mouseIsDown", function() {
        return Cell(false);
      })
    ];
    var sketch$2 = function(detail, components2, _spec, _externals) {
      var _a2;
      var getThumb = function(component) {
        return getPartOrDie(component, detail, "thumb");
      };
      var getSpectrum = function(component) {
        return getPartOrDie(component, detail, "spectrum");
      };
      var getLeftEdge = function(component) {
        return getPart(component, detail, "left-edge");
      };
      var getRightEdge = function(component) {
        return getPart(component, detail, "right-edge");
      };
      var getTopEdge = function(component) {
        return getPart(component, detail, "top-edge");
      };
      var getBottomEdge = function(component) {
        return getPart(component, detail, "bottom-edge");
      };
      var modelDetail = detail.model;
      var model = modelDetail.manager;
      var refresh2 = function(slider, thumb) {
        model.setPositionFromValue(slider, thumb, detail, {
          getLeftEdge,
          getRightEdge,
          getTopEdge,
          getBottomEdge,
          getSpectrum
        });
      };
      var setValue2 = function(slider, newValue) {
        modelDetail.value.set(newValue);
        var thumb = getThumb(slider);
        refresh2(slider, thumb);
      };
      var changeValue = function(slider, newValue) {
        setValue2(slider, newValue);
        var thumb = getThumb(slider);
        detail.onChange(slider, thumb, newValue);
        return Optional.some(true);
      };
      var resetToMin = function(slider) {
        model.setToMin(slider, detail);
      };
      var resetToMax = function(slider) {
        model.setToMax(slider, detail);
      };
      var choose2 = function(slider) {
        var fireOnChoose = function() {
          getPart(slider, detail, "thumb").each(function(thumb) {
            var value2 = modelDetail.value.get();
            detail.onChoose(slider, thumb, value2);
          });
        };
        var wasDown = detail.mouseIsDown.get();
        detail.mouseIsDown.set(false);
        if (wasDown) {
          fireOnChoose();
        }
      };
      var onDragStart = function(slider, simulatedEvent) {
        simulatedEvent.stop();
        detail.mouseIsDown.set(true);
        detail.onDragStart(slider, getThumb(slider));
      };
      var onDragEnd = function(slider, simulatedEvent) {
        simulatedEvent.stop();
        detail.onDragEnd(slider, getThumb(slider));
        choose2(slider);
      };
      return {
        uid: detail.uid,
        dom: detail.dom,
        components: components2,
        behaviours: augment(detail.sliderBehaviours, [
          Keying.config({
            mode: "special",
            focusIn: function(slider) {
              return getPart(slider, detail, "spectrum").map(Keying.focusIn).map(always);
            }
          }),
          Representing.config({
            store: {
              mode: "manual",
              getValue: function(_2) {
                return modelDetail.value.get();
              }
            }
          }),
          Receiving.config({ channels: (_a2 = {}, _a2[mouseReleased()] = { onReceive: choose2 }, _a2) })
        ]),
        events: derive$2([
          run$1(sliderChangeEvent(), function(slider, simulatedEvent) {
            changeValue(slider, simulatedEvent.event.value);
          }),
          runOnAttached(function(slider, _simulatedEvent) {
            var getInitial = modelDetail.getInitialValue();
            modelDetail.value.set(getInitial);
            var thumb = getThumb(slider);
            refresh2(slider, thumb);
            var spectrum = getSpectrum(slider);
            detail.onInit(slider, thumb, spectrum, modelDetail.value.get());
          }),
          run$1(touchstart(), onDragStart),
          run$1(touchend(), onDragEnd),
          run$1(mousedown(), onDragStart),
          run$1(mouseup(), onDragEnd)
        ]),
        apis: {
          resetToMin,
          resetToMax,
          setValue: setValue2,
          refresh: refresh2
        },
        domModification: { styles: { position: "relative" } }
      };
    };
    var Slider = composite({
      name: "Slider",
      configFields: SliderSchema,
      partFields: SliderParts,
      factory: sketch$2,
      apis: {
        setValue: function(apis, slider, value2) {
          apis.setValue(slider, value2);
        },
        resetToMin: function(apis, slider) {
          apis.resetToMin(slider);
        },
        resetToMax: function(apis, slider) {
          apis.resetToMax(slider);
        },
        refresh: function(apis, slider) {
          apis.refresh(slider);
        }
      }
    });
    var fieldsUpdate = generate$6("rgb-hex-update");
    var sliderUpdate = generate$6("slider-update");
    var paletteUpdate = generate$6("palette-update");
    var sliderFactory = function(translate2, getClass) {
      var spectrum = Slider.parts.spectrum({
        dom: {
          tag: "div",
          classes: [getClass("hue-slider-spectrum")],
          attributes: { role: "presentation" }
        }
      });
      var thumb = Slider.parts.thumb({
        dom: {
          tag: "div",
          classes: [getClass("hue-slider-thumb")],
          attributes: { role: "presentation" }
        }
      });
      return Slider.sketch({
        dom: {
          tag: "div",
          classes: [getClass("hue-slider")],
          attributes: { role: "presentation" }
        },
        rounded: false,
        model: {
          mode: "y",
          getInitialValue: constant$1({ y: 0 })
        },
        components: [
          spectrum,
          thumb
        ],
        sliderBehaviours: derive$1([Focusing.config({})]),
        onChange: function(slider, _thumb, value2) {
          emitWith(slider, sliderUpdate, { value: value2 });
        }
      });
    };
    var owner$1 = "form";
    var schema$i = [field("formBehaviours", [Representing])];
    var getPartName$1 = function(name2) {
      return "<alloy.field." + name2 + ">";
    };
    var sketch$1 = function(fSpec) {
      var parts2 = function() {
        var record2 = [];
        var field2 = function(name2, config2) {
          record2.push(name2);
          return generateOne$1(owner$1, getPartName$1(name2), config2);
        };
        return {
          field: field2,
          record: constant$1(record2)
        };
      }();
      var spec = fSpec(parts2);
      var partNames = parts2.record();
      var fieldParts = map$2(partNames, function(n2) {
        return required({
          name: n2,
          pname: getPartName$1(n2)
        });
      });
      return composite$1(owner$1, schema$i, fieldParts, make$4, spec);
    };
    var toResult = function(o2, e2) {
      return o2.fold(function() {
        return Result.error(e2);
      }, Result.value);
    };
    var make$4 = function(detail, components2) {
      return {
        uid: detail.uid,
        dom: detail.dom,
        components: components2,
        behaviours: augment(detail.formBehaviours, [Representing.config({
          store: {
            mode: "manual",
            getValue: function(form) {
              var resPs = getAllParts(form, detail);
              return map$12(resPs, function(resPThunk, pName) {
                return resPThunk().bind(function(v2) {
                  var opt = Composing.getCurrent(v2);
                  return toResult(opt, new Error("Cannot find a current component to extract the value from for form part '" + pName + "': " + element(v2.element)));
                }).map(Representing.getValue);
              });
            },
            setValue: function(form, values2) {
              each2(values2, function(newValue, key) {
                getPart(form, detail, key).each(function(wrapper) {
                  Composing.getCurrent(wrapper).each(function(field2) {
                    Representing.setValue(field2, newValue);
                  });
                });
              });
            }
          }
        })]),
        apis: {
          getField: function(form, key) {
            return getPart(form, detail, key).bind(Composing.getCurrent);
          }
        }
      };
    };
    var Form = {
      getField: makeApi(function(apis, component, key) {
        return apis.getField(component, key);
      }),
      sketch: sketch$1
    };
    var validInput = generate$6("valid-input");
    var invalidInput = generate$6("invalid-input");
    var validatingInput = generate$6("validating-input");
    var translatePrefix = "colorcustom.rgb.";
    var rgbFormFactory = function(translate2, getClass, onValidHexx, onInvalidHexx) {
      var invalidation = function(label, isValid2) {
        return Invalidating.config({
          invalidClass: getClass("invalid"),
          notify: {
            onValidate: function(comp) {
              emitWith(comp, validatingInput, { type: label });
            },
            onValid: function(comp) {
              emitWith(comp, validInput, {
                type: label,
                value: Representing.getValue(comp)
              });
            },
            onInvalid: function(comp) {
              emitWith(comp, invalidInput, {
                type: label,
                value: Representing.getValue(comp)
              });
            }
          },
          validator: {
            validate: function(comp) {
              var value2 = Representing.getValue(comp);
              var res = isValid2(value2) ? Result.value(true) : Result.error(translate2("aria.input.invalid"));
              return Future.pure(res);
            },
            validateOnLoad: false
          }
        });
      };
      var renderTextField2 = function(isValid2, name2, label, description, data) {
        var helptext = translate2(translatePrefix + "range");
        var pLabel = FormField.parts.label({
          dom: {
            tag: "label",
            innerHtml: label,
            attributes: { "aria-label": description }
          }
        });
        var pField = FormField.parts.field({
          data,
          factory: Input,
          inputAttributes: __assign({ type: "text" }, name2 === "hex" ? { "aria-live": "polite" } : {}),
          inputClasses: [getClass("textfield")],
          inputBehaviours: derive$1([
            invalidation(name2, isValid2),
            Tabstopping.config({})
          ]),
          onSetValue: function(input2) {
            if (Invalidating.isInvalid(input2)) {
              var run2 = Invalidating.run(input2);
              run2.get(noop3);
            }
          }
        });
        var comps = [
          pLabel,
          pField
        ];
        var concats = name2 !== "hex" ? [FormField.parts["aria-descriptor"]({ text: helptext })] : [];
        var components2 = comps.concat(concats);
        return {
          dom: {
            tag: "div",
            attributes: { role: "presentation" }
          },
          components: components2
        };
      };
      var copyRgbToHex = function(form, rgba) {
        var hex2 = fromRgba(rgba);
        Form.getField(form, "hex").each(function(hexField) {
          if (!Focusing.isFocused(hexField)) {
            Representing.setValue(form, { hex: hex2.value });
          }
        });
        return hex2;
      };
      var copyRgbToForm = function(form, rgb) {
        var red2 = rgb.red;
        var green = rgb.green;
        var blue = rgb.blue;
        Representing.setValue(form, {
          red: red2,
          green,
          blue
        });
      };
      var memPreview = record({
        dom: {
          tag: "div",
          classes: [getClass("rgba-preview")],
          styles: { "background-color": "white" },
          attributes: { role: "presentation" }
        }
      });
      var updatePreview = function(anyInSystem, hex2) {
        memPreview.getOpt(anyInSystem).each(function(preview) {
          set$7(preview.element, "background-color", "#" + hex2.value);
        });
      };
      var factory2 = function() {
        var state = {
          red: Cell(Optional.some(255)),
          green: Cell(Optional.some(255)),
          blue: Cell(Optional.some(255)),
          hex: Cell(Optional.some("ffffff"))
        };
        var copyHexToRgb = function(form, hex2) {
          var rgb = fromHex(hex2);
          copyRgbToForm(form, rgb);
          setValueRgb(rgb);
        };
        var get2 = function(prop) {
          return state[prop].get();
        };
        var set3 = function(prop, value2) {
          state[prop].set(value2);
        };
        var getValueRgb = function() {
          return get2("red").bind(function(red2) {
            return get2("green").bind(function(green) {
              return get2("blue").map(function(blue) {
                return rgbaColour(red2, green, blue, 1);
              });
            });
          });
        };
        var setValueRgb = function(rgb) {
          var red2 = rgb.red;
          var green = rgb.green;
          var blue = rgb.blue;
          set3("red", Optional.some(red2));
          set3("green", Optional.some(green));
          set3("blue", Optional.some(blue));
        };
        var onInvalidInput = function(form, simulatedEvent) {
          var data = simulatedEvent.event;
          if (data.type !== "hex") {
            set3(data.type, Optional.none());
          } else {
            onInvalidHexx(form);
          }
        };
        var onValidHex = function(form, value2) {
          onValidHexx(form);
          var hex2 = hexColour(value2);
          set3("hex", Optional.some(value2));
          var rgb = fromHex(hex2);
          copyRgbToForm(form, rgb);
          setValueRgb(rgb);
          emitWith(form, fieldsUpdate, { hex: hex2 });
          updatePreview(form, hex2);
        };
        var onValidRgb = function(form, prop, value2) {
          var val = parseInt(value2, 10);
          set3(prop, Optional.some(val));
          getValueRgb().each(function(rgb) {
            var hex2 = copyRgbToHex(form, rgb);
            emitWith(form, fieldsUpdate, { hex: hex2 });
            updatePreview(form, hex2);
          });
        };
        var isHexInputEvent = function(data) {
          return data.type === "hex";
        };
        var onValidInput = function(form, simulatedEvent) {
          var data = simulatedEvent.event;
          if (isHexInputEvent(data)) {
            onValidHex(form, data.value);
          } else {
            onValidRgb(form, data.type, data.value);
          }
        };
        var formPartStrings = function(key) {
          return {
            label: translate2(translatePrefix + key + ".label"),
            description: translate2(translatePrefix + key + ".description")
          };
        };
        var redStrings = formPartStrings("red");
        var greenStrings = formPartStrings("green");
        var blueStrings = formPartStrings("blue");
        var hexStrings = formPartStrings("hex");
        return deepMerge(Form.sketch(function(parts2) {
          return {
            dom: {
              tag: "form",
              classes: [getClass("rgb-form")],
              attributes: { "aria-label": translate2("aria.color.picker") }
            },
            components: [
              parts2.field("red", FormField.sketch(renderTextField2(isRgbaComponent, "red", redStrings.label, redStrings.description, 255))),
              parts2.field("green", FormField.sketch(renderTextField2(isRgbaComponent, "green", greenStrings.label, greenStrings.description, 255))),
              parts2.field("blue", FormField.sketch(renderTextField2(isRgbaComponent, "blue", blueStrings.label, blueStrings.description, 255))),
              parts2.field("hex", FormField.sketch(renderTextField2(isHexString, "hex", hexStrings.label, hexStrings.description, "ffffff"))),
              memPreview.asSpec()
            ],
            formBehaviours: derive$1([
              Invalidating.config({ invalidClass: getClass("form-invalid") }),
              config("rgb-form-events", [
                run$1(validInput, onValidInput),
                run$1(invalidInput, onInvalidInput),
                run$1(validatingInput, onInvalidInput)
              ])
            ])
          };
        }), {
          apis: {
            updateHex: function(form, hex2) {
              Representing.setValue(form, { hex: hex2.value });
              copyHexToRgb(form, hex2);
              updatePreview(form, hex2);
            }
          }
        });
      };
      var rgbFormSketcher = single({
        factory: factory2,
        name: "RgbForm",
        configFields: [],
        apis: {
          updateHex: function(apis, form, hex2) {
            apis.updateHex(form, hex2);
          }
        },
        extraApis: {}
      });
      return rgbFormSketcher;
    };
    var paletteFactory = function(_translate, getClass) {
      var spectrumPart2 = Slider.parts.spectrum({
        dom: {
          tag: "canvas",
          attributes: { role: "presentation" },
          classes: [getClass("sv-palette-spectrum")]
        }
      });
      var thumbPart2 = Slider.parts.thumb({
        dom: {
          tag: "div",
          attributes: { role: "presentation" },
          classes: [getClass("sv-palette-thumb")],
          innerHtml: "<div class=" + getClass("sv-palette-inner-thumb") + ' role="presentation"></div>'
        }
      });
      var setColour = function(canvas, rgba) {
        var width2 = canvas.width, height2 = canvas.height;
        var ctx = canvas.getContext("2d");
        if (ctx === null) {
          return;
        }
        ctx.fillStyle = rgba;
        ctx.fillRect(0, 0, width2, height2);
        var grdWhite = ctx.createLinearGradient(0, 0, width2, 0);
        grdWhite.addColorStop(0, "rgba(255,255,255,1)");
        grdWhite.addColorStop(1, "rgba(255,255,255,0)");
        ctx.fillStyle = grdWhite;
        ctx.fillRect(0, 0, width2, height2);
        var grdBlack = ctx.createLinearGradient(0, 0, 0, height2);
        grdBlack.addColorStop(0, "rgba(0,0,0,0)");
        grdBlack.addColorStop(1, "rgba(0,0,0,1)");
        ctx.fillStyle = grdBlack;
        ctx.fillRect(0, 0, width2, height2);
      };
      var setPaletteHue = function(slider, hue2) {
        var canvas = slider.components()[0].element.dom;
        var hsv = hsvColour(hue2, 100, 100);
        var rgba = fromHsv(hsv);
        setColour(canvas, toString(rgba));
      };
      var setPaletteThumb = function(slider, hex2) {
        var hsv = fromRgb(fromHex(hex2));
        Slider.setValue(slider, {
          x: hsv.saturation,
          y: 100 - hsv.value
        });
      };
      var factory2 = function(_detail) {
        var getInitialValue = constant$1({
          x: 0,
          y: 0
        });
        var onChange = function(slider, _thumb, value2) {
          emitWith(slider, paletteUpdate, { value: value2 });
        };
        var onInit = function(_slider, _thumb, spectrum, _value) {
          setColour(spectrum.element.dom, toString(red));
        };
        var sliderBehaviours = derive$1([
          Composing.config({ find: Optional.some }),
          Focusing.config({})
        ]);
        return Slider.sketch({
          dom: {
            tag: "div",
            attributes: { role: "presentation" },
            classes: [getClass("sv-palette")]
          },
          model: {
            mode: "xy",
            getInitialValue
          },
          rounded: false,
          components: [
            spectrumPart2,
            thumbPart2
          ],
          onChange,
          onInit,
          sliderBehaviours
        });
      };
      var saturationBrightnessPaletteSketcher = single({
        factory: factory2,
        name: "SaturationBrightnessPalette",
        configFields: [],
        apis: {
          setHue: function(_apis, slider, hue2) {
            setPaletteHue(slider, hue2);
          },
          setThumb: function(_apis, slider, hex2) {
            setPaletteThumb(slider, hex2);
          }
        },
        extraApis: {}
      });
      return saturationBrightnessPaletteSketcher;
    };
    var makeFactory = function(translate2, getClass) {
      var factory2 = function(detail) {
        var rgbForm = rgbFormFactory(translate2, getClass, detail.onValidHex, detail.onInvalidHex);
        var sbPalette = paletteFactory(translate2, getClass);
        var hueSliderToDegrees = function(hue2) {
          return (100 - hue2) / 100 * 360;
        };
        var hueDegreesToSlider = function(hue2) {
          return 100 - hue2 / 360 * 100;
        };
        var state = {
          paletteRgba: Cell(red),
          paletteHue: Cell(0)
        };
        var memSlider = record(sliderFactory(translate2, getClass));
        var memPalette = record(sbPalette.sketch({}));
        var memRgb = record(rgbForm.sketch({}));
        var updatePalette = function(anyInSystem, _hex, hue2) {
          memPalette.getOpt(anyInSystem).each(function(palette) {
            sbPalette.setHue(palette, hue2);
          });
        };
        var updateFields = function(anyInSystem, hex2) {
          memRgb.getOpt(anyInSystem).each(function(form) {
            rgbForm.updateHex(form, hex2);
          });
        };
        var updateSlider = function(anyInSystem, _hex, hue2) {
          memSlider.getOpt(anyInSystem).each(function(slider) {
            Slider.setValue(slider, { y: hueDegreesToSlider(hue2) });
          });
        };
        var updatePaletteThumb = function(anyInSystem, hex2) {
          memPalette.getOpt(anyInSystem).each(function(palette) {
            sbPalette.setThumb(palette, hex2);
          });
        };
        var updateState = function(hex2, hue2) {
          var rgba = fromHex(hex2);
          state.paletteRgba.set(rgba);
          state.paletteHue.set(hue2);
        };
        var runUpdates = function(anyInSystem, hex2, hue2, updates) {
          updateState(hex2, hue2);
          each$1(updates, function(update) {
            update(anyInSystem, hex2, hue2);
          });
        };
        var onPaletteUpdate = function() {
          var updates = [updateFields];
          return function(form, simulatedEvent) {
            var value2 = simulatedEvent.event.value;
            var oldHue = state.paletteHue.get();
            var newHsv = hsvColour(oldHue, value2.x, 100 - value2.y);
            var newHex = hsvToHex(newHsv);
            runUpdates(form, newHex, oldHue, updates);
          };
        };
        var onSliderUpdate = function() {
          var updates = [
            updatePalette,
            updateFields
          ];
          return function(form, simulatedEvent) {
            var hue2 = hueSliderToDegrees(simulatedEvent.event.value.y);
            var oldRgb = state.paletteRgba.get();
            var oldHsv = fromRgb(oldRgb);
            var newHsv = hsvColour(hue2, oldHsv.saturation, oldHsv.value);
            var newHex = hsvToHex(newHsv);
            runUpdates(form, newHex, hue2, updates);
          };
        };
        var onFieldsUpdate = function() {
          var updates = [
            updatePalette,
            updateSlider,
            updatePaletteThumb
          ];
          return function(form, simulatedEvent) {
            var hex2 = simulatedEvent.event.hex;
            var hsv = hexToHsv(hex2);
            runUpdates(form, hex2, hsv.hue, updates);
          };
        };
        return {
          uid: detail.uid,
          dom: detail.dom,
          components: [
            memPalette.asSpec(),
            memSlider.asSpec(),
            memRgb.asSpec()
          ],
          behaviours: derive$1([
            config("colour-picker-events", [
              run$1(fieldsUpdate, onFieldsUpdate()),
              run$1(paletteUpdate, onPaletteUpdate()),
              run$1(sliderUpdate, onSliderUpdate())
            ]),
            Composing.config({
              find: function(comp) {
                return memRgb.getOpt(comp);
              }
            }),
            Keying.config({ mode: "acyclic" })
          ])
        };
      };
      var colourPickerSketcher = single({
        name: "ColourPicker",
        configFields: [
          required$1("dom"),
          defaulted("onValidHex", noop3),
          defaulted("onInvalidHex", noop3)
        ],
        factory: factory2
      });
      return colourPickerSketcher;
    };
    var self$1 = function() {
      return Composing.config({ find: Optional.some });
    };
    var memento$1 = function(mem) {
      return Composing.config({ find: mem.getOpt });
    };
    var childAt = function(index) {
      return Composing.config({
        find: function(comp) {
          return child$2(comp.element, index).bind(function(element2) {
            return comp.getSystem().getByDom(element2).toOptional();
          });
        }
      });
    };
    var ComposingConfigs = {
      self: self$1,
      memento: memento$1,
      childAt
    };
    var english = {
      "colorcustom.rgb.red.label": "R",
      "colorcustom.rgb.red.description": "Red component",
      "colorcustom.rgb.green.label": "G",
      "colorcustom.rgb.green.description": "Green component",
      "colorcustom.rgb.blue.label": "B",
      "colorcustom.rgb.blue.description": "Blue component",
      "colorcustom.rgb.hex.label": "#",
      "colorcustom.rgb.hex.description": "Hex color code",
      "colorcustom.rgb.range": "Range 0 to 255",
      "colorcustom.sb.saturation": "Saturation",
      "colorcustom.sb.brightness": "Brightness",
      "colorcustom.sb.picker": "Saturation and Brightness Picker",
      "colorcustom.sb.palette": "Saturation and Brightness Palette",
      "colorcustom.sb.instructions": "Use arrow keys to select saturation and brightness, on x and y axes",
      "colorcustom.hue.hue": "Hue",
      "colorcustom.hue.slider": "Hue Slider",
      "colorcustom.hue.palette": "Hue Palette",
      "colorcustom.hue.instructions": "Use arrow keys to select a hue",
      "aria.color.picker": "Color Picker",
      "aria.input.invalid": "Invalid input"
    };
    var getEnglishText = function(key) {
      return english[key];
    };
    var translate$1 = function(key) {
      return getEnglishText(key);
    };
    var renderColorPicker = function(_spec) {
      var getClass = function(key) {
        return "tox-" + key;
      };
      var colourPickerFactory = makeFactory(translate$1, getClass);
      var onValidHex = function(form) {
        emitWith(form, formActionEvent, {
          name: "hex-valid",
          value: true
        });
      };
      var onInvalidHex = function(form) {
        emitWith(form, formActionEvent, {
          name: "hex-valid",
          value: false
        });
      };
      var memPicker = record(colourPickerFactory.sketch({
        dom: {
          tag: "div",
          classes: [getClass("color-picker-container")],
          attributes: { role: "presentation" }
        },
        onValidHex,
        onInvalidHex
      }));
      return {
        dom: { tag: "div" },
        components: [memPicker.asSpec()],
        behaviours: derive$1([
          Representing.config({
            store: {
              mode: "manual",
              getValue: function(comp) {
                var picker = memPicker.get(comp);
                var optRgbForm = Composing.getCurrent(picker);
                var optHex = optRgbForm.bind(function(rgbForm) {
                  var formValues = Representing.getValue(rgbForm);
                  return formValues.hex;
                });
                return optHex.map(function(hex2) {
                  return "#" + hex2;
                }).getOr("");
              },
              setValue: function(comp, newValue) {
                var pattern2 = /^#([a-fA-F0-9]{3}(?:[a-fA-F0-9]{3})?)/;
                var m2 = pattern2.exec(newValue);
                var picker = memPicker.get(comp);
                var optRgbForm = Composing.getCurrent(picker);
                optRgbForm.fold(function() {
                  console.log("Can not find form");
                }, function(rgbForm) {
                  Representing.setValue(rgbForm, { hex: Optional.from(m2[1]).getOr("") });
                  Form.getField(rgbForm, "hex").each(function(hexField) {
                    emit(hexField, input());
                  });
                });
              }
            }
          }),
          ComposingConfigs.self()
        ])
      };
    };
    var global$6 = tinymce.util.Tools.resolve("tinymce.Resource");
    var isOldCustomEditor = function(spec) {
      return has$2(spec, "init");
    };
    var renderCustomEditor = function(spec) {
      var editorApi = value$1();
      var memReplaced = record({ dom: { tag: spec.tag } });
      var initialValue = value$1();
      return {
        dom: {
          tag: "div",
          classes: ["tox-custom-editor"]
        },
        behaviours: derive$1([
          config("custom-editor-events", [runOnAttached(function(component) {
            memReplaced.getOpt(component).each(function(ta) {
              (isOldCustomEditor(spec) ? spec.init(ta.element.dom) : global$6.load(spec.scriptId, spec.scriptUrl).then(function(init2) {
                return init2(ta.element.dom, spec.settings);
              })).then(function(ea) {
                initialValue.on(function(cvalue) {
                  ea.setValue(cvalue);
                });
                initialValue.clear();
                editorApi.set(ea);
              });
            });
          })]),
          Representing.config({
            store: {
              mode: "manual",
              getValue: function() {
                return editorApi.get().fold(function() {
                  return initialValue.get().getOr("");
                }, function(ed) {
                  return ed.getValue();
                });
              },
              setValue: function(component, value2) {
                editorApi.get().fold(function() {
                  initialValue.set(value2);
                }, function(ed) {
                  return ed.setValue(value2);
                });
              }
            }
          }),
          ComposingConfigs.self()
        ]),
        components: [memReplaced.asSpec()]
      };
    };
    var global$5 = tinymce.util.Tools.resolve("tinymce.util.Tools");
    var processors = objOf([
      defaulted("preprocess", identity$1),
      defaulted("postprocess", identity$1)
    ]);
    var memento = function(mem, rawProcessors) {
      var ps = asRawOrDie$1("RepresentingConfigs.memento processors", processors, rawProcessors);
      return Representing.config({
        store: {
          mode: "manual",
          getValue: function(comp) {
            var other = mem.get(comp);
            var rawValue = Representing.getValue(other);
            return ps.postprocess(rawValue);
          },
          setValue: function(comp, rawValue) {
            var newValue = ps.preprocess(rawValue);
            var other = mem.get(comp);
            Representing.setValue(other, newValue);
          }
        }
      });
    };
    var withComp = function(optInitialValue, getter, setter) {
      return Representing.config(deepMerge({
        store: {
          mode: "manual",
          getValue: getter,
          setValue: setter
        }
      }, optInitialValue.map(function(initialValue) {
        return { store: { initialValue } };
      }).getOr({})));
    };
    var withElement = function(initialValue, getter, setter) {
      return withComp(initialValue, function(c2) {
        return getter(c2.element);
      }, function(c2, v2) {
        return setter(c2.element, v2);
      });
    };
    var domValue = function(optInitialValue) {
      return withElement(optInitialValue, get$5, set$4);
    };
    var domHtml = function(optInitialValue) {
      return withElement(optInitialValue, get$7, set$5);
    };
    var memory = function(initialValue) {
      return Representing.config({
        store: {
          mode: "memory",
          initialValue
        }
      });
    };
    var RepresentingConfigs = {
      memento,
      withElement,
      withComp,
      domValue,
      domHtml,
      memory
    };
    var defaultImageFileTypes = "jpeg,jpg,jpe,jfi,jif,jfif,png,gif,bmp,webp";
    var filterByExtension = function(files, providersBackstage) {
      var allowedImageFileTypes = global$5.explode(providersBackstage.getSetting("images_file_types", defaultImageFileTypes, "string"));
      var isFileInAllowedTypes = function(file) {
        return exists(allowedImageFileTypes, function(type2) {
          return endsWith(file.name.toLowerCase(), "." + type2.toLowerCase());
        });
      };
      return filter$2(from(files), isFileInAllowedTypes);
    };
    var renderDropZone = function(spec, providersBackstage) {
      var stopper2 = function(_2, se2) {
        se2.stop();
      };
      var sequence2 = function(actions) {
        return function(comp, se2) {
          each$1(actions, function(a2) {
            a2(comp, se2);
          });
        };
      };
      var onDrop = function(comp, se2) {
        if (!Disabling.isDisabled(comp)) {
          var transferEvent = se2.event.raw;
          handleFiles(comp, transferEvent.dataTransfer.files);
        }
      };
      var onSelect = function(component, simulatedEvent) {
        var input2 = simulatedEvent.event.raw.target;
        handleFiles(component, input2.files);
      };
      var handleFiles = function(component, files) {
        Representing.setValue(component, filterByExtension(files, providersBackstage));
        emitWith(component, formChangeEvent, { name: spec.name });
      };
      var memInput = record({
        dom: {
          tag: "input",
          attributes: {
            type: "file",
            accept: "image/*"
          },
          styles: { display: "none" }
        },
        behaviours: derive$1([config("input-file-events", [
          cutter(click()),
          cutter(tap())
        ])])
      });
      var renderField = function(s2) {
        return {
          uid: s2.uid,
          dom: {
            tag: "div",
            classes: ["tox-dropzone-container"]
          },
          behaviours: derive$1([
            RepresentingConfigs.memory([]),
            ComposingConfigs.self(),
            Disabling.config({}),
            Toggling.config({
              toggleClass: "dragenter",
              toggleOnExecute: false
            }),
            config("dropzone-events", [
              run$1("dragenter", sequence2([
                stopper2,
                Toggling.toggle
              ])),
              run$1("dragleave", sequence2([
                stopper2,
                Toggling.toggle
              ])),
              run$1("dragover", stopper2),
              run$1("drop", sequence2([
                stopper2,
                onDrop
              ])),
              run$1(change(), onSelect)
            ])
          ]),
          components: [{
            dom: {
              tag: "div",
              classes: ["tox-dropzone"],
              styles: {}
            },
            components: [
              {
                dom: {
                  tag: "p",
                  innerHtml: providersBackstage.translate("Drop an image here")
                }
              },
              Button2.sketch({
                dom: {
                  tag: "button",
                  innerHtml: providersBackstage.translate("Browse for an image"),
                  styles: { position: "relative" },
                  classes: [
                    "tox-button",
                    "tox-button--secondary"
                  ]
                },
                components: [memInput.asSpec()],
                action: function(comp) {
                  var inputComp = memInput.get(comp);
                  inputComp.element.dom.click();
                },
                buttonBehaviours: derive$1([
                  Tabstopping.config({}),
                  DisablingConfigs.button(providersBackstage.isDisabled),
                  receivingConfig()
                ])
              })
            ]
          }]
        };
      };
      var pLabel = spec.label.map(function(label) {
        return renderLabel$2(label, providersBackstage);
      });
      var pField = FormField.parts.field({ factory: { sketch: renderField } });
      return renderFormFieldWith(pLabel, pField, ["tox-form__group--stretched"], []);
    };
    var renderGrid = function(spec, backstage) {
      return {
        dom: {
          tag: "div",
          classes: [
            "tox-form__grid",
            "tox-form__grid--" + spec.columns + "col"
          ]
        },
        components: map$2(spec.items, backstage.interpreter)
      };
    };
    var beforeObject = generate$6("alloy-fake-before-tabstop");
    var afterObject = generate$6("alloy-fake-after-tabstop");
    var craftWithClasses = function(classes2) {
      return {
        dom: {
          tag: "div",
          styles: {
            width: "1px",
            height: "1px",
            outline: "none"
          },
          attributes: { tabindex: "0" },
          classes: classes2
        },
        behaviours: derive$1([
          Focusing.config({ ignore: true }),
          Tabstopping.config({})
        ])
      };
    };
    var craft = function(spec) {
      return {
        dom: {
          tag: "div",
          classes: ["tox-navobj"]
        },
        components: [
          craftWithClasses([beforeObject]),
          spec,
          craftWithClasses([afterObject])
        ],
        behaviours: derive$1([ComposingConfigs.childAt(1)])
      };
    };
    var triggerTab = function(placeholder2, shiftKey) {
      emitWith(placeholder2, keydown(), {
        raw: {
          which: 9,
          shiftKey
        }
      });
    };
    var onFocus = function(container, targetComp) {
      var target = targetComp.element;
      if (has(target, beforeObject)) {
        triggerTab(container, true);
      } else if (has(target, afterObject)) {
        triggerTab(container, false);
      }
    };
    var isPseudoStop = function(element2) {
      return closest(element2, [
        "." + beforeObject,
        "." + afterObject
      ].join(","), never);
    };
    var platformNeedsSandboxing = !(detect$1().browser.isIE() || detect$1().browser.isEdge());
    var getDynamicSource = function(isSandbox) {
      var cachedValue = Cell("");
      return {
        getValue: function(_frameComponent) {
          return cachedValue.get();
        },
        setValue: function(frameComponent, html) {
          if (!isSandbox) {
            set$8(frameComponent.element, "src", "javascript:''");
            var doc = frameComponent.element.dom.contentWindow.document;
            doc.open();
            doc.write(html);
            doc.close();
          } else {
            set$8(frameComponent.element, "srcdoc", html);
          }
          cachedValue.set(html);
        }
      };
    };
    var renderIFrame = function(spec, providersBackstage) {
      var isSandbox = platformNeedsSandboxing && spec.sandboxed;
      var attributes = __assign(__assign({}, spec.label.map(function(title) {
        return { title };
      }).getOr({})), isSandbox ? { sandbox: "allow-scripts allow-same-origin" } : {});
      var sourcing = getDynamicSource(isSandbox);
      var pLabel = spec.label.map(function(label) {
        return renderLabel$2(label, providersBackstage);
      });
      var factory2 = function(newSpec) {
        return craft({
          uid: newSpec.uid,
          dom: {
            tag: "iframe",
            attributes
          },
          behaviours: derive$1([
            Tabstopping.config({}),
            Focusing.config({}),
            RepresentingConfigs.withComp(Optional.none(), sourcing.getValue, sourcing.setValue)
          ])
        });
      };
      var pField = FormField.parts.field({ factory: { sketch: factory2 } });
      return renderFormFieldWith(pLabel, pField, ["tox-form__group--stretched"], []);
    };
    var create$3 = function(width2, height2) {
      return resize$3(document.createElement("canvas"), width2, height2);
    };
    var clone2 = function(canvas) {
      var tCanvas = create$3(canvas.width, canvas.height);
      var ctx = get2dContext(tCanvas);
      ctx.drawImage(canvas, 0, 0);
      return tCanvas;
    };
    var get2dContext = function(canvas) {
      return canvas.getContext("2d");
    };
    var resize$3 = function(canvas, width2, height2) {
      canvas.width = width2;
      canvas.height = height2;
      return canvas;
    };
    var getWidth$1 = function(image) {
      return image.naturalWidth || image.width;
    };
    var getHeight$1 = function(image) {
      return image.naturalHeight || image.height;
    };
    var blobToImage = function(blob) {
      return new Promise$1(function(resolve2, reject) {
        var blobUrl = URL.createObjectURL(blob);
        var image = new Image();
        var removeListeners = function() {
          image.removeEventListener("load", loaded);
          image.removeEventListener("error", error4);
        };
        var loaded = function() {
          removeListeners();
          resolve2(image);
        };
        var error4 = function() {
          removeListeners();
          reject("Unable to load data of type " + blob.type + ": " + blobUrl);
        };
        image.addEventListener("load", loaded);
        image.addEventListener("error", error4);
        image.src = blobUrl;
        if (image.complete) {
          setTimeout(loaded, 0);
        }
      });
    };
    var dataUriToBlobSync = function(uri) {
      var data = uri.split(",");
      var matches = /data:([^;]+)/.exec(data[0]);
      if (!matches) {
        return Optional.none();
      }
      var mimetype = matches[1];
      var base64 = data[1];
      var sliceSize = 1024;
      var byteCharacters = atob(base64);
      var bytesLength = byteCharacters.length;
      var slicesCount = Math.ceil(bytesLength / sliceSize);
      var byteArrays = new Array(slicesCount);
      for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
        var begin = sliceIndex * sliceSize;
        var end2 = Math.min(begin + sliceSize, bytesLength);
        var bytes = new Array(end2 - begin);
        for (var offset3 = begin, i2 = 0; offset3 < end2; ++i2, ++offset3) {
          bytes[i2] = byteCharacters[offset3].charCodeAt(0);
        }
        byteArrays[sliceIndex] = new Uint8Array(bytes);
      }
      return Optional.some(new Blob(byteArrays, { type: mimetype }));
    };
    var dataUriToBlob = function(uri) {
      return new Promise$1(function(resolve2, reject) {
        dataUriToBlobSync(uri).fold(function() {
          reject("uri is not base64: " + uri);
        }, resolve2);
      });
    };
    var canvasToBlob = function(canvas, type2, quality) {
      type2 = type2 || "image/png";
      if (isFunction2(HTMLCanvasElement.prototype.toBlob)) {
        return new Promise$1(function(resolve2, reject) {
          canvas.toBlob(function(blob) {
            if (blob) {
              resolve2(blob);
            } else {
              reject();
            }
          }, type2, quality);
        });
      } else {
        return dataUriToBlob(canvas.toDataURL(type2, quality));
      }
    };
    var canvasToDataURL = function(canvas, type2, quality) {
      type2 = type2 || "image/png";
      return canvas.toDataURL(type2, quality);
    };
    var blobToCanvas = function(blob) {
      return blobToImage(blob).then(function(image) {
        revokeImageUrl(image);
        var canvas = create$3(getWidth$1(image), getHeight$1(image));
        var context = get2dContext(canvas);
        context.drawImage(image, 0, 0);
        return canvas;
      });
    };
    var blobToDataUri = function(blob) {
      return new Promise$1(function(resolve2) {
        var reader = new FileReader();
        reader.onloadend = function() {
          resolve2(reader.result);
        };
        reader.readAsDataURL(blob);
      });
    };
    var revokeImageUrl = function(image) {
      URL.revokeObjectURL(image.src);
    };
    var create$2 = function(getCanvas2, blob, uri) {
      var initialType = blob.type;
      var getType = constant$1(initialType);
      var toBlob = function() {
        return Promise$1.resolve(blob);
      };
      var toDataURL = constant$1(uri);
      var toBase64 = function() {
        return uri.split(",")[1];
      };
      var toAdjustedBlob = function(type2, quality) {
        return getCanvas2.then(function(canvas) {
          return canvasToBlob(canvas, type2, quality);
        });
      };
      var toAdjustedDataURL = function(type2, quality) {
        return getCanvas2.then(function(canvas) {
          return canvasToDataURL(canvas, type2, quality);
        });
      };
      var toAdjustedBase64 = function(type2, quality) {
        return toAdjustedDataURL(type2, quality).then(function(dataurl) {
          return dataurl.split(",")[1];
        });
      };
      var toCanvas = function() {
        return getCanvas2.then(clone2);
      };
      return {
        getType,
        toBlob,
        toDataURL,
        toBase64,
        toAdjustedBlob,
        toAdjustedDataURL,
        toAdjustedBase64,
        toCanvas
      };
    };
    var fromBlob = function(blob) {
      return blobToDataUri(blob).then(function(uri) {
        return create$2(blobToCanvas(blob), blob, uri);
      });
    };
    var fromCanvas = function(canvas, type2) {
      return canvasToBlob(canvas, type2).then(function(blob) {
        return create$2(Promise$1.resolve(canvas), blob, canvas.toDataURL());
      });
    };
    var blobToImageResult = function(blob) {
      return fromBlob(blob);
    };
    var clamp = function(value2, min3, max3) {
      var parsedValue = typeof value2 === "string" ? parseFloat(value2) : value2;
      if (parsedValue > max3) {
        parsedValue = max3;
      } else if (parsedValue < min3) {
        parsedValue = min3;
      }
      return parsedValue;
    };
    var identity = function() {
      return [
        1,
        0,
        0,
        0,
        0,
        0,
        1,
        0,
        0,
        0,
        0,
        0,
        1,
        0,
        0,
        0,
        0,
        0,
        1,
        0,
        0,
        0,
        0,
        0,
        1
      ];
    };
    var DELTA_INDEX = [
      0,
      0.01,
      0.02,
      0.04,
      0.05,
      0.06,
      0.07,
      0.08,
      0.1,
      0.11,
      0.12,
      0.14,
      0.15,
      0.16,
      0.17,
      0.18,
      0.2,
      0.21,
      0.22,
      0.24,
      0.25,
      0.27,
      0.28,
      0.3,
      0.32,
      0.34,
      0.36,
      0.38,
      0.4,
      0.42,
      0.44,
      0.46,
      0.48,
      0.5,
      0.53,
      0.56,
      0.59,
      0.62,
      0.65,
      0.68,
      0.71,
      0.74,
      0.77,
      0.8,
      0.83,
      0.86,
      0.89,
      0.92,
      0.95,
      0.98,
      1,
      1.06,
      1.12,
      1.18,
      1.24,
      1.3,
      1.36,
      1.42,
      1.48,
      1.54,
      1.6,
      1.66,
      1.72,
      1.78,
      1.84,
      1.9,
      1.96,
      2,
      2.12,
      2.25,
      2.37,
      2.5,
      2.62,
      2.75,
      2.87,
      3,
      3.2,
      3.4,
      3.6,
      3.8,
      4,
      4.3,
      4.7,
      4.9,
      5,
      5.5,
      6,
      6.5,
      6.8,
      7,
      7.3,
      7.5,
      7.8,
      8,
      8.4,
      8.7,
      9,
      9.4,
      9.6,
      9.8,
      10
    ];
    var multiply = function(matrix1, matrix2) {
      var col = [];
      var out = new Array(25);
      var val;
      for (var i2 = 0; i2 < 5; i2++) {
        for (var j2 = 0; j2 < 5; j2++) {
          col[j2] = matrix2[j2 + i2 * 5];
        }
        for (var j2 = 0; j2 < 5; j2++) {
          val = 0;
          for (var k2 = 0; k2 < 5; k2++) {
            val += matrix1[j2 + k2 * 5] * col[k2];
          }
          out[j2 + i2 * 5] = val;
        }
      }
      return out;
    };
    var adjustContrast = function(matrix2, value2) {
      var x2;
      value2 = clamp(value2, -1, 1);
      value2 *= 100;
      if (value2 < 0) {
        x2 = 127 + value2 / 100 * 127;
      } else {
        x2 = value2 % 1;
        if (x2 === 0) {
          x2 = DELTA_INDEX[value2];
        } else {
          x2 = DELTA_INDEX[Math.floor(value2)] * (1 - x2) + DELTA_INDEX[Math.floor(value2) + 1] * x2;
        }
        x2 = x2 * 127 + 127;
      }
      return multiply(matrix2, [
        x2 / 127,
        0,
        0,
        0,
        0.5 * (127 - x2),
        0,
        x2 / 127,
        0,
        0,
        0.5 * (127 - x2),
        0,
        0,
        x2 / 127,
        0,
        0.5 * (127 - x2),
        0,
        0,
        0,
        1,
        0,
        0,
        0,
        0,
        0,
        1
      ]);
    };
    var adjustBrightness = function(matrix2, value2) {
      value2 = clamp(255 * value2, -255, 255);
      return multiply(matrix2, [
        1,
        0,
        0,
        0,
        value2,
        0,
        1,
        0,
        0,
        value2,
        0,
        0,
        1,
        0,
        value2,
        0,
        0,
        0,
        1,
        0,
        0,
        0,
        0,
        0,
        1
      ]);
    };
    var adjustColors = function(matrix2, adjustR, adjustG, adjustB) {
      adjustR = clamp(adjustR, 0, 2);
      adjustG = clamp(adjustG, 0, 2);
      adjustB = clamp(adjustB, 0, 2);
      return multiply(matrix2, [
        adjustR,
        0,
        0,
        0,
        0,
        0,
        adjustG,
        0,
        0,
        0,
        0,
        0,
        adjustB,
        0,
        0,
        0,
        0,
        0,
        1,
        0,
        0,
        0,
        0,
        0,
        1
      ]);
    };
    var colorFilter = function(ir, matrix2) {
      return ir.toCanvas().then(function(canvas) {
        return applyColorFilter(canvas, ir.getType(), matrix2);
      });
    };
    var applyColorFilter = function(canvas, type2, matrix2) {
      var context = get2dContext(canvas);
      var applyMatrix = function(pixelsData, m2) {
        var r3, g2, b3, a2;
        var data = pixelsData.data, m0 = m2[0], m1 = m2[1], m22 = m2[2], m3 = m2[3], m4 = m2[4], m5 = m2[5], m6 = m2[6], m7 = m2[7], m8 = m2[8], m9 = m2[9], m10 = m2[10], m11 = m2[11], m12 = m2[12], m13 = m2[13], m14 = m2[14], m15 = m2[15], m16 = m2[16], m17 = m2[17], m18 = m2[18], m19 = m2[19];
        for (var i2 = 0; i2 < data.length; i2 += 4) {
          r3 = data[i2];
          g2 = data[i2 + 1];
          b3 = data[i2 + 2];
          a2 = data[i2 + 3];
          data[i2] = r3 * m0 + g2 * m1 + b3 * m22 + a2 * m3 + m4;
          data[i2 + 1] = r3 * m5 + g2 * m6 + b3 * m7 + a2 * m8 + m9;
          data[i2 + 2] = r3 * m10 + g2 * m11 + b3 * m12 + a2 * m13 + m14;
          data[i2 + 3] = r3 * m15 + g2 * m16 + b3 * m17 + a2 * m18 + m19;
        }
        return pixelsData;
      };
      var pixels = applyMatrix(context.getImageData(0, 0, canvas.width, canvas.height), matrix2);
      context.putImageData(pixels, 0, 0);
      return fromCanvas(canvas, type2);
    };
    var convoluteFilter = function(ir, matrix2) {
      return ir.toCanvas().then(function(canvas) {
        return applyConvoluteFilter(canvas, ir.getType(), matrix2);
      });
    };
    var applyConvoluteFilter = function(canvas, type2, matrix2) {
      var context = get2dContext(canvas);
      var applyMatrix = function(pIn, pOut, aMatrix) {
        var clamp2 = function(value2, min3, max3) {
          if (value2 > max3) {
            value2 = max3;
          } else if (value2 < min3) {
            value2 = min3;
          }
          return value2;
        };
        var side = Math.round(Math.sqrt(aMatrix.length));
        var halfSide = Math.floor(side / 2);
        var rgba = pIn.data;
        var drgba = pOut.data;
        var w2 = pIn.width;
        var h3 = pIn.height;
        for (var y2 = 0; y2 < h3; y2++) {
          for (var x2 = 0; x2 < w2; x2++) {
            var r3 = 0;
            var g2 = 0;
            var b3 = 0;
            for (var cy = 0; cy < side; cy++) {
              for (var cx = 0; cx < side; cx++) {
                var scx = clamp2(x2 + cx - halfSide, 0, w2 - 1);
                var scy = clamp2(y2 + cy - halfSide, 0, h3 - 1);
                var innerOffset = (scy * w2 + scx) * 4;
                var wt2 = aMatrix[cy * side + cx];
                r3 += rgba[innerOffset] * wt2;
                g2 += rgba[innerOffset + 1] * wt2;
                b3 += rgba[innerOffset + 2] * wt2;
              }
            }
            var offset3 = (y2 * w2 + x2) * 4;
            drgba[offset3] = clamp2(r3, 0, 255);
            drgba[offset3 + 1] = clamp2(g2, 0, 255);
            drgba[offset3 + 2] = clamp2(b3, 0, 255);
          }
        }
        return pOut;
      };
      var pixelsIn = context.getImageData(0, 0, canvas.width, canvas.height);
      var pixelsOut = context.getImageData(0, 0, canvas.width, canvas.height);
      pixelsOut = applyMatrix(pixelsIn, pixelsOut, matrix2);
      context.putImageData(pixelsOut, 0, 0);
      return fromCanvas(canvas, type2);
    };
    var functionColorFilter = function(colorFn) {
      var filterImpl = function(canvas, type2, value2) {
        var context = get2dContext(canvas);
        var lookup2 = new Array(256);
        var applyLookup = function(pixelsData, lookupData) {
          var data = pixelsData.data;
          for (var i3 = 0; i3 < data.length; i3 += 4) {
            data[i3] = lookupData[data[i3]];
            data[i3 + 1] = lookupData[data[i3 + 1]];
            data[i3 + 2] = lookupData[data[i3 + 2]];
          }
          return pixelsData;
        };
        for (var i2 = 0; i2 < lookup2.length; i2++) {
          lookup2[i2] = colorFn(i2, value2);
        }
        var pixels = applyLookup(context.getImageData(0, 0, canvas.width, canvas.height), lookup2);
        context.putImageData(pixels, 0, 0);
        return fromCanvas(canvas, type2);
      };
      return function(ir, value2) {
        return ir.toCanvas().then(function(canvas) {
          return filterImpl(canvas, ir.getType(), value2);
        });
      };
    };
    var complexAdjustableColorFilter = function(matrixAdjustFn) {
      return function(ir, adjust) {
        return colorFilter(ir, matrixAdjustFn(identity(), adjust));
      };
    };
    var basicColorFilter = function(matrix2) {
      return function(ir) {
        return colorFilter(ir, matrix2);
      };
    };
    var basicConvolutionFilter = function(kernel) {
      return function(ir) {
        return convoluteFilter(ir, kernel);
      };
    };
    var invert$1 = basicColorFilter([
      -1,
      0,
      0,
      0,
      255,
      0,
      -1,
      0,
      0,
      255,
      0,
      0,
      -1,
      0,
      255,
      0,
      0,
      0,
      1,
      0,
      0,
      0,
      0,
      0,
      1
    ]);
    var brightness$1 = complexAdjustableColorFilter(adjustBrightness);
    var contrast$1 = complexAdjustableColorFilter(adjustContrast);
    var colorize$1 = function(ir, adjustR, adjustG, adjustB) {
      return colorFilter(ir, adjustColors(identity(), adjustR, adjustG, adjustB));
    };
    var sharpen$1 = basicConvolutionFilter([
      0,
      -1,
      0,
      -1,
      5,
      -1,
      0,
      -1,
      0
    ]);
    var gamma$1 = functionColorFilter(function(color2, value2) {
      return Math.pow(color2 / 255, 1 - value2) * 255;
    });
    var scale = function(image, dW, dH) {
      var sW = getWidth$1(image);
      var sH = getHeight$1(image);
      var wRatio = dW / sW;
      var hRatio = dH / sH;
      var scaleCapped = false;
      if (wRatio < 0.5 || wRatio > 2) {
        wRatio = wRatio < 0.5 ? 0.5 : 2;
        scaleCapped = true;
      }
      if (hRatio < 0.5 || hRatio > 2) {
        hRatio = hRatio < 0.5 ? 0.5 : 2;
        scaleCapped = true;
      }
      var scaled = _scale(image, wRatio, hRatio);
      return !scaleCapped ? scaled : scaled.then(function(tCanvas) {
        return scale(tCanvas, dW, dH);
      });
    };
    var _scale = function(image, wRatio, hRatio) {
      return new Promise$1(function(resolve2) {
        var sW = getWidth$1(image);
        var sH = getHeight$1(image);
        var dW = Math.floor(sW * wRatio);
        var dH = Math.floor(sH * hRatio);
        var canvas = create$3(dW, dH);
        var context = get2dContext(canvas);
        context.drawImage(image, 0, 0, sW, sH, 0, 0, dW, dH);
        resolve2(canvas);
      });
    };
    var ceilWithPrecision = function(num, precision) {
      if (precision === void 0) {
        precision = 2;
      }
      var mul = Math.pow(10, precision);
      var upper = Math.round(num * mul);
      return Math.ceil(upper / mul);
    };
    var rotate$1 = function(ir, angle) {
      return ir.toCanvas().then(function(canvas) {
        return applyRotate(canvas, ir.getType(), angle);
      });
    };
    var applyRotate = function(image, type2, angle) {
      var degrees = angle < 0 ? 360 + angle : angle;
      var rad = degrees * Math.PI / 180;
      var width2 = image.width;
      var height2 = image.height;
      var sin = Math.sin(rad);
      var cos = Math.cos(rad);
      var newWidth = ceilWithPrecision(Math.abs(width2 * cos) + Math.abs(height2 * sin));
      var newHeight = ceilWithPrecision(Math.abs(width2 * sin) + Math.abs(height2 * cos));
      var canvas = create$3(newWidth, newHeight);
      var context = get2dContext(canvas);
      context.translate(newWidth / 2, newHeight / 2);
      context.rotate(rad);
      context.drawImage(image, -width2 / 2, -height2 / 2);
      return fromCanvas(canvas, type2);
    };
    var flip$1 = function(ir, axis) {
      return ir.toCanvas().then(function(canvas) {
        return applyFlip(canvas, ir.getType(), axis);
      });
    };
    var applyFlip = function(image, type2, axis) {
      var canvas = create$3(image.width, image.height);
      var context = get2dContext(canvas);
      if (axis === "v") {
        context.scale(1, -1);
        context.drawImage(image, 0, -canvas.height);
      } else {
        context.scale(-1, 1);
        context.drawImage(image, -canvas.width, 0);
      }
      return fromCanvas(canvas, type2);
    };
    var crop$1 = function(ir, x2, y2, w2, h3) {
      return ir.toCanvas().then(function(canvas) {
        return applyCrop(canvas, ir.getType(), x2, y2, w2, h3);
      });
    };
    var applyCrop = function(image, type2, x2, y2, w2, h3) {
      var canvas = create$3(w2, h3);
      var context = get2dContext(canvas);
      context.drawImage(image, -x2, -y2);
      return fromCanvas(canvas, type2);
    };
    var resize$2 = function(ir, w2, h3) {
      return ir.toCanvas().then(function(canvas) {
        return scale(canvas, w2, h3).then(function(newCanvas) {
          return fromCanvas(newCanvas, ir.getType());
        });
      });
    };
    var invert = function(ir) {
      return invert$1(ir);
    };
    var sharpen = function(ir) {
      return sharpen$1(ir);
    };
    var gamma = function(ir, value2) {
      return gamma$1(ir, value2);
    };
    var colorize = function(ir, adjustR, adjustG, adjustB) {
      return colorize$1(ir, adjustR, adjustG, adjustB);
    };
    var brightness = function(ir, adjust) {
      return brightness$1(ir, adjust);
    };
    var contrast = function(ir, adjust) {
      return contrast$1(ir, adjust);
    };
    var flip2 = function(ir, axis) {
      return flip$1(ir, axis);
    };
    var crop = function(ir, x2, y2, w2, h3) {
      return crop$1(ir, x2, y2, w2, h3);
    };
    var resize$1 = function(ir, w2, h3) {
      return resize$2(ir, w2, h3);
    };
    var rotate2 = function(ir, angle) {
      return rotate$1(ir, angle);
    };
    var renderIcon = function(iconName, iconsProvider, behaviours2) {
      return render$3(iconName, {
        tag: "span",
        classes: [
          "tox-icon",
          "tox-tbtn__icon-wrap"
        ],
        behaviours: behaviours2
      }, iconsProvider);
    };
    var renderIconFromPack = function(iconName, iconsProvider) {
      return renderIcon(iconName, iconsProvider, []);
    };
    var renderReplacableIconFromPack = function(iconName, iconsProvider) {
      return renderIcon(iconName, iconsProvider, [Replacing.config({})]);
    };
    var renderLabel$1 = function(text2, prefix2, providersBackstage) {
      return {
        dom: {
          tag: "span",
          innerHtml: providersBackstage.translate(text2),
          classes: [prefix2 + "__select-label"]
        },
        behaviours: derive$1([Replacing.config({})])
      };
    };
    var _a;
    var internalToolbarButtonExecute = generate$6("toolbar.button.execute");
    var onToolbarButtonExecute = function(info) {
      return runOnExecute$1(function(comp, _simulatedEvent) {
        runWithApi(info, comp)(function(itemApi) {
          emitWith(comp, internalToolbarButtonExecute, { buttonApi: itemApi });
          info.onAction(itemApi);
        });
      });
    };
    var toolbarButtonEventOrder = (_a = {}, _a[execute$5()] = [
      "disabling",
      "alloy.base.behaviour",
      "toggling",
      "toolbar-button-events"
    ], _a);
    var updateMenuText = generate$6("update-menu-text");
    var updateMenuIcon = generate$6("update-menu-icon");
    var renderCommonDropdown = function(spec, prefix2, sharedBackstage) {
      var editorOffCell = Cell(noop3);
      var optMemDisplayText = spec.text.map(function(text2) {
        return record(renderLabel$1(text2, prefix2, sharedBackstage.providers));
      });
      var optMemDisplayIcon = spec.icon.map(function(iconName) {
        return record(renderReplacableIconFromPack(iconName, sharedBackstage.providers.icons));
      });
      var onLeftOrRightInMenu = function(comp, se2) {
        var dropdown = Representing.getValue(comp);
        Focusing.focus(dropdown);
        emitWith(dropdown, "keydown", { raw: se2.event.raw });
        Dropdown2.close(dropdown);
        return Optional.some(true);
      };
      var role = spec.role.fold(function() {
        return {};
      }, function(role2) {
        return { role: role2 };
      });
      var tooltipAttributes = spec.tooltip.fold(function() {
        return {};
      }, function(tooltip) {
        var translatedTooltip = sharedBackstage.providers.translate(tooltip);
        return {
          "title": translatedTooltip,
          "aria-label": translatedTooltip
        };
      });
      var iconSpec = render$3("chevron-down", {
        tag: "div",
        classes: [prefix2 + "__select-chevron"]
      }, sharedBackstage.providers.icons);
      var memDropdown = record(Dropdown2.sketch(__assign(__assign(__assign({}, spec.uid ? { uid: spec.uid } : {}), role), {
        dom: {
          tag: "button",
          classes: [
            prefix2,
            prefix2 + "--select"
          ].concat(map$2(spec.classes, function(c2) {
            return prefix2 + "--" + c2;
          })),
          attributes: __assign({}, tooltipAttributes)
        },
        components: componentRenderPipeline([
          optMemDisplayIcon.map(function(mem) {
            return mem.asSpec();
          }),
          optMemDisplayText.map(function(mem) {
            return mem.asSpec();
          }),
          Optional.some(iconSpec)
        ]),
        matchWidth: true,
        useMinWidth: true,
        dropdownBehaviours: derive$1(__spreadArray(__spreadArray([], spec.dropdownBehaviours, true), [
          DisablingConfigs.button(function() {
            return spec.disabled || sharedBackstage.providers.isDisabled();
          }),
          receivingConfig(),
          Unselecting.config({}),
          Replacing.config({}),
          config("dropdown-events", [
            onControlAttached(spec, editorOffCell),
            onControlDetached(spec, editorOffCell)
          ]),
          config("menubutton-update-display-text", [
            run$1(updateMenuText, function(comp, se2) {
              optMemDisplayText.bind(function(mem) {
                return mem.getOpt(comp);
              }).each(function(displayText) {
                Replacing.set(displayText, [text(sharedBackstage.providers.translate(se2.event.text))]);
              });
            }),
            run$1(updateMenuIcon, function(comp, se2) {
              optMemDisplayIcon.bind(function(mem) {
                return mem.getOpt(comp);
              }).each(function(displayIcon) {
                Replacing.set(displayIcon, [renderReplacableIconFromPack(se2.event.icon, sharedBackstage.providers.icons)]);
              });
            })
          ])
        ], false)),
        eventOrder: deepMerge(toolbarButtonEventOrder, {
          mousedown: [
            "focusing",
            "alloy.base.behaviour",
            "item-type-events",
            "normal-dropdown-events"
          ]
        }),
        sandboxBehaviours: derive$1([Keying.config({
          mode: "special",
          onLeft: onLeftOrRightInMenu,
          onRight: onLeftOrRightInMenu
        })]),
        lazySink: sharedBackstage.getSink,
        toggleClass: prefix2 + "--active",
        parts: { menu: part(false, spec.columns, spec.presets) },
        fetch: function(comp) {
          return Future.nu(curry(spec.fetch, comp));
        }
      })));
      return memDropdown.asSpec();
    };
    var isMenuItemReference = function(item2) {
      return isString(item2);
    };
    var isSeparator$1 = function(item2) {
      return item2.type === "separator";
    };
    var isExpandingMenuItem = function(item2) {
      return has$2(item2, "getSubmenuItems");
    };
    var separator$2 = { type: "separator" };
    var unwrapReferences = function(items, menuItems) {
      var realItems = foldl(items, function(acc, item2) {
        if (isMenuItemReference(item2)) {
          if (item2 === "") {
            return acc;
          } else if (item2 === "|") {
            return acc.length > 0 && !isSeparator$1(acc[acc.length - 1]) ? acc.concat([separator$2]) : acc;
          } else if (has$2(menuItems, item2.toLowerCase())) {
            return acc.concat([menuItems[item2.toLowerCase()]]);
          } else {
            return acc;
          }
        } else {
          return acc.concat([item2]);
        }
      }, []);
      if (realItems.length > 0 && isSeparator$1(realItems[realItems.length - 1])) {
        realItems.pop();
      }
      return realItems;
    };
    var getFromExpandingItem = function(item2, menuItems) {
      var submenuItems = item2.getSubmenuItems();
      var rest = expand(submenuItems, menuItems);
      var newMenus = deepMerge(rest.menus, wrap$1(item2.value, rest.items));
      var newExpansions = deepMerge(rest.expansions, wrap$1(item2.value, item2.value));
      return {
        item: item2,
        menus: newMenus,
        expansions: newExpansions
      };
    };
    var getFromItem = function(item2, menuItems) {
      return isExpandingMenuItem(item2) ? getFromExpandingItem(item2, menuItems) : {
        item: item2,
        menus: {},
        expansions: {}
      };
    };
    var generateValueIfRequired = function(item2) {
      if (isSeparator$1(item2)) {
        return item2;
      } else {
        var itemValue = get$e(item2, "value").getOrThunk(function() {
          return generate$6("generated-menu-item");
        });
        return deepMerge({ value: itemValue }, item2);
      }
    };
    var expand = function(items, menuItems) {
      var realItems = unwrapReferences(isString(items) ? items.split(" ") : items, menuItems);
      return foldr(realItems, function(acc, item2) {
        var itemWithValue = generateValueIfRequired(item2);
        var newData = getFromItem(itemWithValue, menuItems);
        return {
          menus: deepMerge(acc.menus, newData.menus),
          items: [newData.item].concat(acc.items),
          expansions: deepMerge(acc.expansions, newData.expansions)
        };
      }, {
        menus: {},
        expansions: {},
        items: []
      });
    };
    var build = function(items, itemResponse, backstage, isHorizontalMenu) {
      var primary = generate$6("primary-menu");
      var data = expand(items, backstage.shared.providers.menuItems());
      if (data.items.length === 0) {
        return Optional.none();
      }
      var mainMenu = createPartialMenu(primary, data.items, itemResponse, backstage, isHorizontalMenu);
      var submenus = map$12(data.menus, function(menuItems, menuName) {
        return createPartialMenu(menuName, menuItems, itemResponse, backstage, false);
      });
      var menus = deepMerge(submenus, wrap$1(primary, mainMenu));
      return Optional.from(tieredMenu.tieredData(primary, menus, data.expansions));
    };
    var getMenuButtonApi = function(component) {
      return {
        isDisabled: function() {
          return Disabling.isDisabled(component);
        },
        setDisabled: function(state) {
          return Disabling.set(component, state);
        },
        setActive: function(state) {
          var elm = component.element;
          if (state) {
            add$2(elm, "tox-tbtn--enabled");
            set$8(elm, "aria-pressed", true);
          } else {
            remove$2(elm, "tox-tbtn--enabled");
            remove$7(elm, "aria-pressed");
          }
        },
        isActive: function() {
          return has(component.element, "tox-tbtn--enabled");
        }
      };
    };
    var renderMenuButton = function(spec, prefix2, backstage, role) {
      return renderCommonDropdown({
        text: spec.text,
        icon: spec.icon,
        tooltip: spec.tooltip,
        role,
        fetch: function(_comp, callback2) {
          spec.fetch(function(items) {
            callback2(build(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, false));
          });
        },
        onSetup: spec.onSetup,
        getApi: getMenuButtonApi,
        columns: 1,
        presets: "normal",
        classes: [],
        dropdownBehaviours: [Tabstopping.config({})]
      }, prefix2, backstage.shared);
    };
    var getFetch = function(items, getButton, backstage) {
      var getMenuItemAction = function(item2) {
        return function(api2) {
          var newValue = !api2.isActive();
          api2.setActive(newValue);
          item2.storage.set(newValue);
          backstage.shared.getSink().each(function(sink) {
            getButton().getOpt(sink).each(function(orig) {
              focus$3(orig.element);
              emitWith(orig, formActionEvent, {
                name: item2.name,
                value: item2.storage.get()
              });
            });
          });
        };
      };
      var getMenuItemSetup = function(item2) {
        return function(api2) {
          api2.setActive(item2.storage.get());
        };
      };
      return function(success) {
        success(map$2(items, function(item2) {
          var text2 = item2.text.fold(function() {
            return {};
          }, function(text3) {
            return { text: text3 };
          });
          return __assign(__assign({
            type: item2.type,
            active: false
          }, text2), {
            onAction: getMenuItemAction(item2),
            onSetup: getMenuItemSetup(item2)
          });
        }));
      };
    };
    var renderCommonSpec = function(spec, actionOpt, extraBehaviours, dom2, components2, providersBackstage) {
      if (extraBehaviours === void 0) {
        extraBehaviours = [];
      }
      var action = actionOpt.fold(function() {
        return {};
      }, function(action2) {
        return { action: action2 };
      });
      var common = __assign({
        buttonBehaviours: derive$1([
          DisablingConfigs.button(function() {
            return spec.disabled || providersBackstage.isDisabled();
          }),
          receivingConfig(),
          Tabstopping.config({}),
          config("button press", [
            preventDefault("click"),
            preventDefault("mousedown")
          ])
        ].concat(extraBehaviours)),
        eventOrder: {
          click: [
            "button press",
            "alloy.base.behaviour"
          ],
          mousedown: [
            "button press",
            "alloy.base.behaviour"
          ]
        }
      }, action);
      var domFinal = deepMerge(common, { dom: dom2 });
      return deepMerge(domFinal, { components: components2 });
    };
    var renderIconButtonSpec = function(spec, action, providersBackstage, extraBehaviours) {
      if (extraBehaviours === void 0) {
        extraBehaviours = [];
      }
      var tooltipAttributes = spec.tooltip.map(function(tooltip) {
        return {
          "aria-label": providersBackstage.translate(tooltip),
          "title": providersBackstage.translate(tooltip)
        };
      }).getOr({});
      var dom2 = {
        tag: "button",
        classes: ["tox-tbtn"],
        attributes: tooltipAttributes
      };
      var icon = spec.icon.map(function(iconName) {
        return renderIconFromPack(iconName, providersBackstage.icons);
      });
      var components2 = componentRenderPipeline([icon]);
      return renderCommonSpec(spec, action, extraBehaviours, dom2, components2, providersBackstage);
    };
    var renderIconButton = function(spec, action, providersBackstage, extraBehaviours) {
      if (extraBehaviours === void 0) {
        extraBehaviours = [];
      }
      var iconButtonSpec = renderIconButtonSpec(spec, Optional.some(action), providersBackstage, extraBehaviours);
      return Button2.sketch(iconButtonSpec);
    };
    var renderButtonSpec = function(spec, action, providersBackstage, extraBehaviours, extraClasses) {
      if (extraBehaviours === void 0) {
        extraBehaviours = [];
      }
      if (extraClasses === void 0) {
        extraClasses = [];
      }
      var translatedText = providersBackstage.translate(spec.text);
      var icon = spec.icon ? spec.icon.map(function(iconName) {
        return renderIconFromPack(iconName, providersBackstage.icons);
      }) : Optional.none();
      var components2 = icon.isSome() ? componentRenderPipeline([icon]) : [];
      var innerHtml = icon.isSome() ? {} : { innerHtml: translatedText };
      var classes2 = __spreadArray(__spreadArray(__spreadArray(__spreadArray([], !spec.primary && !spec.borderless ? [
        "tox-button",
        "tox-button--secondary"
      ] : ["tox-button"], true), icon.isSome() ? ["tox-button--icon"] : [], true), spec.borderless ? ["tox-button--naked"] : [], true), extraClasses, true);
      var dom2 = __assign(__assign({
        tag: "button",
        classes: classes2
      }, innerHtml), { attributes: { title: translatedText } });
      return renderCommonSpec(spec, action, extraBehaviours, dom2, components2, providersBackstage);
    };
    var renderButton = function(spec, action, providersBackstage, extraBehaviours, extraClasses) {
      if (extraBehaviours === void 0) {
        extraBehaviours = [];
      }
      if (extraClasses === void 0) {
        extraClasses = [];
      }
      var buttonSpec = renderButtonSpec(spec, Optional.some(action), providersBackstage, extraBehaviours, extraClasses);
      return Button2.sketch(buttonSpec);
    };
    var getAction2 = function(name2, buttonType) {
      return function(comp) {
        if (buttonType === "custom") {
          emitWith(comp, formActionEvent, {
            name: name2,
            value: {}
          });
        } else if (buttonType === "submit") {
          emit(comp, formSubmitEvent);
        } else if (buttonType === "cancel") {
          emit(comp, formCancelEvent);
        } else {
          console.error("Unknown button type: ", buttonType);
        }
      };
    };
    var isMenuFooterButtonSpec = function(spec, buttonType) {
      return buttonType === "menu";
    };
    var isNormalFooterButtonSpec = function(spec, buttonType) {
      return buttonType === "custom" || buttonType === "cancel" || buttonType === "submit";
    };
    var renderFooterButton = function(spec, buttonType, backstage) {
      if (isMenuFooterButtonSpec(spec, buttonType)) {
        var getButton = function() {
          return memButton_1;
        };
        var menuButtonSpec = spec;
        var fixedSpec = __assign(__assign({}, spec), {
          onSetup: function(api2) {
            api2.setDisabled(spec.disabled);
            return noop3;
          },
          fetch: getFetch(menuButtonSpec.items, getButton, backstage)
        });
        var memButton_1 = record(renderMenuButton(fixedSpec, "tox-tbtn", backstage, Optional.none()));
        return memButton_1.asSpec();
      } else if (isNormalFooterButtonSpec(spec, buttonType)) {
        var action = getAction2(spec.name, buttonType);
        var buttonSpec = __assign(__assign({}, spec), { borderless: false });
        return renderButton(buttonSpec, action, backstage.shared.providers, []);
      } else {
        console.error("Unknown footer button type: ", buttonType);
      }
    };
    var renderDialogButton = function(spec, providersBackstage) {
      var action = getAction2(spec.name, "custom");
      return renderFormField(Optional.none(), FormField.parts.field(__assign({ factory: Button2 }, renderButtonSpec(spec, Optional.some(action), providersBackstage, [
        RepresentingConfigs.memory(""),
        ComposingConfigs.self()
      ]))));
    };
    var schema$h = constant$1([
      defaulted("field1Name", "field1"),
      defaulted("field2Name", "field2"),
      onStrictHandler("onLockedChange"),
      markers$1(["lockClass"]),
      defaulted("locked", false),
      SketchBehaviours.field("coupledFieldBehaviours", [
        Composing,
        Representing
      ])
    ]);
    var getField = function(comp, detail, partName) {
      return getPart(comp, detail, partName).bind(Composing.getCurrent);
    };
    var coupledPart = function(selfName, otherName) {
      return required({
        factory: FormField,
        name: selfName,
        overrides: function(detail) {
          return {
            fieldBehaviours: derive$1([config("coupled-input-behaviour", [run$1(input(), function(me2) {
              getField(me2, detail, otherName).each(function(other) {
                getPart(me2, detail, "lock").each(function(lock) {
                  if (Toggling.isOn(lock)) {
                    detail.onLockedChange(me2, other, lock);
                  }
                });
              });
            })])])
          };
        }
      });
    };
    var parts$c = constant$1([
      coupledPart("field1", "field2"),
      coupledPart("field2", "field1"),
      required({
        factory: Button2,
        schema: [required$1("dom")],
        name: "lock",
        overrides: function(detail) {
          return {
            buttonBehaviours: derive$1([Toggling.config({
              selected: detail.locked,
              toggleClass: detail.markers.lockClass,
              aria: { mode: "pressed" }
            })])
          };
        }
      })
    ]);
    var factory$f = function(detail, components2, _spec, _externals) {
      return {
        uid: detail.uid,
        dom: detail.dom,
        components: components2,
        behaviours: SketchBehaviours.augment(detail.coupledFieldBehaviours, [
          Composing.config({ find: Optional.some }),
          Representing.config({
            store: {
              mode: "manual",
              getValue: function(comp) {
                var _a2;
                var parts2 = getPartsOrDie(comp, detail, [
                  "field1",
                  "field2"
                ]);
                return _a2 = {}, _a2[detail.field1Name] = Representing.getValue(parts2.field1()), _a2[detail.field2Name] = Representing.getValue(parts2.field2()), _a2;
              },
              setValue: function(comp, value2) {
                var parts2 = getPartsOrDie(comp, detail, [
                  "field1",
                  "field2"
                ]);
                if (hasNonNullableKey(value2, detail.field1Name)) {
                  Representing.setValue(parts2.field1(), value2[detail.field1Name]);
                }
                if (hasNonNullableKey(value2, detail.field2Name)) {
                  Representing.setValue(parts2.field2(), value2[detail.field2Name]);
                }
              }
            }
          })
        ]),
        apis: {
          getField1: function(component) {
            return getPart(component, detail, "field1");
          },
          getField2: function(component) {
            return getPart(component, detail, "field2");
          },
          getLock: function(component) {
            return getPart(component, detail, "lock");
          }
        }
      };
    };
    var FormCoupledInputs = composite({
      name: "FormCoupledInputs",
      configFields: schema$h(),
      partFields: parts$c(),
      factory: factory$f,
      apis: {
        getField1: function(apis, component) {
          return apis.getField1(component);
        },
        getField2: function(apis, component) {
          return apis.getField2(component);
        },
        getLock: function(apis, component) {
          return apis.getLock(component);
        }
      }
    });
    var formatSize = function(size) {
      var unitDec = {
        "": 0,
        "px": 0,
        "pt": 1,
        "mm": 1,
        "pc": 2,
        "ex": 2,
        "em": 2,
        "ch": 2,
        "rem": 2,
        "cm": 3,
        "in": 4,
        "%": 4
      };
      var maxDecimal = function(unit) {
        return unit in unitDec ? unitDec[unit] : 1;
      };
      var numText = size.value.toFixed(maxDecimal(size.unit));
      if (numText.indexOf(".") !== -1) {
        numText = numText.replace(/\.?0*$/, "");
      }
      return numText + size.unit;
    };
    var parseSize = function(sizeText) {
      var numPattern = /^\s*(\d+(?:\.\d+)?)\s*(|cm|mm|in|px|pt|pc|em|ex|ch|rem|vw|vh|vmin|vmax|%)\s*$/;
      var match2 = numPattern.exec(sizeText);
      if (match2 !== null) {
        var value2 = parseFloat(match2[1]);
        var unit = match2[2];
        return Result.value({
          value: value2,
          unit
        });
      } else {
        return Result.error(sizeText);
      }
    };
    var convertUnit = function(size, unit) {
      var inInch = {
        "": 96,
        "px": 96,
        "pt": 72,
        "cm": 2.54,
        "pc": 12,
        "mm": 25.4,
        "in": 1
      };
      var supported2 = function(u2) {
        return has$2(inInch, u2);
      };
      if (size.unit === unit) {
        return Optional.some(size.value);
      } else if (supported2(size.unit) && supported2(unit)) {
        if (inInch[size.unit] === inInch[unit]) {
          return Optional.some(size.value);
        } else {
          return Optional.some(size.value / inInch[size.unit] * inInch[unit]);
        }
      } else {
        return Optional.none();
      }
    };
    var noSizeConversion = function(_input) {
      return Optional.none();
    };
    var ratioSizeConversion = function(scale2, unit) {
      return function(size) {
        return convertUnit(size, unit).map(function(value2) {
          return {
            value: value2 * scale2,
            unit
          };
        });
      };
    };
    var makeRatioConverter = function(currentFieldText, otherFieldText) {
      var cValue = parseSize(currentFieldText).toOptional();
      var oValue = parseSize(otherFieldText).toOptional();
      return lift2(cValue, oValue, function(cSize, oSize) {
        return convertUnit(cSize, oSize.unit).map(function(val) {
          return oSize.value / val;
        }).map(function(r3) {
          return ratioSizeConversion(r3, oSize.unit);
        }).getOr(noSizeConversion);
      }).getOr(noSizeConversion);
    };
    var renderSizeInput = function(spec, providersBackstage) {
      var converter = noSizeConversion;
      var ratioEvent = generate$6("ratio-event");
      var makeIcon = function(iconName) {
        return render$3(iconName, {
          tag: "span",
          classes: [
            "tox-icon",
            "tox-lock-icon__" + iconName
          ]
        }, providersBackstage.icons);
      };
      var pLock = FormCoupledInputs.parts.lock({
        dom: {
          tag: "button",
          classes: [
            "tox-lock",
            "tox-button",
            "tox-button--naked",
            "tox-button--icon"
          ],
          attributes: { title: providersBackstage.translate(spec.label.getOr("Constrain proportions")) }
        },
        components: [
          makeIcon("lock"),
          makeIcon("unlock")
        ],
        buttonBehaviours: derive$1([
          Disabling.config({
            disabled: function() {
              return spec.disabled || providersBackstage.isDisabled();
            }
          }),
          receivingConfig(),
          Tabstopping.config({})
        ])
      });
      var formGroup = function(components2) {
        return {
          dom: {
            tag: "div",
            classes: ["tox-form__group"]
          },
          components: components2
        };
      };
      var getFieldPart = function(isField1) {
        return FormField.parts.field({
          factory: Input,
          inputClasses: ["tox-textfield"],
          inputBehaviours: derive$1([
            Disabling.config({
              disabled: function() {
                return spec.disabled || providersBackstage.isDisabled();
              }
            }),
            receivingConfig(),
            Tabstopping.config({}),
            config("size-input-events", [
              run$1(focusin(), function(component, _simulatedEvent) {
                emitWith(component, ratioEvent, { isField1 });
              }),
              run$1(change(), function(component, _simulatedEvent) {
                emitWith(component, formChangeEvent, { name: spec.name });
              })
            ])
          ]),
          selectOnFocus: false
        });
      };
      var getLabel = function(label) {
        return {
          dom: {
            tag: "label",
            classes: ["tox-label"],
            innerHtml: providersBackstage.translate(label)
          }
        };
      };
      var widthField = FormCoupledInputs.parts.field1(formGroup([
        FormField.parts.label(getLabel("Width")),
        getFieldPart(true)
      ]));
      var heightField = FormCoupledInputs.parts.field2(formGroup([
        FormField.parts.label(getLabel("Height")),
        getFieldPart(false)
      ]));
      return FormCoupledInputs.sketch({
        dom: {
          tag: "div",
          classes: ["tox-form__group"]
        },
        components: [{
          dom: {
            tag: "div",
            classes: ["tox-form__controls-h-stack"]
          },
          components: [
            widthField,
            heightField,
            formGroup([
              getLabel("&nbsp;"),
              pLock
            ])
          ]
        }],
        field1Name: "width",
        field2Name: "height",
        locked: true,
        markers: { lockClass: "tox-locked" },
        onLockedChange: function(current, other, _lock) {
          parseSize(Representing.getValue(current)).each(function(size) {
            converter(size).each(function(newSize) {
              Representing.setValue(other, formatSize(newSize));
            });
          });
        },
        coupledFieldBehaviours: derive$1([
          Disabling.config({
            disabled: function() {
              return spec.disabled || providersBackstage.isDisabled();
            },
            onDisabled: function(comp) {
              FormCoupledInputs.getField1(comp).bind(FormField.getField).each(Disabling.disable);
              FormCoupledInputs.getField2(comp).bind(FormField.getField).each(Disabling.disable);
              FormCoupledInputs.getLock(comp).each(Disabling.disable);
            },
            onEnabled: function(comp) {
              FormCoupledInputs.getField1(comp).bind(FormField.getField).each(Disabling.enable);
              FormCoupledInputs.getField2(comp).bind(FormField.getField).each(Disabling.enable);
              FormCoupledInputs.getLock(comp).each(Disabling.enable);
            }
          }),
          receivingConfig(),
          config("size-input-events2", [run$1(ratioEvent, function(component, simulatedEvent) {
            var isField1 = simulatedEvent.event.isField1;
            var optCurrent = isField1 ? FormCoupledInputs.getField1(component) : FormCoupledInputs.getField2(component);
            var optOther = isField1 ? FormCoupledInputs.getField2(component) : FormCoupledInputs.getField1(component);
            var value1 = optCurrent.map(Representing.getValue).getOr("");
            var value2 = optOther.map(Representing.getValue).getOr("");
            converter = makeRatioConverter(value1, value2);
          })])
        ])
      });
    };
    var undo = constant$1(generate$6("undo"));
    var redo = constant$1(generate$6("redo"));
    var zoom = constant$1(generate$6("zoom"));
    var back = constant$1(generate$6("back"));
    var apply = constant$1(generate$6("apply"));
    var swap2 = constant$1(generate$6("swap"));
    var transform$1 = constant$1(generate$6("transform"));
    var tempTransform = constant$1(generate$6("temp-transform"));
    var transformApply = constant$1(generate$6("transform-apply"));
    var internal = {
      undo,
      redo,
      zoom,
      back,
      apply,
      swap: swap2,
      transform: transform$1,
      tempTransform,
      transformApply
    };
    var saveState = constant$1("save-state");
    var disable2 = constant$1("disable");
    var enable2 = constant$1("enable");
    var external = {
      formActionEvent,
      saveState,
      disable: disable2,
      enable: enable2
    };
    var renderEditPanel = function(imagePanel, providersBackstage) {
      var createButton2 = function(text2, action, disabled, primary) {
        return record(renderButton({
          name: text2,
          text: text2,
          disabled,
          primary,
          icon: Optional.none(),
          borderless: false
        }, action, providersBackstage));
      };
      var createIconButton = function(icon, tooltip, action, disabled) {
        return record(renderIconButton({
          name: icon,
          icon: Optional.some(icon),
          tooltip: Optional.some(tooltip),
          disabled,
          primary: false,
          borderless: false
        }, action, providersBackstage));
      };
      var disableAllComponents = function(comps, eventcomp) {
        comps.map(function(mem) {
          var component = mem.get(eventcomp);
          if (component.hasConfigured(Disabling)) {
            Disabling.disable(component);
          }
        });
      };
      var enableAllComponents = function(comps, eventcomp) {
        comps.map(function(mem) {
          var component = mem.get(eventcomp);
          if (component.hasConfigured(Disabling)) {
            Disabling.enable(component);
          }
        });
      };
      var panelDom = {
        tag: "div",
        classes: [
          "tox-image-tools__toolbar",
          "tox-image-tools-edit-panel"
        ]
      };
      var noop$1 = noop3;
      var emit$1 = function(comp, event, data) {
        emitWith(comp, event, data);
      };
      var emitDisable = function(component) {
        return emit(component, external.disable());
      };
      var emitEnable = function(component) {
        return emit(component, external.enable());
      };
      var emitTransform = function(comp, transform2) {
        emitDisable(comp);
        emit$1(comp, internal.transform(), { transform: transform2 });
        emitEnable(comp);
      };
      var emitTempTransform = function(comp, transform2) {
        emitDisable(comp);
        emit$1(comp, internal.tempTransform(), { transform: transform2 });
        emitEnable(comp);
      };
      var getBackSwap = function(anyInSystem) {
        return function() {
          memContainer.getOpt(anyInSystem).each(function(container2) {
            Replacing.set(container2, [ButtonPanel]);
          });
        };
      };
      var emitTransformApply = function(comp, transform2) {
        emitDisable(comp);
        emit$1(comp, internal.transformApply(), {
          transform: transform2,
          swap: getBackSwap(comp)
        });
        emitEnable(comp);
      };
      var createBackButton = function() {
        return createButton2("Back", function(button2) {
          return emit$1(button2, internal.back(), { swap: getBackSwap(button2) });
        }, false, false);
      };
      var createSpacer = function() {
        return record({
          dom: {
            tag: "div",
            classes: ["tox-spacer"]
          },
          behaviours: derive$1([Disabling.config({})])
        });
      };
      var createApplyButton = function() {
        return createButton2("Apply", function(button2) {
          return emit$1(button2, internal.apply(), { swap: getBackSwap(button2) });
        }, true, true);
      };
      var makeCropTransform = function() {
        return function(ir) {
          var rect2 = imagePanel.getRect();
          return crop(ir, rect2.x, rect2.y, rect2.w, rect2.h);
        };
      };
      var cropPanelComponents = [
        createBackButton(),
        createSpacer(),
        createButton2("Apply", function(button2) {
          var transform2 = makeCropTransform();
          emitTransformApply(button2, transform2);
          imagePanel.hideCrop();
        }, false, true)
      ];
      var CropPanel = Container.sketch({
        dom: panelDom,
        components: cropPanelComponents.map(function(mem) {
          return mem.asSpec();
        }),
        containerBehaviours: derive$1([config("image-tools-crop-buttons-events", [
          run$1(external.disable(), function(comp, _se) {
            disableAllComponents(cropPanelComponents, comp);
          }),
          run$1(external.enable(), function(comp, _se) {
            enableAllComponents(cropPanelComponents, comp);
          })
        ])])
      });
      var memSize = record(renderSizeInput({
        name: "size",
        label: Optional.none(),
        constrain: true,
        disabled: false
      }, providersBackstage));
      var makeResizeTransform = function(width2, height2) {
        return function(ir) {
          return resize$1(ir, width2, height2);
        };
      };
      var resizePanelComponents = [
        createBackButton(),
        createSpacer(),
        memSize,
        createSpacer(),
        createButton2("Apply", function(button2) {
          memSize.getOpt(button2).each(function(sizeInput) {
            var value2 = Representing.getValue(sizeInput);
            var width2 = parseInt(value2.width, 10);
            var height2 = parseInt(value2.height, 10);
            var transform2 = makeResizeTransform(width2, height2);
            emitTransformApply(button2, transform2);
          });
        }, false, true)
      ];
      var ResizePanel = Container.sketch({
        dom: panelDom,
        components: resizePanelComponents.map(function(mem) {
          return mem.asSpec();
        }),
        containerBehaviours: derive$1([config("image-tools-resize-buttons-events", [
          run$1(external.disable(), function(comp, _se) {
            disableAllComponents(resizePanelComponents, comp);
          }),
          run$1(external.enable(), function(comp, _se) {
            enableAllComponents(resizePanelComponents, comp);
          })
        ])])
      });
      var makeValueTransform = function(transform2, value2) {
        return function(ir) {
          return transform2(ir, value2);
        };
      };
      var horizontalFlip = makeValueTransform(flip2, "h");
      var verticalFlip = makeValueTransform(flip2, "v");
      var counterclockwiseRotate = makeValueTransform(rotate2, -90);
      var clockwiseRotate = makeValueTransform(rotate2, 90);
      var flipRotateOnAction = function(comp, operation) {
        emitTempTransform(comp, operation);
      };
      var flipRotateComponents = [
        createBackButton(),
        createSpacer(),
        createIconButton("flip-horizontally", "Flip horizontally", function(button2) {
          flipRotateOnAction(button2, horizontalFlip);
        }, false),
        createIconButton("flip-vertically", "Flip vertically", function(button2) {
          flipRotateOnAction(button2, verticalFlip);
        }, false),
        createIconButton("rotate-left", "Rotate counterclockwise", function(button2) {
          flipRotateOnAction(button2, counterclockwiseRotate);
        }, false),
        createIconButton("rotate-right", "Rotate clockwise", function(button2) {
          flipRotateOnAction(button2, clockwiseRotate);
        }, false),
        createSpacer(),
        createApplyButton()
      ];
      var FlipRotatePanel = Container.sketch({
        dom: panelDom,
        components: flipRotateComponents.map(function(mem) {
          return mem.asSpec();
        }),
        containerBehaviours: derive$1([config("image-tools-fliprotate-buttons-events", [
          run$1(external.disable(), function(comp, _se) {
            disableAllComponents(flipRotateComponents, comp);
          }),
          run$1(external.enable(), function(comp, _se) {
            enableAllComponents(flipRotateComponents, comp);
          })
        ])])
      });
      var makeSlider = function(label, onChoose, min3, value2, max3) {
        var labelPart2 = Slider.parts.label({
          dom: {
            tag: "label",
            classes: ["tox-label"],
            innerHtml: providersBackstage.translate(label)
          }
        });
        var spectrum = Slider.parts.spectrum({
          dom: {
            tag: "div",
            classes: ["tox-slider__rail"],
            attributes: { role: "presentation" }
          }
        });
        var thumb = Slider.parts.thumb({
          dom: {
            tag: "div",
            classes: ["tox-slider__handle"],
            attributes: { role: "presentation" }
          }
        });
        return record(Slider.sketch({
          dom: {
            tag: "div",
            classes: ["tox-slider"],
            attributes: { role: "presentation" }
          },
          model: {
            mode: "x",
            minX: min3,
            maxX: max3,
            getInitialValue: constant$1({ x: value2 })
          },
          components: [
            labelPart2,
            spectrum,
            thumb
          ],
          sliderBehaviours: derive$1([Focusing.config({})]),
          onChoose
        }));
      };
      var makeVariableSlider = function(label, transform2, min3, value2, max3) {
        var onChoose = function(slider, _thumb, value3) {
          var valTransform = makeValueTransform(transform2, value3.x / 100);
          emitTransform(slider, valTransform);
        };
        return makeSlider(label, onChoose, min3, value2, max3);
      };
      var variableFilterPanelComponents = function(label, transform2, min3, value2, max3) {
        return [
          createBackButton(),
          makeVariableSlider(label, transform2, min3, value2, max3),
          createApplyButton()
        ];
      };
      var createVariableFilterPanel = function(label, transform2, min3, value2, max3) {
        var filterPanelComponents2 = variableFilterPanelComponents(label, transform2, min3, value2, max3);
        return Container.sketch({
          dom: panelDom,
          components: filterPanelComponents2.map(function(mem) {
            return mem.asSpec();
          }),
          containerBehaviours: derive$1([config("image-tools-filter-panel-buttons-events", [
            run$1(external.disable(), function(comp, _se) {
              disableAllComponents(filterPanelComponents2, comp);
            }),
            run$1(external.enable(), function(comp, _se) {
              enableAllComponents(filterPanelComponents2, comp);
            })
          ])])
        });
      };
      var filterPanelComponents = [
        createBackButton(),
        createSpacer(),
        createApplyButton()
      ];
      var FilterPanel = Container.sketch({
        dom: panelDom,
        components: filterPanelComponents.map(function(mem) {
          return mem.asSpec();
        })
      });
      var BrightnessPanel = createVariableFilterPanel("Brightness", brightness, -100, 0, 100);
      var ContrastPanel = createVariableFilterPanel("Contrast", contrast, -100, 0, 100);
      var GammaPanel = createVariableFilterPanel("Gamma", gamma, -100, 0, 100);
      var makeColorTransform = function(red2, green, blue) {
        return function(ir) {
          return colorize(ir, red2, green, blue);
        };
      };
      var makeColorSlider = function(label) {
        var onChoose = function(slider, _thumb, _value) {
          var redOpt = memRed.getOpt(slider);
          var blueOpt = memBlue.getOpt(slider);
          var greenOpt = memGreen.getOpt(slider);
          redOpt.each(function(red2) {
            blueOpt.each(function(blue) {
              greenOpt.each(function(green) {
                var r3 = Representing.getValue(red2).x / 100;
                var g2 = Representing.getValue(green).x / 100;
                var b3 = Representing.getValue(blue).x / 100;
                var transform2 = makeColorTransform(r3, g2, b3);
                emitTransform(slider, transform2);
              });
            });
          });
        };
        return makeSlider(label, onChoose, 0, 100, 200);
      };
      var memRed = makeColorSlider("R");
      var memGreen = makeColorSlider("G");
      var memBlue = makeColorSlider("B");
      var colorizePanelComponents = [
        createBackButton(),
        memRed,
        memGreen,
        memBlue,
        createApplyButton()
      ];
      var ColorizePanel = Container.sketch({
        dom: panelDom,
        components: colorizePanelComponents.map(function(mem) {
          return mem.asSpec();
        })
      });
      var getTransformPanelEvent = function(panel, transform2, update) {
        return function(button2) {
          var swap3 = function() {
            memContainer.getOpt(button2).each(function(container2) {
              Replacing.set(container2, [panel]);
              update(container2);
            });
          };
          emit$1(button2, internal.swap(), {
            transform: transform2,
            swap: swap3
          });
        };
      };
      var cropPanelUpdate = function(_anyInSystem) {
        imagePanel.showCrop();
      };
      var resizePanelUpdate = function(anyInSystem) {
        memSize.getOpt(anyInSystem).each(function(sizeInput) {
          var measurements = imagePanel.getMeasurements();
          var width2 = measurements.width;
          var height2 = measurements.height;
          Representing.setValue(sizeInput, {
            width: width2,
            height: height2
          });
        });
      };
      var sharpenTransform = Optional.some(sharpen);
      var invertTransform = Optional.some(invert);
      var buttonPanelComponents = [
        createIconButton("crop", "Crop", getTransformPanelEvent(CropPanel, Optional.none(), cropPanelUpdate), false),
        createIconButton("resize", "Resize", getTransformPanelEvent(ResizePanel, Optional.none(), resizePanelUpdate), false),
        createIconButton("orientation", "Orientation", getTransformPanelEvent(FlipRotatePanel, Optional.none(), noop$1), false),
        createIconButton("brightness", "Brightness", getTransformPanelEvent(BrightnessPanel, Optional.none(), noop$1), false),
        createIconButton("sharpen", "Sharpen", getTransformPanelEvent(FilterPanel, sharpenTransform, noop$1), false),
        createIconButton("contrast", "Contrast", getTransformPanelEvent(ContrastPanel, Optional.none(), noop$1), false),
        createIconButton("color-levels", "Color levels", getTransformPanelEvent(ColorizePanel, Optional.none(), noop$1), false),
        createIconButton("gamma", "Gamma", getTransformPanelEvent(GammaPanel, Optional.none(), noop$1), false),
        createIconButton("invert", "Invert", getTransformPanelEvent(FilterPanel, invertTransform, noop$1), false)
      ];
      var ButtonPanel = Container.sketch({
        dom: panelDom,
        components: buttonPanelComponents.map(function(mem) {
          return mem.asSpec();
        })
      });
      var container = Container.sketch({
        dom: { tag: "div" },
        components: [ButtonPanel],
        containerBehaviours: derive$1([Replacing.config({})])
      });
      var memContainer = record(container);
      var getApplyButton = function(anyInSystem) {
        return memContainer.getOpt(anyInSystem).map(function(container2) {
          var panel = container2.components()[0];
          return panel.components()[panel.components().length - 1];
        });
      };
      return {
        memContainer,
        getApplyButton
      };
    };
    var global$4 = tinymce.util.Tools.resolve("tinymce.geom.Rect");
    var global$3 = tinymce.util.Tools.resolve("tinymce.util.Observable");
    var global$2 = tinymce.util.Tools.resolve("tinymce.util.VK");
    var getDocumentSize = function(doc) {
      var max3 = Math.max;
      var documentElement2 = doc.documentElement;
      var body2 = doc.body;
      var scrollWidth = max3(documentElement2.scrollWidth, body2.scrollWidth);
      var clientWidth = max3(documentElement2.clientWidth, body2.clientWidth);
      var offsetWidth = max3(documentElement2.offsetWidth, body2.offsetWidth);
      var scrollHeight = max3(documentElement2.scrollHeight, body2.scrollHeight);
      var clientHeight = max3(documentElement2.clientHeight, body2.clientHeight);
      var offsetHeight = max3(documentElement2.offsetHeight, body2.offsetHeight);
      return {
        width: scrollWidth < offsetWidth ? clientWidth : scrollWidth,
        height: scrollHeight < offsetHeight ? clientHeight : scrollHeight
      };
    };
    var isTouchEvent$1 = function(e2) {
      return isNonNullable(e2.changedTouches);
    };
    var updateWithTouchData = function(e2) {
      if (isTouchEvent$1(e2)) {
        var keys2 = "screenX screenY pageX pageY clientX clientY".split(" ");
        for (var i2 = 0; i2 < keys2.length; i2++) {
          e2[keys2[i2]] = e2.changedTouches[0][keys2[i2]];
        }
      }
    };
    function DragHelper(id2, settings) {
      var _a2, _b, _c;
      var eventOverlay;
      var handleEvents = [];
      var overlayEvents = [];
      var doc = (_a2 = settings.document) !== null && _a2 !== void 0 ? _a2 : document;
      var root = (_b = settings.root) !== null && _b !== void 0 ? _b : doc;
      var sugarDoc = SugarElement.fromDom(doc);
      var downButton;
      var startX;
      var startY;
      var handleElement = SugarElement.fromDom(root.getElementById((_c = settings.handle) !== null && _c !== void 0 ? _c : id2));
      var start4 = function(e2) {
        var rawEvent = e2.raw;
        var docSize = getDocumentSize(doc);
        updateWithTouchData(rawEvent);
        e2.prevent();
        downButton = rawEvent.button;
        startX = rawEvent.screenX;
        startY = rawEvent.screenY;
        var cursor = get$c(handleElement, "cursor");
        eventOverlay = SugarElement.fromTag("div", doc);
        setAll(eventOverlay, {
          "position": "absolute",
          "top": "0",
          "left": "0",
          "width": docSize.width + "px",
          "height": docSize.height + "px",
          "z-index": 2147483647 + "",
          "opacity": "0.0001",
          cursor
        });
        append$2(getBody(sugarDoc), eventOverlay);
        overlayEvents.push(bind(sugarDoc, "mousemove", drag), bind(sugarDoc, "touchmove", drag), bind(sugarDoc, "mouseup", stop2), bind(sugarDoc, "touchend", stop2));
        settings.start(rawEvent);
      };
      var drag = function(e2) {
        var rawEvent = e2.raw;
        updateWithTouchData(rawEvent);
        if (rawEvent.button !== downButton) {
          return stop2(e2);
        }
        rawEvent.deltaX = rawEvent.screenX - startX;
        rawEvent.deltaY = rawEvent.screenY - startY;
        e2.prevent();
        settings.drag(rawEvent);
      };
      var stop2 = function(e2) {
        updateWithTouchData(e2.raw);
        each$1(overlayEvents, function(e3) {
          return e3.unbind();
        });
        overlayEvents = [];
        remove$5(eventOverlay);
        if (settings.stop) {
          settings.stop(e2.raw);
        }
      };
      var destroy = function() {
        each$1(overlayEvents.concat(handleEvents), function(e2) {
          return e2.unbind();
        });
        overlayEvents = [];
        handleEvents = [];
        if (isNonNullable(eventOverlay)) {
          remove$5(eventOverlay);
        }
      };
      handleEvents.push(bind(handleElement, "mousedown", start4), bind(handleElement, "touchstart", start4));
      return { destroy };
    }
    var count = 0;
    var create$1 = function(currentRect, viewPortRect, clampRect, containerElm, action) {
      var dragHelpers;
      var events2 = [];
      var prefix2 = "tox-";
      var id2 = prefix2 + "crid-" + count++;
      var container = SugarElement.fromDom(containerElm);
      var handles = [
        {
          name: "move",
          xMul: 0,
          yMul: 0,
          deltaX: 1,
          deltaY: 1,
          deltaW: 0,
          deltaH: 0,
          label: "Crop Mask"
        },
        {
          name: "nw",
          xMul: 0,
          yMul: 0,
          deltaX: 1,
          deltaY: 1,
          deltaW: -1,
          deltaH: -1,
          label: "Top Left Crop Handle"
        },
        {
          name: "ne",
          xMul: 1,
          yMul: 0,
          deltaX: 0,
          deltaY: 1,
          deltaW: 1,
          deltaH: -1,
          label: "Top Right Crop Handle"
        },
        {
          name: "sw",
          xMul: 0,
          yMul: 1,
          deltaX: 1,
          deltaY: 0,
          deltaW: -1,
          deltaH: 1,
          label: "Bottom Left Crop Handle"
        },
        {
          name: "se",
          xMul: 1,
          yMul: 1,
          deltaX: 0,
          deltaY: 0,
          deltaW: 1,
          deltaH: 1,
          label: "Bottom Right Crop Handle"
        }
      ];
      var blockers = [
        "top",
        "right",
        "bottom",
        "left"
      ];
      var getAbsoluteRect = function(outerRect, relativeRect) {
        return {
          x: relativeRect.x + outerRect.x,
          y: relativeRect.y + outerRect.y,
          w: relativeRect.w,
          h: relativeRect.h
        };
      };
      var getRelativeRect = function(outerRect, innerRect) {
        return {
          x: innerRect.x - outerRect.x,
          y: innerRect.y - outerRect.y,
          w: innerRect.w,
          h: innerRect.h
        };
      };
      var getInnerRect = function() {
        return getRelativeRect(clampRect, currentRect);
      };
      var moveRect = function(handle2, startRect, deltaX, deltaY) {
        var x2 = startRect.x + deltaX * handle2.deltaX;
        var y2 = startRect.y + deltaY * handle2.deltaY;
        var w2 = Math.max(20, startRect.w + deltaX * handle2.deltaW);
        var h3 = Math.max(20, startRect.h + deltaY * handle2.deltaH);
        var rect2 = currentRect = global$4.clamp({
          x: x2,
          y: y2,
          w: w2,
          h: h3
        }, clampRect, handle2.name === "move");
        rect2 = getRelativeRect(clampRect, rect2);
        instance.fire("updateRect", { rect: rect2 });
        setInnerRect(rect2);
      };
      var render2 = function() {
        var createDragHelper = function(handle2) {
          var startRect;
          return DragHelper(id2, {
            document: containerElm.ownerDocument,
            root: getRootNode(container).dom,
            handle: id2 + "-" + handle2.name,
            start: function() {
              startRect = currentRect;
            },
            drag: function(e2) {
              moveRect(handle2, startRect, e2.deltaX, e2.deltaY);
            }
          });
        };
        var cropContainer = SugarElement.fromTag("div");
        setAll$1(cropContainer, {
          id: id2,
          "class": prefix2 + "croprect-container",
          "role": "grid",
          "aria-dropeffect": "execute"
        });
        append$2(container, cropContainer);
        each$1(blockers, function(blocker) {
          descendant(container, "#" + id2).each(function(blockerElm) {
            var cropBlocker = SugarElement.fromTag("div");
            setAll$1(cropBlocker, {
              "id": id2 + "-" + blocker,
              "class": prefix2 + "croprect-block",
              "data-mce-bogus": "all"
            });
            set$7(cropBlocker, "display", "none");
            append$2(blockerElm, cropBlocker);
          });
        });
        each$1(handles, function(handle2) {
          descendant(container, "#" + id2).each(function(handleElm) {
            var cropHandle = SugarElement.fromTag("div");
            setAll$1(cropHandle, {
              "id": id2 + "-" + handle2.name,
              "aria-label": handle2.label,
              "aria-grabbed": "false",
              "data-mce-bogus": "all",
              "role": "gridcell",
              "tabindex": "-1",
              "title": handle2.label
            });
            add$1(cropHandle, [
              prefix2 + "croprect-handle",
              prefix2 + "croprect-handle-" + handle2.name
            ]);
            set$7(cropHandle, "display", "none");
            append$2(handleElm, cropHandle);
          });
        });
        dragHelpers = map$2(handles, createDragHelper);
        repaint(currentRect);
        var handleFocus = function(e2) {
          set$8(e2.target, "aria-grabbed", e2.raw.type === "focus" ? "true" : "false");
        };
        var handleKeydown = function(e2) {
          var activeHandle;
          each$1(handles, function(handle2) {
            if (get$d(e2.target, "id") === id2 + "-" + handle2.name) {
              activeHandle = handle2;
              return false;
            }
          });
          var moveAndBlock = function(evt, handle2, startRect, deltaX, deltaY) {
            evt.stopPropagation();
            evt.preventDefault();
            moveRect(activeHandle, startRect, deltaX, deltaY);
          };
          switch (e2.raw.keyCode) {
            case global$2.LEFT:
              moveAndBlock(e2, activeHandle, currentRect, -10, 0);
              break;
            case global$2.RIGHT:
              moveAndBlock(e2, activeHandle, currentRect, 10, 0);
              break;
            case global$2.UP:
              moveAndBlock(e2, activeHandle, currentRect, 0, -10);
              break;
            case global$2.DOWN:
              moveAndBlock(e2, activeHandle, currentRect, 0, 10);
              break;
            case global$2.ENTER:
            case global$2.SPACEBAR:
              e2.prevent();
              action();
              break;
          }
        };
        events2.push(bind(container, "focusin", handleFocus), bind(container, "focusout", handleFocus), bind(container, "keydown", handleKeydown));
      };
      var toggleVisibility = function(state) {
        var selectors = __spreadArray(__spreadArray([], map$2(handles, function(handle2) {
          return "#" + id2 + "-" + handle2.name;
        }), true), map$2(blockers, function(blocker) {
          return "#" + id2 + "-" + blocker;
        }), true).join(",");
        var elems = descendants(container, selectors);
        if (state) {
          each$1(elems, function(elm) {
            return remove$6(elm, "display");
          });
        } else {
          each$1(elems, function(elm) {
            return set$7(elm, "display", "none");
          });
        }
      };
      var repaint = function(rect2) {
        var updateElementRect = function(name2, newRect) {
          descendant(container, "#" + id2 + "-" + name2).each(function(elm) {
            setAll(elm, {
              left: newRect.x + "px",
              top: newRect.y + "px",
              width: Math.max(0, newRect.w) + "px",
              height: Math.max(0, newRect.h) + "px"
            });
          });
        };
        each$1(handles, function(handle2) {
          descendant(container, "#" + id2 + "-" + handle2.name).each(function(elm) {
            setAll(elm, {
              left: rect2.w * handle2.xMul + rect2.x + "px",
              top: rect2.h * handle2.yMul + rect2.y + "px"
            });
          });
        });
        updateElementRect("top", {
          x: viewPortRect.x,
          y: viewPortRect.y,
          w: viewPortRect.w,
          h: rect2.y - viewPortRect.y
        });
        updateElementRect("right", {
          x: rect2.x + rect2.w,
          y: rect2.y,
          w: viewPortRect.w - rect2.x - rect2.w + viewPortRect.x,
          h: rect2.h
        });
        updateElementRect("bottom", {
          x: viewPortRect.x,
          y: rect2.y + rect2.h,
          w: viewPortRect.w,
          h: viewPortRect.h - rect2.y - rect2.h + viewPortRect.y
        });
        updateElementRect("left", {
          x: viewPortRect.x,
          y: rect2.y,
          w: rect2.x - viewPortRect.x,
          h: rect2.h
        });
        updateElementRect("move", rect2);
      };
      var setRect = function(rect2) {
        currentRect = rect2;
        repaint(currentRect);
      };
      var setViewPortRect = function(rect2) {
        viewPortRect = rect2;
        repaint(currentRect);
      };
      var setInnerRect = function(rect2) {
        setRect(getAbsoluteRect(clampRect, rect2));
      };
      var setClampRect = function(rect2) {
        clampRect = rect2;
        repaint(currentRect);
      };
      var destroy = function() {
        each$1(dragHelpers, function(helper) {
          return helper.destroy();
        });
        dragHelpers = [];
        each$1(events2, function(e2) {
          return e2.unbind();
        });
        events2 = [];
      };
      render2();
      var instance = __assign(__assign({}, global$3), {
        toggleVisibility,
        setClampRect,
        setRect,
        getInnerRect,
        setInnerRect,
        setViewPortRect,
        destroy
      });
      return instance;
    };
    var CropRect = { create: create$1 };
    var loadImage = function(image) {
      return new global$c(function(resolve2) {
        var loaded = function() {
          image.removeEventListener("load", loaded);
          resolve2(image);
        };
        if (image.complete) {
          resolve2(image);
        } else {
          image.addEventListener("load", loaded);
        }
      });
    };
    var renderImagePanel = function(initialUrl) {
      var memBg = record({
        dom: {
          tag: "div",
          classes: ["tox-image-tools__image-bg"],
          attributes: { role: "presentation" }
        }
      });
      var zoomState = Cell(1);
      var cropRect = api$1();
      var rectState = Cell({
        x: 0,
        y: 0,
        w: 1,
        h: 1
      });
      var viewRectState = Cell({
        x: 0,
        y: 0,
        w: 1,
        h: 1
      });
      var repaintImg = function(anyInSystem, img) {
        memContainer.getOpt(anyInSystem).each(function(panel) {
          var zoom3 = zoomState.get();
          var panelW = get$a(panel.element);
          var panelH = get$b(panel.element);
          var width2 = img.dom.naturalWidth * zoom3;
          var height2 = img.dom.naturalHeight * zoom3;
          var left3 = Math.max(0, panelW / 2 - width2 / 2);
          var top3 = Math.max(0, panelH / 2 - height2 / 2);
          var css = {
            left: left3.toString() + "px",
            top: top3.toString() + "px",
            width: width2.toString() + "px",
            height: height2.toString() + "px",
            position: "absolute"
          };
          setAll(img, css);
          memBg.getOpt(panel).each(function(bg) {
            setAll(bg.element, css);
          });
          cropRect.run(function(cRect) {
            var rect2 = rectState.get();
            cRect.setRect({
              x: rect2.x * zoom3 + left3,
              y: rect2.y * zoom3 + top3,
              w: rect2.w * zoom3,
              h: rect2.h * zoom3
            });
            cRect.setClampRect({
              x: left3,
              y: top3,
              w: width2,
              h: height2
            });
            cRect.setViewPortRect({
              x: 0,
              y: 0,
              w: panelW,
              h: panelH
            });
          });
        });
      };
      var zoomFit = function(anyInSystem, img) {
        memContainer.getOpt(anyInSystem).each(function(panel) {
          var panelW = get$a(panel.element);
          var panelH = get$b(panel.element);
          var width2 = img.dom.naturalWidth;
          var height2 = img.dom.naturalHeight;
          var zoom3 = Math.min(panelW / width2, panelH / height2);
          if (zoom3 >= 1) {
            zoomState.set(1);
          } else {
            zoomState.set(zoom3);
          }
        });
      };
      var updateSrc = function(anyInSystem, url) {
        var img = SugarElement.fromTag("img");
        set$8(img, "src", url);
        return loadImage(img.dom).then(function() {
          if (anyInSystem.getSystem().isConnected()) {
            memContainer.getOpt(anyInSystem).map(function(panel) {
              var aImg = external$2({ element: img });
              Replacing.replaceAt(panel, 1, Optional.some(aImg));
              var lastViewRect = viewRectState.get();
              var viewRect = {
                x: 0,
                y: 0,
                w: img.dom.naturalWidth,
                h: img.dom.naturalHeight
              };
              viewRectState.set(viewRect);
              var rect2 = global$4.inflate(viewRect, -20, -20);
              rectState.set(rect2);
              if (lastViewRect.w !== viewRect.w || lastViewRect.h !== viewRect.h) {
                zoomFit(panel, img);
              }
              repaintImg(panel, img);
            });
          }
        });
      };
      var zoom2 = function(anyInSystem, direction) {
        var currentZoom = zoomState.get();
        var newZoom = direction > 0 ? Math.min(2, currentZoom + 0.1) : Math.max(0.1, currentZoom - 0.1);
        zoomState.set(newZoom);
        memContainer.getOpt(anyInSystem).each(function(panel) {
          var img = panel.components()[1].element;
          repaintImg(panel, img);
        });
      };
      var showCrop = function() {
        cropRect.run(function(cRect) {
          cRect.toggleVisibility(true);
        });
      };
      var hideCrop = function() {
        cropRect.run(function(cRect) {
          cRect.toggleVisibility(false);
        });
      };
      var getRect = function() {
        return rectState.get();
      };
      var container = Container.sketch({
        dom: {
          tag: "div",
          classes: ["tox-image-tools__image"]
        },
        components: [
          memBg.asSpec(),
          {
            dom: {
              tag: "img",
              attributes: { src: initialUrl }
            }
          },
          {
            dom: { tag: "div" },
            behaviours: derive$1([config("image-panel-crop-events", [
              runOnAttached(function(comp) {
                memContainer.getOpt(comp).each(function(container2) {
                  var el = container2.element.dom;
                  var cRect = CropRect.create({
                    x: 10,
                    y: 10,
                    w: 100,
                    h: 100
                  }, {
                    x: 0,
                    y: 0,
                    w: 200,
                    h: 200
                  }, {
                    x: 0,
                    y: 0,
                    w: 200,
                    h: 200
                  }, el, noop3);
                  cRect.toggleVisibility(false);
                  cRect.on("updateRect", function(e2) {
                    var rect2 = e2.rect;
                    var zoom3 = zoomState.get();
                    var newRect = {
                      x: Math.round(rect2.x / zoom3),
                      y: Math.round(rect2.y / zoom3),
                      w: Math.round(rect2.w / zoom3),
                      h: Math.round(rect2.h / zoom3)
                    };
                    rectState.set(newRect);
                  });
                  cropRect.set(cRect);
                });
              }),
              runOnDetached(function() {
                cropRect.clear();
              })
            ])])
          }
        ],
        containerBehaviours: derive$1([
          Replacing.config({}),
          config("image-panel-events", [runOnAttached(function(comp) {
            updateSrc(comp, initialUrl);
          })])
        ])
      });
      var memContainer = record(container);
      var getMeasurements = function() {
        var viewRect = viewRectState.get();
        return {
          width: viewRect.w,
          height: viewRect.h
        };
      };
      return {
        memContainer,
        updateSrc,
        zoom: zoom2,
        showCrop,
        hideCrop,
        getRect,
        getMeasurements
      };
    };
    var createButton = function(innerHtml, icon, disabled, action, providersBackstage) {
      return renderIconButton({
        name: innerHtml,
        icon: Optional.some(icon),
        disabled,
        tooltip: Optional.some(innerHtml),
        primary: false,
        borderless: false
      }, action, providersBackstage);
    };
    var setButtonEnabled = function(button2, enabled) {
      if (enabled) {
        Disabling.enable(button2);
      } else {
        Disabling.disable(button2);
      }
    };
    var renderSideBar = function(providersBackstage) {
      var updateButtonUndoStates = function(anyInSystem, undoEnabled, redoEnabled) {
        memUndo.getOpt(anyInSystem).each(function(undo2) {
          setButtonEnabled(undo2, undoEnabled);
        });
        memRedo.getOpt(anyInSystem).each(function(redo2) {
          setButtonEnabled(redo2, redoEnabled);
        });
      };
      var memUndo = record(createButton("Undo", "undo", true, function(button2) {
        emitWith(button2, internal.undo(), { direction: 1 });
      }, providersBackstage));
      var memRedo = record(createButton("Redo", "redo", true, function(button2) {
        emitWith(button2, internal.redo(), { direction: 1 });
      }, providersBackstage));
      var container = Container.sketch({
        dom: {
          tag: "div",
          classes: [
            "tox-image-tools__toolbar",
            "tox-image-tools__sidebar"
          ]
        },
        components: [
          memUndo.asSpec(),
          memRedo.asSpec(),
          createButton("Zoom in", "zoom-in", false, function(button2) {
            emitWith(button2, internal.zoom(), { direction: 1 });
          }, providersBackstage),
          createButton("Zoom out", "zoom-out", false, function(button2) {
            emitWith(button2, internal.zoom(), { direction: -1 });
          }, providersBackstage)
        ]
      });
      return {
        container,
        updateButtonUndoStates
      };
    };
    function UndoStack() {
      var data = [];
      var index = -1;
      var add4 = function(state) {
        var removed = data.splice(++index);
        data.push(state);
        return {
          state,
          removed
        };
      };
      var undo2 = function() {
        if (canUndo()) {
          return data[--index];
        }
      };
      var redo2 = function() {
        if (canRedo()) {
          return data[++index];
        }
      };
      var canUndo = function() {
        return index > 0;
      };
      var canRedo = function() {
        return index !== -1 && index < data.length - 1;
      };
      return {
        data,
        add: add4,
        undo: undo2,
        redo: redo2,
        canUndo,
        canRedo
      };
    }
    var makeState = function(initialState) {
      var blobState = Cell(initialState);
      var tempState = value$1();
      var undoStack = UndoStack();
      undoStack.add(initialState);
      var getBlobState = function() {
        return blobState.get();
      };
      var setBlobState = function(state) {
        blobState.set(state);
      };
      var getTempState = function() {
        return tempState.get().getOrThunk(blobState.get);
      };
      var updateTempState = function(blob) {
        var newTempState = createState(blob);
        destroyTempState();
        tempState.set(newTempState);
        return newTempState.url;
      };
      var createState = function(blob) {
        return {
          blob,
          url: URL.createObjectURL(blob)
        };
      };
      var destroyState = function(state) {
        URL.revokeObjectURL(state.url);
      };
      var destroyStates = function(states) {
        global$5.each(states, destroyState);
      };
      var destroyTempState = function() {
        tempState.on(destroyState);
        tempState.clear();
      };
      var addBlobState = function(blob) {
        var newState = createState(blob);
        setBlobState(newState);
        var removed = undoStack.add(newState).removed;
        destroyStates(removed);
        return newState.url;
      };
      var addTempState = function(blob) {
        var newState = createState(blob);
        tempState.set(newState);
        return newState.url;
      };
      var applyTempState = function(postApply) {
        return tempState.get().fold(noop3, function(temp) {
          addBlobState(temp.blob);
          postApply();
        });
      };
      var undo2 = function() {
        var currentState = undoStack.undo();
        setBlobState(currentState);
        return currentState.url;
      };
      var redo2 = function() {
        var currentState = undoStack.redo();
        setBlobState(currentState);
        return currentState.url;
      };
      var getHistoryStates = function() {
        var undoEnabled = undoStack.canUndo();
        var redoEnabled = undoStack.canRedo();
        return {
          undoEnabled,
          redoEnabled
        };
      };
      return {
        getBlobState,
        setBlobState,
        addBlobState,
        getTempState,
        updateTempState,
        addTempState,
        applyTempState,
        destroyTempState,
        undo: undo2,
        redo: redo2,
        getHistoryStates
      };
    };
    var renderImageTools = function(detail, providersBackstage) {
      var state = makeState(detail.currentState);
      var zoom2 = function(anyInSystem, simulatedEvent) {
        var direction = simulatedEvent.event.direction;
        imagePanel.zoom(anyInSystem, direction);
      };
      var updateButtonUndoStates = function(anyInSystem) {
        var historyStates = state.getHistoryStates();
        sideBar.updateButtonUndoStates(anyInSystem, historyStates.undoEnabled, historyStates.redoEnabled);
        emitWith(anyInSystem, external.formActionEvent, {
          name: external.saveState(),
          value: historyStates.undoEnabled
        });
      };
      var disableUndoRedo = function(anyInSystem) {
        sideBar.updateButtonUndoStates(anyInSystem, false, false);
      };
      var undo2 = function(anyInSystem, _simulatedEvent) {
        var url = state.undo();
        updateSrc(anyInSystem, url).then(function(_oImg) {
          unblock2(anyInSystem);
          updateButtonUndoStates(anyInSystem);
        });
      };
      var redo2 = function(anyInSystem, _simulatedEvent) {
        var url = state.redo();
        updateSrc(anyInSystem, url).then(function(_oImg) {
          unblock2(anyInSystem);
          updateButtonUndoStates(anyInSystem);
        });
      };
      var imageResultToBlob = function(ir) {
        return ir.toBlob();
      };
      var block2 = function(anyInSystem) {
        emitWith(anyInSystem, external.formActionEvent, {
          name: external.disable(),
          value: {}
        });
      };
      var unblock2 = function(anyInSystem) {
        editPanel.getApplyButton(anyInSystem).each(function(applyButton) {
          Disabling.enable(applyButton);
        });
        emitWith(anyInSystem, external.formActionEvent, {
          name: external.enable(),
          value: {}
        });
      };
      var updateSrc = function(anyInSystem, src) {
        block2(anyInSystem);
        return imagePanel.updateSrc(anyInSystem, src);
      };
      var blobManipulate = function(anyInSystem, blob, filter2, action, swap4) {
        block2(anyInSystem);
        blobToImageResult(blob).then(filter2).then(imageResultToBlob).then(action).then(function(url) {
          return updateSrc(anyInSystem, url);
        }).then(function() {
          updateButtonUndoStates(anyInSystem);
          swap4();
          unblock2(anyInSystem);
        }).catch(function(err) {
          console.log(err);
          if (anyInSystem.getSystem().isConnected()) {
            unblock2(anyInSystem);
          }
        });
      };
      var manipulate = function(anyInSystem, filter2, swap4) {
        var blob = state.getBlobState().blob;
        var action = function(blob2) {
          return state.updateTempState(blob2);
        };
        blobManipulate(anyInSystem, blob, filter2, action, swap4);
      };
      var tempManipulate = function(anyInSystem, filter2) {
        var blob = state.getTempState().blob;
        var action = function(blob2) {
          return state.addTempState(blob2);
        };
        blobManipulate(anyInSystem, blob, filter2, action, noop3);
      };
      var manipulateApply = function(anyInSystem, filter2, swap4) {
        var blob = state.getBlobState().blob;
        var action = function(blob2) {
          var url = state.addBlobState(blob2);
          destroyTempState(anyInSystem);
          return url;
        };
        blobManipulate(anyInSystem, blob, filter2, action, swap4);
      };
      var apply2 = function(anyInSystem, simulatedEvent) {
        var postApply = function() {
          destroyTempState(anyInSystem);
          var swap4 = simulatedEvent.event.swap;
          swap4();
        };
        state.applyTempState(postApply);
      };
      var destroyTempState = function(anyInSystem) {
        var currentUrl = state.getBlobState().url;
        state.destroyTempState();
        updateButtonUndoStates(anyInSystem);
        return currentUrl;
      };
      var cancel = function(anyInSystem) {
        var currentUrl = destroyTempState(anyInSystem);
        updateSrc(anyInSystem, currentUrl).then(function(_oImg) {
          unblock2(anyInSystem);
        });
      };
      var back2 = function(anyInSystem, simulatedEvent) {
        cancel(anyInSystem);
        var swap4 = simulatedEvent.event.swap;
        swap4();
        imagePanel.hideCrop();
      };
      var transform2 = function(anyInSystem, simulatedEvent) {
        return manipulate(anyInSystem, simulatedEvent.event.transform, noop3);
      };
      var tempTransform2 = function(anyInSystem, simulatedEvent) {
        return tempManipulate(anyInSystem, simulatedEvent.event.transform);
      };
      var transformApply2 = function(anyInSystem, simulatedEvent) {
        return manipulateApply(anyInSystem, simulatedEvent.event.transform, simulatedEvent.event.swap);
      };
      var imagePanel = renderImagePanel(detail.currentState.url);
      var sideBar = renderSideBar(providersBackstage);
      var editPanel = renderEditPanel(imagePanel, providersBackstage);
      var swap3 = function(anyInSystem, simulatedEvent) {
        disableUndoRedo(anyInSystem);
        var transform3 = simulatedEvent.event.transform;
        var swap4 = simulatedEvent.event.swap;
        transform3.fold(function() {
          swap4();
        }, function(transform4) {
          manipulate(anyInSystem, transform4, swap4);
        });
      };
      return {
        dom: {
          tag: "div",
          attributes: { role: "presentation" }
        },
        components: [
          editPanel.memContainer.asSpec(),
          imagePanel.memContainer.asSpec(),
          sideBar.container
        ],
        behaviours: derive$1([
          Representing.config({
            store: {
              mode: "manual",
              getValue: function() {
                return state.getBlobState();
              }
            }
          }),
          config("image-tools-events", [
            run$1(internal.undo(), undo2),
            run$1(internal.redo(), redo2),
            run$1(internal.zoom(), zoom2),
            run$1(internal.back(), back2),
            run$1(internal.apply(), apply2),
            run$1(internal.transform(), transform2),
            run$1(internal.tempTransform(), tempTransform2),
            run$1(internal.transformApply(), transformApply2),
            run$1(internal.swap(), swap3)
          ]),
          ComposingConfigs.self()
        ])
      };
    };
    var renderLabel = function(spec, backstageShared) {
      var label = {
        dom: {
          tag: "label",
          innerHtml: backstageShared.providers.translate(spec.label),
          classes: ["tox-label"]
        }
      };
      var comps = map$2(spec.items, backstageShared.interpreter);
      return {
        dom: {
          tag: "div",
          classes: ["tox-form__group"]
        },
        components: [label].concat(comps),
        behaviours: derive$1([
          ComposingConfigs.self(),
          Replacing.config({}),
          RepresentingConfigs.domHtml(Optional.none()),
          Keying.config({ mode: "acyclic" })
        ])
      };
    };
    var isSingleListItem = function(item2) {
      return !has$2(item2, "items");
    };
    var dataAttribute = "data-value";
    var fetchItems = function(dropdownComp, name2, items, selectedValue) {
      return map$2(items, function(item2) {
        if (!isSingleListItem(item2)) {
          return {
            type: "nestedmenuitem",
            text: item2.text,
            getSubmenuItems: function() {
              return fetchItems(dropdownComp, name2, item2.items, selectedValue);
            }
          };
        } else {
          return {
            type: "togglemenuitem",
            text: item2.text,
            value: item2.value,
            active: item2.value === selectedValue,
            onAction: function() {
              Representing.setValue(dropdownComp, item2.value);
              emitWith(dropdownComp, formChangeEvent, { name: name2 });
              Focusing.focus(dropdownComp);
            }
          };
        }
      });
    };
    var findItemByValue = function(items, value2) {
      return findMap(items, function(item2) {
        if (!isSingleListItem(item2)) {
          return findItemByValue(item2.items, value2);
        } else {
          return someIf(item2.value === value2, item2);
        }
      });
    };
    var renderListBox = function(spec, backstage) {
      var providersBackstage = backstage.shared.providers;
      var initialItem = head(spec.items).filter(isSingleListItem);
      var pLabel = spec.label.map(function(label) {
        return renderLabel$2(label, providersBackstage);
      });
      var pField = FormField.parts.field({
        dom: {},
        factory: {
          sketch: function(sketchSpec) {
            return renderCommonDropdown({
              uid: sketchSpec.uid,
              text: initialItem.map(function(item2) {
                return item2.text;
              }),
              icon: Optional.none(),
              tooltip: spec.label,
              role: Optional.none(),
              fetch: function(comp, callback2) {
                var items = fetchItems(comp, spec.name, spec.items, Representing.getValue(comp));
                callback2(build(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, false));
              },
              onSetup: constant$1(noop3),
              getApi: constant$1({}),
              columns: 1,
              presets: "normal",
              classes: [],
              dropdownBehaviours: [
                Tabstopping.config({}),
                Representing.config({
                  store: {
                    mode: "manual",
                    initialValue: initialItem.map(function(item2) {
                      return item2.value;
                    }).getOr(""),
                    getValue: function(comp) {
                      return get$d(comp.element, dataAttribute);
                    },
                    setValue: function(comp, data) {
                      findItemByValue(spec.items, data).each(function(item2) {
                        set$8(comp.element, dataAttribute, item2.value);
                        emitWith(comp, updateMenuText, { text: item2.text });
                      });
                    }
                  }
                })
              ]
            }, "tox-listbox", backstage.shared);
          }
        }
      });
      var listBoxWrap = {
        dom: {
          tag: "div",
          classes: ["tox-listboxfield"]
        },
        components: [pField]
      };
      return FormField.sketch({
        dom: {
          tag: "div",
          classes: ["tox-form__group"]
        },
        components: flatten([
          pLabel.toArray(),
          [listBoxWrap]
        ]),
        fieldBehaviours: derive$1([Disabling.config({
          disabled: constant$1(spec.disabled),
          onDisabled: function(comp) {
            FormField.getField(comp).each(Disabling.disable);
          },
          onEnabled: function(comp) {
            FormField.getField(comp).each(Disabling.enable);
          }
        })])
      });
    };
    var renderPanel = function(spec, backstage) {
      return {
        dom: {
          tag: "div",
          classes: spec.classes
        },
        components: map$2(spec.items, backstage.shared.interpreter)
      };
    };
    var factory$e = function(detail, _spec) {
      var options = map$2(detail.options, function(option2) {
        return {
          dom: {
            tag: "option",
            value: option2.value,
            innerHtml: option2.text
          }
        };
      });
      var initialValues = detail.data.map(function(v2) {
        return wrap$1("initialValue", v2);
      }).getOr({});
      return {
        uid: detail.uid,
        dom: {
          tag: "select",
          classes: detail.selectClasses,
          attributes: detail.selectAttributes
        },
        components: options,
        behaviours: augment(detail.selectBehaviours, [
          Focusing.config({}),
          Representing.config({
            store: __assign({
              mode: "manual",
              getValue: function(select2) {
                return get$5(select2.element);
              },
              setValue: function(select2, newValue) {
                var found = find$5(detail.options, function(opt) {
                  return opt.value === newValue;
                });
                if (found.isSome()) {
                  set$4(select2.element, newValue);
                }
              }
            }, initialValues)
          })
        ])
      };
    };
    var HtmlSelect = single({
      name: "HtmlSelect",
      configFields: [
        required$1("options"),
        field("selectBehaviours", [
          Focusing,
          Representing
        ]),
        defaulted("selectClasses", []),
        defaulted("selectAttributes", {}),
        option("data")
      ],
      factory: factory$e
    });
    var renderSelectBox = function(spec, providersBackstage) {
      var translatedOptions = map$2(spec.items, function(item2) {
        return {
          text: providersBackstage.translate(item2.text),
          value: item2.value
        };
      });
      var pLabel = spec.label.map(function(label) {
        return renderLabel$2(label, providersBackstage);
      });
      var pField = FormField.parts.field({
        dom: {},
        selectAttributes: { size: spec.size },
        options: translatedOptions,
        factory: HtmlSelect,
        selectBehaviours: derive$1([
          Disabling.config({
            disabled: function() {
              return spec.disabled || providersBackstage.isDisabled();
            }
          }),
          Tabstopping.config({}),
          config("selectbox-change", [run$1(change(), function(component, _2) {
            emitWith(component, formChangeEvent, { name: spec.name });
          })])
        ])
      });
      var chevron = spec.size > 1 ? Optional.none() : Optional.some(render$3("chevron-down", {
        tag: "div",
        classes: ["tox-selectfield__icon-js"]
      }, providersBackstage.icons));
      var selectWrap = {
        dom: {
          tag: "div",
          classes: ["tox-selectfield"]
        },
        components: flatten([
          [pField],
          chevron.toArray()
        ])
      };
      return FormField.sketch({
        dom: {
          tag: "div",
          classes: ["tox-form__group"]
        },
        components: flatten([
          pLabel.toArray(),
          [selectWrap]
        ]),
        fieldBehaviours: derive$1([
          Disabling.config({
            disabled: function() {
              return spec.disabled || providersBackstage.isDisabled();
            },
            onDisabled: function(comp) {
              FormField.getField(comp).each(Disabling.disable);
            },
            onEnabled: function(comp) {
              FormField.getField(comp).each(Disabling.enable);
            }
          }),
          receivingConfig()
        ])
      });
    };
    var renderTable = function(spec, providersBackstage) {
      var renderTh = function(text2) {
        return {
          dom: {
            tag: "th",
            innerHtml: providersBackstage.translate(text2)
          }
        };
      };
      var renderHeader2 = function(header) {
        return {
          dom: { tag: "thead" },
          components: [{
            dom: { tag: "tr" },
            components: map$2(header, renderTh)
          }]
        };
      };
      var renderTd = function(text2) {
        return {
          dom: {
            tag: "td",
            innerHtml: providersBackstage.translate(text2)
          }
        };
      };
      var renderTr = function(row) {
        return {
          dom: { tag: "tr" },
          components: map$2(row, renderTd)
        };
      };
      var renderRows = function(rows) {
        return {
          dom: { tag: "tbody" },
          components: map$2(rows, renderTr)
        };
      };
      return {
        dom: {
          tag: "table",
          classes: ["tox-dialog__table"]
        },
        components: [
          renderHeader2(spec.header),
          renderRows(spec.cells)
        ],
        behaviours: derive$1([
          Tabstopping.config({}),
          Focusing.config({})
        ])
      };
    };
    var renderTextField = function(spec, providersBackstage) {
      var pLabel = spec.label.map(function(label) {
        return renderLabel$2(label, providersBackstage);
      });
      var baseInputBehaviours = [
        Disabling.config({
          disabled: function() {
            return spec.disabled || providersBackstage.isDisabled();
          }
        }),
        receivingConfig(),
        Keying.config({
          mode: "execution",
          useEnter: spec.multiline !== true,
          useControlEnter: spec.multiline === true,
          execute: function(comp) {
            emit(comp, formSubmitEvent);
            return Optional.some(true);
          }
        }),
        config("textfield-change", [
          run$1(input(), function(component, _2) {
            emitWith(component, formChangeEvent, { name: spec.name });
          }),
          run$1(postPaste(), function(component, _2) {
            emitWith(component, formChangeEvent, { name: spec.name });
          })
        ]),
        Tabstopping.config({})
      ];
      var validatingBehaviours = spec.validation.map(function(vl) {
        return Invalidating.config({
          getRoot: function(input2) {
            return parent(input2.element);
          },
          invalidClass: "tox-invalid",
          validator: {
            validate: function(input2) {
              var v2 = Representing.getValue(input2);
              var result = vl.validator(v2);
              return Future.pure(result === true ? Result.value(v2) : Result.error(result));
            },
            validateOnLoad: vl.validateOnLoad
          }
        });
      }).toArray();
      var placeholder2 = spec.placeholder.fold(constant$1({}), function(p2) {
        return { placeholder: providersBackstage.translate(p2) };
      });
      var inputMode = spec.inputMode.fold(constant$1({}), function(mode) {
        return { inputmode: mode };
      });
      var inputAttributes = __assign(__assign({}, placeholder2), inputMode);
      var pField = FormField.parts.field({
        tag: spec.multiline === true ? "textarea" : "input",
        inputAttributes,
        inputClasses: [spec.classname],
        inputBehaviours: derive$1(flatten([
          baseInputBehaviours,
          validatingBehaviours
        ])),
        selectOnFocus: false,
        factory: Input
      });
      var extraClasses = spec.flex ? ["tox-form__group--stretched"] : [];
      var extraClasses2 = extraClasses.concat(spec.maximized ? ["tox-form-group--maximize"] : []);
      var extraBehaviours = [
        Disabling.config({
          disabled: function() {
            return spec.disabled || providersBackstage.isDisabled();
          },
          onDisabled: function(comp) {
            FormField.getField(comp).each(Disabling.disable);
          },
          onEnabled: function(comp) {
            FormField.getField(comp).each(Disabling.enable);
          }
        }),
        receivingConfig()
      ];
      return renderFormFieldWith(pLabel, pField, extraClasses2, extraBehaviours);
    };
    var renderInput = function(spec, providersBackstage) {
      return renderTextField({
        name: spec.name,
        multiline: false,
        label: spec.label,
        inputMode: spec.inputMode,
        placeholder: spec.placeholder,
        flex: false,
        disabled: spec.disabled,
        classname: "tox-textfield",
        validation: Optional.none(),
        maximized: spec.maximized
      }, providersBackstage);
    };
    var renderTextarea = function(spec, providersBackstage) {
      return renderTextField({
        name: spec.name,
        multiline: true,
        label: spec.label,
        inputMode: Optional.none(),
        placeholder: spec.placeholder,
        flex: true,
        disabled: spec.disabled,
        classname: "tox-textarea",
        validation: Optional.none(),
        maximized: spec.maximized
      }, providersBackstage);
    };
    var events$6 = function(streamConfig, streamState) {
      var streams = streamConfig.stream.streams;
      var processor = streams.setup(streamConfig, streamState);
      return derive$2([
        run$1(streamConfig.event, processor),
        runOnDetached(function() {
          return streamState.cancel();
        })
      ].concat(streamConfig.cancelEvent.map(function(e2) {
        return [run$1(e2, function() {
          return streamState.cancel();
        })];
      }).getOr([])));
    };
    var ActiveStreaming = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      events: events$6
    });
    var throttle = function(_config) {
      var state = Cell(null);
      var readState = function() {
        return { timer: state.get() !== null ? "set" : "unset" };
      };
      var setTimer = function(t3) {
        state.set(t3);
      };
      var cancel = function() {
        var t3 = state.get();
        if (t3 !== null) {
          t3.cancel();
        }
      };
      return nu$8({
        readState,
        setTimer,
        cancel
      });
    };
    var init$9 = function(spec) {
      return spec.stream.streams.state(spec);
    };
    var StreamingState = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      throttle,
      init: init$9
    });
    var setup$c = function(streamInfo, streamState) {
      var sInfo = streamInfo.stream;
      var throttler = last(streamInfo.onStream, sInfo.delay);
      streamState.setTimer(throttler);
      return function(component, simulatedEvent) {
        throttler.throttle(component, simulatedEvent);
        if (sInfo.stopEvent) {
          simulatedEvent.stop();
        }
      };
    };
    var StreamingSchema = [
      requiredOf("stream", choose$1("mode", {
        throttle: [
          required$1("delay"),
          defaulted("stopEvent", true),
          output$1("streams", {
            setup: setup$c,
            state: throttle
          })
        ]
      })),
      defaulted("event", "input"),
      option("cancelEvent"),
      onStrictHandler("onStream")
    ];
    var Streaming = create$7({
      fields: StreamingSchema,
      name: "streaming",
      active: ActiveStreaming,
      state: StreamingState
    });
    var setValueFromItem = function(model, input2, item2) {
      var itemData = Representing.getValue(item2);
      Representing.setValue(input2, itemData);
      setCursorAtEnd(input2);
    };
    var setSelectionOn = function(input2, f2) {
      var el = input2.element;
      var value2 = get$5(el);
      var node = el.dom;
      if (get$d(el, "type") !== "number") {
        f2(node, value2);
      }
    };
    var setCursorAtEnd = function(input2) {
      setSelectionOn(input2, function(node, value2) {
        return node.setSelectionRange(value2.length, value2.length);
      });
    };
    var setSelectionToEnd = function(input2, startOffset) {
      setSelectionOn(input2, function(node, value2) {
        return node.setSelectionRange(startOffset, value2.length);
      });
    };
    var attemptSelectOver = function(model, input2, item2) {
      if (!model.selectsOver) {
        return Optional.none();
      } else {
        var currentValue2 = Representing.getValue(input2);
        var inputDisplay_1 = model.getDisplayText(currentValue2);
        var itemValue = Representing.getValue(item2);
        var itemDisplay = model.getDisplayText(itemValue);
        return itemDisplay.indexOf(inputDisplay_1) === 0 ? Optional.some(function() {
          setValueFromItem(model, input2, item2);
          setSelectionToEnd(input2, inputDisplay_1.length);
        }) : Optional.none();
      }
    };
    var itemExecute = constant$1("alloy.typeahead.itemexecute");
    var make$3 = function(detail, components2, spec, externals) {
      var navigateList = function(comp, simulatedEvent, highlighter) {
        detail.previewing.set(false);
        var sandbox = Coupling.getCoupled(comp, "sandbox");
        if (Sandboxing.isOpen(sandbox)) {
          Composing.getCurrent(sandbox).each(function(menu2) {
            Highlighting.getHighlighted(menu2).fold(function() {
              highlighter(menu2);
            }, function() {
              dispatchEvent3(sandbox, menu2.element, "keydown", simulatedEvent);
            });
          });
        } else {
          var onOpenSync = function(sandbox2) {
            Composing.getCurrent(sandbox2).each(highlighter);
          };
          open(detail, mapFetch(comp), comp, sandbox, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop3);
        }
      };
      var focusBehaviours$1 = focusBehaviours(detail);
      var mapFetch = function(comp) {
        return function(tdata) {
          return tdata.map(function(data) {
            var menus = values(data.menus);
            var items = bind$3(menus, function(menu2) {
              return filter$2(menu2.items, function(item2) {
                return item2.type === "item";
              });
            });
            var repState = Representing.getState(comp);
            repState.update(map$2(items, function(item2) {
              return item2.data;
            }));
            return data;
          });
        };
      };
      var behaviours2 = [
        Focusing.config({}),
        Representing.config({
          onSetValue: detail.onSetValue,
          store: __assign({
            mode: "dataset",
            getDataKey: function(comp) {
              return get$5(comp.element);
            },
            getFallbackEntry: function(itemString) {
              return {
                value: itemString,
                meta: {}
              };
            },
            setValue: function(comp, data) {
              set$4(comp.element, detail.model.getDisplayText(data));
            }
          }, detail.initialData.map(function(d2) {
            return wrap$1("initialValue", d2);
          }).getOr({}))
        }),
        Streaming.config({
          stream: {
            mode: "throttle",
            delay: detail.responseTime,
            stopEvent: false
          },
          onStream: function(component, _simulatedEvent) {
            var sandbox = Coupling.getCoupled(component, "sandbox");
            var focusInInput = Focusing.isFocused(component);
            if (focusInInput) {
              if (get$5(component.element).length >= detail.minChars) {
                var previousValue_1 = Composing.getCurrent(sandbox).bind(function(menu2) {
                  return Highlighting.getHighlighted(menu2).map(Representing.getValue);
                });
                detail.previewing.set(true);
                var onOpenSync = function(_sandbox) {
                  Composing.getCurrent(sandbox).each(function(menu2) {
                    previousValue_1.fold(function() {
                      if (detail.model.selectsOver) {
                        Highlighting.highlightFirst(menu2);
                      }
                    }, function(pv) {
                      Highlighting.highlightBy(menu2, function(item2) {
                        var itemData = Representing.getValue(item2);
                        return itemData.value === pv.value;
                      });
                      Highlighting.getHighlighted(menu2).orThunk(function() {
                        Highlighting.highlightFirst(menu2);
                        return Optional.none();
                      });
                    });
                  });
                };
                open(detail, mapFetch(component), component, sandbox, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop3);
              }
            }
          },
          cancelEvent: typeaheadCancel()
        }),
        Keying.config({
          mode: "special",
          onDown: function(comp, simulatedEvent) {
            navigateList(comp, simulatedEvent, Highlighting.highlightFirst);
            return Optional.some(true);
          },
          onEscape: function(comp) {
            var sandbox = Coupling.getCoupled(comp, "sandbox");
            if (Sandboxing.isOpen(sandbox)) {
              Sandboxing.close(sandbox);
              return Optional.some(true);
            }
            return Optional.none();
          },
          onUp: function(comp, simulatedEvent) {
            navigateList(comp, simulatedEvent, Highlighting.highlightLast);
            return Optional.some(true);
          },
          onEnter: function(comp) {
            var sandbox = Coupling.getCoupled(comp, "sandbox");
            var sandboxIsOpen = Sandboxing.isOpen(sandbox);
            if (sandboxIsOpen && !detail.previewing.get()) {
              return Composing.getCurrent(sandbox).bind(function(menu2) {
                return Highlighting.getHighlighted(menu2);
              }).map(function(item2) {
                emitWith(comp, itemExecute(), { item: item2 });
                return true;
              });
            } else {
              var currentValue2 = Representing.getValue(comp);
              emit(comp, typeaheadCancel());
              detail.onExecute(sandbox, comp, currentValue2);
              if (sandboxIsOpen) {
                Sandboxing.close(sandbox);
              }
              return Optional.some(true);
            }
          }
        }),
        Toggling.config({
          toggleClass: detail.markers.openClass,
          aria: { mode: "expanded" }
        }),
        Coupling.config({
          others: {
            sandbox: function(hotspot) {
              return makeSandbox$1(detail, hotspot, {
                onOpen: function() {
                  return Toggling.on(hotspot);
                },
                onClose: function() {
                  return Toggling.off(hotspot);
                }
              });
            }
          }
        }),
        config("typeaheadevents", [
          runOnExecute$1(function(comp) {
            var onOpenSync = noop3;
            togglePopup(detail, mapFetch(comp), comp, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop3);
          }),
          run$1(itemExecute(), function(comp, se2) {
            var sandbox = Coupling.getCoupled(comp, "sandbox");
            setValueFromItem(detail.model, comp, se2.event.item);
            emit(comp, typeaheadCancel());
            detail.onItemExecute(comp, sandbox, se2.event.item, Representing.getValue(comp));
            Sandboxing.close(sandbox);
            setCursorAtEnd(comp);
          })
        ].concat(detail.dismissOnBlur ? [run$1(postBlur(), function(typeahead) {
          var sandbox = Coupling.getCoupled(typeahead, "sandbox");
          if (search(sandbox.element).isNone()) {
            Sandboxing.close(sandbox);
          }
        })] : []))
      ];
      return {
        uid: detail.uid,
        dom: dom(deepMerge(detail, {
          inputAttributes: {
            "role": "combobox",
            "aria-autocomplete": "list",
            "aria-haspopup": "true"
          }
        })),
        behaviours: __assign(__assign({}, focusBehaviours$1), augment(detail.typeaheadBehaviours, behaviours2)),
        eventOrder: detail.eventOrder
      };
    };
    var schema$g = constant$1([
      option("lazySink"),
      required$1("fetch"),
      defaulted("minChars", 5),
      defaulted("responseTime", 1e3),
      onHandler("onOpen"),
      defaulted("getHotspot", Optional.some),
      defaulted("getAnchorOverrides", constant$1({})),
      defaulted("layouts", Optional.none()),
      defaulted("eventOrder", {}),
      defaultedObjOf("model", {}, [
        defaulted("getDisplayText", function(itemData) {
          return itemData.meta !== void 0 && itemData.meta.text !== void 0 ? itemData.meta.text : itemData.value;
        }),
        defaulted("selectsOver", true),
        defaulted("populateFromBrowse", true)
      ]),
      onHandler("onSetValue"),
      onKeyboardHandler("onExecute"),
      onHandler("onItemExecute"),
      defaulted("inputClasses", []),
      defaulted("inputAttributes", {}),
      defaulted("inputStyles", {}),
      defaulted("matchWidth", true),
      defaulted("useMinWidth", false),
      defaulted("dismissOnBlur", true),
      markers$1(["openClass"]),
      option("initialData"),
      field("typeaheadBehaviours", [
        Focusing,
        Representing,
        Streaming,
        Keying,
        Toggling,
        Coupling
      ]),
      customField("previewing", function() {
        return Cell(true);
      })
    ].concat(schema$k()).concat(sandboxFields()));
    var parts$b = constant$1([external$1({
      schema: [tieredMenuMarkers()],
      name: "menu",
      overrides: function(detail) {
        return {
          fakeFocus: true,
          onHighlight: function(menu2, item2) {
            if (!detail.previewing.get()) {
              menu2.getSystem().getByUid(detail.uid).each(function(input2) {
                if (detail.model.populateFromBrowse) {
                  setValueFromItem(detail.model, input2, item2);
                }
              });
            } else {
              menu2.getSystem().getByUid(detail.uid).each(function(input2) {
                attemptSelectOver(detail.model, input2, item2).fold(function() {
                  return Highlighting.dehighlight(menu2, item2);
                }, function(fn3) {
                  return fn3();
                });
              });
            }
            detail.previewing.set(false);
          },
          onExecute: function(menu2, item2) {
            return menu2.getSystem().getByUid(detail.uid).toOptional().map(function(typeahead) {
              emitWith(typeahead, itemExecute(), { item: item2 });
              return true;
            });
          },
          onHover: function(menu2, item2) {
            detail.previewing.set(false);
            menu2.getSystem().getByUid(detail.uid).each(function(input2) {
              if (detail.model.populateFromBrowse) {
                setValueFromItem(detail.model, input2, item2);
              }
            });
          }
        };
      }
    })]);
    var Typeahead = composite({
      name: "Typeahead",
      configFields: schema$g(),
      partFields: parts$b(),
      factory: make$3
    });
    var wrap = function(delegate) {
      var toCached = function() {
        return wrap(delegate.toCached());
      };
      var bindFuture = function(f2) {
        return wrap(delegate.bind(function(resA) {
          return resA.fold(function(err) {
            return Future.pure(Result.error(err));
          }, function(a2) {
            return f2(a2);
          });
        }));
      };
      var bindResult = function(f2) {
        return wrap(delegate.map(function(resA) {
          return resA.bind(f2);
        }));
      };
      var mapResult = function(f2) {
        return wrap(delegate.map(function(resA) {
          return resA.map(f2);
        }));
      };
      var mapError2 = function(f2) {
        return wrap(delegate.map(function(resA) {
          return resA.mapError(f2);
        }));
      };
      var foldResult = function(whenError, whenValue) {
        return delegate.map(function(res) {
          return res.fold(whenError, whenValue);
        });
      };
      var withTimeout = function(timeout, errorThunk) {
        return wrap(Future.nu(function(callback2) {
          var timedOut = false;
          var timer = setTimeout(function() {
            timedOut = true;
            callback2(Result.error(errorThunk()));
          }, timeout);
          delegate.get(function(result) {
            if (!timedOut) {
              clearTimeout(timer);
              callback2(result);
            }
          });
        }));
      };
      return __assign(__assign({}, delegate), {
        toCached,
        bindFuture,
        bindResult,
        mapResult,
        mapError: mapError2,
        foldResult,
        withTimeout
      });
    };
    var nu$1 = function(worker) {
      return wrap(Future.nu(worker));
    };
    var value = function(value2) {
      return wrap(Future.pure(Result.value(value2)));
    };
    var error3 = function(error4) {
      return wrap(Future.pure(Result.error(error4)));
    };
    var fromResult = function(result) {
      return wrap(Future.pure(result));
    };
    var fromFuture = function(future) {
      return wrap(future.map(Result.value));
    };
    var fromPromise = function(promise) {
      return nu$1(function(completer) {
        promise.then(function(value2) {
          completer(Result.value(value2));
        }, function(error4) {
          completer(Result.error(error4));
        });
      });
    };
    var FutureResult = {
      nu: nu$1,
      wrap,
      pure: value,
      value,
      error: error3,
      fromResult,
      fromFuture,
      fromPromise
    };
    var separator$1 = { type: "separator" };
    var toMenuItem = function(target) {
      return {
        type: "menuitem",
        value: target.url,
        text: target.title,
        meta: { attach: target.attach },
        onAction: noop3
      };
    };
    var staticMenuItem = function(title, url) {
      return {
        type: "menuitem",
        value: url,
        text: title,
        meta: { attach: void 0 },
        onAction: noop3
      };
    };
    var toMenuItems = function(targets) {
      return map$2(targets, toMenuItem);
    };
    var filterLinkTargets = function(type2, targets) {
      return filter$2(targets, function(target) {
        return target.type === type2;
      });
    };
    var filteredTargets = function(type2, targets) {
      return toMenuItems(filterLinkTargets(type2, targets));
    };
    var headerTargets = function(linkInfo) {
      return filteredTargets("header", linkInfo.targets);
    };
    var anchorTargets = function(linkInfo) {
      return filteredTargets("anchor", linkInfo.targets);
    };
    var anchorTargetTop = function(linkInfo) {
      return Optional.from(linkInfo.anchorTop).map(function(url) {
        return staticMenuItem("<top>", url);
      }).toArray();
    };
    var anchorTargetBottom = function(linkInfo) {
      return Optional.from(linkInfo.anchorBottom).map(function(url) {
        return staticMenuItem("<bottom>", url);
      }).toArray();
    };
    var historyTargets = function(history2) {
      return map$2(history2, function(url) {
        return staticMenuItem(url, url);
      });
    };
    var joinMenuLists = function(items) {
      return foldl(items, function(a2, b3) {
        var bothEmpty = a2.length === 0 || b3.length === 0;
        return bothEmpty ? a2.concat(b3) : a2.concat(separator$1, b3);
      }, []);
    };
    var filterByQuery = function(term, menuItems) {
      var lowerCaseTerm = term.toLowerCase();
      return filter$2(menuItems, function(item2) {
        var text2 = item2.meta !== void 0 && item2.meta.text !== void 0 ? item2.meta.text : item2.text;
        return contains$1(text2.toLowerCase(), lowerCaseTerm) || contains$1(item2.value.toLowerCase(), lowerCaseTerm);
      });
    };
    var getItems = function(fileType, input2, urlBackstage) {
      var urlInputValue = Representing.getValue(input2);
      var term = urlInputValue.meta.text !== void 0 ? urlInputValue.meta.text : urlInputValue.value;
      var info = urlBackstage.getLinkInformation();
      return info.fold(function() {
        return [];
      }, function(linkInfo) {
        var history2 = filterByQuery(term, historyTargets(urlBackstage.getHistory(fileType)));
        return fileType === "file" ? joinMenuLists([
          history2,
          filterByQuery(term, headerTargets(linkInfo)),
          filterByQuery(term, flatten([
            anchorTargetTop(linkInfo),
            anchorTargets(linkInfo),
            anchorTargetBottom(linkInfo)
          ]))
        ]) : history2;
      });
    };
    var errorId = generate$6("aria-invalid");
    var renderUrlInput = function(spec, backstage, urlBackstage) {
      var _a2;
      var providersBackstage = backstage.shared.providers;
      var updateHistory = function(component) {
        var urlEntry = Representing.getValue(component);
        urlBackstage.addToHistory(urlEntry.value, spec.filetype);
      };
      var pField = FormField.parts.field({
        factory: Typeahead,
        dismissOnBlur: true,
        inputClasses: ["tox-textfield"],
        sandboxClasses: ["tox-dialog__popups"],
        inputAttributes: {
          "aria-errormessage": errorId,
          "type": "url"
        },
        minChars: 0,
        responseTime: 0,
        fetch: function(input2) {
          var items = getItems(spec.filetype, input2, urlBackstage);
          var tdata = build(items, ItemResponse$1.BUBBLE_TO_SANDBOX, backstage, false);
          return Future.pure(tdata);
        },
        getHotspot: function(comp) {
          return memUrlBox.getOpt(comp);
        },
        onSetValue: function(comp, _newValue) {
          if (comp.hasConfigured(Invalidating)) {
            Invalidating.run(comp).get(noop3);
          }
        },
        typeaheadBehaviours: derive$1(flatten([
          urlBackstage.getValidationHandler().map(function(handler) {
            return Invalidating.config({
              getRoot: function(comp) {
                return parent(comp.element);
              },
              invalidClass: "tox-control-wrap--status-invalid",
              notify: {
                onInvalid: function(comp, err) {
                  memInvalidIcon.getOpt(comp).each(function(invalidComp) {
                    set$8(invalidComp.element, "title", providersBackstage.translate(err));
                  });
                }
              },
              validator: {
                validate: function(input2) {
                  var urlEntry = Representing.getValue(input2);
                  return FutureResult.nu(function(completer) {
                    handler({
                      type: spec.filetype,
                      url: urlEntry.value
                    }, function(validation) {
                      if (validation.status === "invalid") {
                        var err = Result.error(validation.message);
                        completer(err);
                      } else {
                        var val = Result.value(validation.message);
                        completer(val);
                      }
                    });
                  });
                },
                validateOnLoad: false
              }
            });
          }).toArray(),
          [
            Disabling.config({
              disabled: function() {
                return spec.disabled || providersBackstage.isDisabled();
              }
            }),
            Tabstopping.config({}),
            config("urlinput-events", flatten([
              spec.filetype === "file" ? [run$1(input(), function(comp) {
                emitWith(comp, formChangeEvent, { name: spec.name });
              })] : [],
              [
                run$1(change(), function(comp) {
                  emitWith(comp, formChangeEvent, { name: spec.name });
                  updateHistory(comp);
                }),
                run$1(postPaste(), function(comp) {
                  emitWith(comp, formChangeEvent, { name: spec.name });
                  updateHistory(comp);
                })
              ]
            ]))
          ]
        ])),
        eventOrder: (_a2 = {}, _a2[input()] = [
          "streaming",
          "urlinput-events",
          "invalidating"
        ], _a2),
        model: {
          getDisplayText: function(itemData) {
            return itemData.value;
          },
          selectsOver: false,
          populateFromBrowse: false
        },
        markers: { openClass: "tox-textfield--popup-open" },
        lazySink: backstage.shared.getSink,
        parts: { menu: part(false, 1, "normal") },
        onExecute: function(_menu, component, _entry) {
          emitWith(component, formSubmitEvent, {});
        },
        onItemExecute: function(typeahead, _sandbox, _item, _value) {
          updateHistory(typeahead);
          emitWith(typeahead, formChangeEvent, { name: spec.name });
        }
      });
      var pLabel = spec.label.map(function(label) {
        return renderLabel$2(label, providersBackstage);
      });
      var makeIcon = function(name2, errId, icon, label) {
        if (icon === void 0) {
          icon = name2;
        }
        if (label === void 0) {
          label = name2;
        }
        return render$3(icon, {
          tag: "div",
          classes: [
            "tox-icon",
            "tox-control-wrap__status-icon-" + name2
          ],
          attributes: __assign({
            "title": providersBackstage.translate(label),
            "aria-live": "polite"
          }, errId.fold(function() {
            return {};
          }, function(id2) {
            return { id: id2 };
          }))
        }, providersBackstage.icons);
      };
      var memInvalidIcon = record(makeIcon("invalid", Optional.some(errorId), "warning"));
      var memStatus = record({
        dom: {
          tag: "div",
          classes: ["tox-control-wrap__status-icon-wrap"]
        },
        components: [memInvalidIcon.asSpec()]
      });
      var optUrlPicker = urlBackstage.getUrlPicker(spec.filetype);
      var browseUrlEvent = generate$6("browser.url.event");
      var memUrlBox = record({
        dom: {
          tag: "div",
          classes: ["tox-control-wrap"]
        },
        components: [
          pField,
          memStatus.asSpec()
        ],
        behaviours: derive$1([Disabling.config({
          disabled: function() {
            return spec.disabled || providersBackstage.isDisabled();
          }
        })])
      });
      var memUrlPickerButton = record(renderButton({
        name: spec.name,
        icon: Optional.some("browse"),
        text: spec.label.getOr(""),
        disabled: spec.disabled,
        primary: false,
        borderless: true
      }, function(component) {
        return emit(component, browseUrlEvent);
      }, providersBackstage, [], ["tox-browse-url"]));
      var controlHWrapper = function() {
        return {
          dom: {
            tag: "div",
            classes: ["tox-form__controls-h-stack"]
          },
          components: flatten([
            [memUrlBox.asSpec()],
            optUrlPicker.map(function() {
              return memUrlPickerButton.asSpec();
            }).toArray()
          ])
        };
      };
      var openUrlPicker = function(comp) {
        Composing.getCurrent(comp).each(function(field2) {
          var componentData = Representing.getValue(field2);
          var urlData = __assign({ fieldname: spec.name }, componentData);
          optUrlPicker.each(function(picker) {
            picker(urlData).get(function(chosenData) {
              Representing.setValue(field2, chosenData);
              emitWith(comp, formChangeEvent, { name: spec.name });
            });
          });
        });
      };
      return FormField.sketch({
        dom: renderFormFieldDom(),
        components: pLabel.toArray().concat([controlHWrapper()]),
        fieldBehaviours: derive$1([
          Disabling.config({
            disabled: function() {
              return spec.disabled || providersBackstage.isDisabled();
            },
            onDisabled: function(comp) {
              FormField.getField(comp).each(Disabling.disable);
              memUrlPickerButton.getOpt(comp).each(Disabling.disable);
            },
            onEnabled: function(comp) {
              FormField.getField(comp).each(Disabling.enable);
              memUrlPickerButton.getOpt(comp).each(Disabling.enable);
            }
          }),
          receivingConfig(),
          config("url-input-events", [run$1(browseUrlEvent, openUrlPicker)])
        ])
      });
    };
    var renderAlertBanner = function(spec, providersBackstage) {
      return Container.sketch({
        dom: {
          tag: "div",
          attributes: { role: "alert" },
          classes: [
            "tox-notification",
            "tox-notification--in",
            "tox-notification--" + spec.level
          ]
        },
        components: [
          {
            dom: {
              tag: "div",
              classes: ["tox-notification__icon"]
            },
            components: [Button2.sketch({
              dom: {
                tag: "button",
                classes: [
                  "tox-button",
                  "tox-button--naked",
                  "tox-button--icon"
                ],
                innerHtml: get$1(spec.icon, providersBackstage.icons),
                attributes: { title: providersBackstage.translate(spec.iconTooltip) }
              },
              action: function(comp) {
                emitWith(comp, formActionEvent, {
                  name: "alert-banner",
                  value: spec.url
                });
              },
              buttonBehaviours: derive$1([addFocusableBehaviour()])
            })]
          },
          {
            dom: {
              tag: "div",
              classes: ["tox-notification__body"],
              innerHtml: providersBackstage.translate(spec.text)
            }
          }
        ]
      });
    };
    var renderCheckbox = function(spec, providerBackstage) {
      var repBehaviour = Representing.config({
        store: {
          mode: "manual",
          getValue: function(comp) {
            var el = comp.element.dom;
            return el.checked;
          },
          setValue: function(comp, value2) {
            var el = comp.element.dom;
            el.checked = value2;
          }
        }
      });
      var toggleCheckboxHandler = function(comp) {
        comp.element.dom.click();
        return Optional.some(true);
      };
      var pField = FormField.parts.field({
        factory: { sketch: identity$1 },
        dom: {
          tag: "input",
          classes: ["tox-checkbox__input"],
          attributes: { type: "checkbox" }
        },
        behaviours: derive$1([
          ComposingConfigs.self(),
          Disabling.config({
            disabled: function() {
              return spec.disabled || providerBackstage.isDisabled();
            }
          }),
          Tabstopping.config({}),
          Focusing.config({}),
          repBehaviour,
          Keying.config({
            mode: "special",
            onEnter: toggleCheckboxHandler,
            onSpace: toggleCheckboxHandler,
            stopSpaceKeyup: true
          }),
          config("checkbox-events", [run$1(change(), function(component, _2) {
            emitWith(component, formChangeEvent, { name: spec.name });
          })])
        ])
      });
      var pLabel = FormField.parts.label({
        dom: {
          tag: "span",
          classes: ["tox-checkbox__label"],
          innerHtml: providerBackstage.translate(spec.label)
        },
        behaviours: derive$1([Unselecting.config({})])
      });
      var makeIcon = function(className) {
        var iconName = className === "checked" ? "selected" : "unselected";
        return render$3(iconName, {
          tag: "span",
          classes: [
            "tox-icon",
            "tox-checkbox-icon__" + className
          ]
        }, providerBackstage.icons);
      };
      var memIcons = record({
        dom: {
          tag: "div",
          classes: ["tox-checkbox__icons"]
        },
        components: [
          makeIcon("checked"),
          makeIcon("unchecked")
        ]
      });
      return FormField.sketch({
        dom: {
          tag: "label",
          classes: ["tox-checkbox"]
        },
        components: [
          pField,
          memIcons.asSpec(),
          pLabel
        ],
        fieldBehaviours: derive$1([
          Disabling.config({
            disabled: function() {
              return spec.disabled || providerBackstage.isDisabled();
            },
            disableClass: "tox-checkbox--disabled",
            onDisabled: function(comp) {
              FormField.getField(comp).each(Disabling.disable);
            },
            onEnabled: function(comp) {
              FormField.getField(comp).each(Disabling.enable);
            }
          }),
          receivingConfig()
        ])
      });
    };
    var renderHtmlPanel = function(spec) {
      if (spec.presets === "presentation") {
        return Container.sketch({
          dom: {
            tag: "div",
            classes: ["tox-form__group"],
            innerHtml: spec.html
          }
        });
      } else {
        return Container.sketch({
          dom: {
            tag: "div",
            classes: ["tox-form__group"],
            innerHtml: spec.html,
            attributes: { role: "document" }
          },
          containerBehaviours: derive$1([
            Tabstopping.config({}),
            Focusing.config({})
          ])
        });
      }
    };
    var make$2 = function(render2) {
      return function(parts2, spec, backstage) {
        return get$e(spec, "name").fold(function() {
          return render2(spec, backstage);
        }, function(fieldName) {
          return parts2.field(fieldName, render2(spec, backstage));
        });
      };
    };
    var makeIframe = function(render2) {
      return function(parts2, spec, backstage) {
        var iframeSpec = deepMerge(spec, { source: "dynamic" });
        return make$2(render2)(parts2, iframeSpec, backstage);
      };
    };
    var factories = {
      bar: make$2(function(spec, backstage) {
        return renderBar(spec, backstage.shared);
      }),
      collection: make$2(function(spec, backstage) {
        return renderCollection(spec, backstage.shared.providers);
      }),
      alertbanner: make$2(function(spec, backstage) {
        return renderAlertBanner(spec, backstage.shared.providers);
      }),
      input: make$2(function(spec, backstage) {
        return renderInput(spec, backstage.shared.providers);
      }),
      textarea: make$2(function(spec, backstage) {
        return renderTextarea(spec, backstage.shared.providers);
      }),
      label: make$2(function(spec, backstage) {
        return renderLabel(spec, backstage.shared);
      }),
      iframe: makeIframe(function(spec, backstage) {
        return renderIFrame(spec, backstage.shared.providers);
      }),
      button: make$2(function(spec, backstage) {
        return renderDialogButton(spec, backstage.shared.providers);
      }),
      checkbox: make$2(function(spec, backstage) {
        return renderCheckbox(spec, backstage.shared.providers);
      }),
      colorinput: make$2(function(spec, backstage) {
        return renderColorInput(spec, backstage.shared, backstage.colorinput);
      }),
      colorpicker: make$2(renderColorPicker),
      dropzone: make$2(function(spec, backstage) {
        return renderDropZone(spec, backstage.shared.providers);
      }),
      grid: make$2(function(spec, backstage) {
        return renderGrid(spec, backstage.shared);
      }),
      listbox: make$2(function(spec, backstage) {
        return renderListBox(spec, backstage);
      }),
      selectbox: make$2(function(spec, backstage) {
        return renderSelectBox(spec, backstage.shared.providers);
      }),
      sizeinput: make$2(function(spec, backstage) {
        return renderSizeInput(spec, backstage.shared.providers);
      }),
      urlinput: make$2(function(spec, backstage) {
        return renderUrlInput(spec, backstage, backstage.urlinput);
      }),
      customeditor: make$2(renderCustomEditor),
      htmlpanel: make$2(renderHtmlPanel),
      imagetools: make$2(function(spec, backstage) {
        return renderImageTools(spec, backstage.shared.providers);
      }),
      table: make$2(function(spec, backstage) {
        return renderTable(spec, backstage.shared.providers);
      }),
      panel: make$2(function(spec, backstage) {
        return renderPanel(spec, backstage);
      })
    };
    var noFormParts = {
      field: function(_name, spec) {
        return spec;
      }
    };
    var interpretInForm = function(parts2, spec, oldBackstage) {
      var newBackstage = deepMerge(oldBackstage, {
        shared: {
          interpreter: function(childSpec) {
            return interpretParts(parts2, childSpec, newBackstage);
          }
        }
      });
      return interpretParts(parts2, spec, newBackstage);
    };
    var interpretParts = function(parts2, spec, backstage) {
      return get$e(factories, spec.type).fold(function() {
        console.error('Unknown factory type "' + spec.type + '", defaulting to container: ', spec);
        return spec;
      }, function(factory2) {
        return factory2(parts2, spec, backstage);
      });
    };
    var interpretWithoutForm = function(spec, backstage) {
      var parts2 = noFormParts;
      return interpretParts(parts2, spec, backstage);
    };
    var bubbleAlignments$2 = {
      valignCentre: [],
      alignCentre: [],
      alignLeft: [],
      alignRight: [],
      right: [],
      left: [],
      bottom: [],
      top: []
    };
    var getInlineDialogAnchor = function(contentAreaElement, lazyAnchorbar, lazyUseEditableAreaAnchor) {
      var bubbleSize2 = 12;
      var overrides2 = { maxHeightFunction: expandable$1() };
      var editableAreaAnchor = function() {
        return {
          type: "node",
          root: getContentContainer(contentAreaElement()),
          node: Optional.from(contentAreaElement()),
          bubble: nu$5(bubbleSize2, bubbleSize2, bubbleAlignments$2),
          layouts: {
            onRtl: function() {
              return [northeast];
            },
            onLtr: function() {
              return [northwest];
            }
          },
          overrides: overrides2
        };
      };
      var standardAnchor = function() {
        return {
          type: "hotspot",
          hotspot: lazyAnchorbar(),
          bubble: nu$5(-bubbleSize2, bubbleSize2, bubbleAlignments$2),
          layouts: {
            onRtl: function() {
              return [southeast$2];
            },
            onLtr: function() {
              return [southwest$2];
            }
          },
          overrides: overrides2
        };
      };
      return function() {
        return lazyUseEditableAreaAnchor() ? editableAreaAnchor() : standardAnchor();
      };
    };
    var getBannerAnchor = function(contentAreaElement, lazyAnchorbar, lazyUseEditableAreaAnchor) {
      var editableAreaAnchor = function() {
        return {
          type: "node",
          root: getContentContainer(contentAreaElement()),
          node: Optional.from(contentAreaElement()),
          layouts: {
            onRtl: function() {
              return [north];
            },
            onLtr: function() {
              return [north];
            }
          }
        };
      };
      var standardAnchor = function() {
        return {
          type: "hotspot",
          hotspot: lazyAnchorbar(),
          layouts: {
            onRtl: function() {
              return [south$2];
            },
            onLtr: function() {
              return [south$2];
            }
          }
        };
      };
      return function() {
        return lazyUseEditableAreaAnchor() ? editableAreaAnchor() : standardAnchor();
      };
    };
    var getCursorAnchor = function(editor, bodyElement) {
      return function() {
        return {
          type: "selection",
          root: bodyElement(),
          getSelection: function() {
            var rng = editor.selection.getRng();
            return Optional.some(SimSelection.range(SugarElement.fromDom(rng.startContainer), rng.startOffset, SugarElement.fromDom(rng.endContainer), rng.endOffset));
          }
        };
      };
    };
    var getNodeAnchor$1 = function(bodyElement) {
      return function(element2) {
        return {
          type: "node",
          root: bodyElement(),
          node: element2
        };
      };
    };
    var getAnchors = function(editor, lazyAnchorbar, isToolbarTop) {
      var useFixedToolbarContainer = useFixedContainer(editor);
      var bodyElement = function() {
        return SugarElement.fromDom(editor.getBody());
      };
      var contentAreaElement = function() {
        return SugarElement.fromDom(editor.getContentAreaContainer());
      };
      var lazyUseEditableAreaAnchor = function() {
        return useFixedToolbarContainer || !isToolbarTop();
      };
      return {
        inlineDialog: getInlineDialogAnchor(contentAreaElement, lazyAnchorbar, lazyUseEditableAreaAnchor),
        banner: getBannerAnchor(contentAreaElement, lazyAnchorbar, lazyUseEditableAreaAnchor),
        cursor: getCursorAnchor(editor, bodyElement),
        node: getNodeAnchor$1(bodyElement)
      };
    };
    var colorPicker = function(editor) {
      return function(callback2, value2) {
        var dialog = colorPickerDialog(editor);
        dialog(callback2, value2);
      };
    };
    var hasCustomColors = function(editor) {
      return function() {
        return hasCustomColors$1(editor);
      };
    };
    var getColors = function(editor) {
      return function() {
        return getColors$2(editor);
      };
    };
    var getColorCols = function(editor) {
      return function() {
        return getColorCols$1(editor);
      };
    };
    var ColorInputBackstage = function(editor) {
      return {
        colorPicker: colorPicker(editor),
        hasCustomColors: hasCustomColors(editor),
        getColors: getColors(editor),
        getColorCols: getColorCols(editor)
      };
    };
    var isDraggableModal = function(editor) {
      return function() {
        return isDraggableModal$1(editor);
      };
    };
    var DialogBackstage = function(editor) {
      return { isDraggableModal: isDraggableModal(editor) };
    };
    var HeaderBackstage = function(editor) {
      var mode = Cell(isToolbarLocationBottom(editor) ? "bottom" : "top");
      return {
        isPositionedAtTop: function() {
          return mode.get() === "top";
        },
        getDockingMode: mode.get,
        setDockingMode: mode.set
      };
    };
    var defaultStyleFormats = [
      {
        title: "Headings",
        items: [
          {
            title: "Heading 1",
            format: "h1"
          },
          {
            title: "Heading 2",
            format: "h2"
          },
          {
            title: "Heading 3",
            format: "h3"
          },
          {
            title: "Heading 4",
            format: "h4"
          },
          {
            title: "Heading 5",
            format: "h5"
          },
          {
            title: "Heading 6",
            format: "h6"
          }
        ]
      },
      {
        title: "Inline",
        items: [
          {
            title: "Bold",
            format: "bold"
          },
          {
            title: "Italic",
            format: "italic"
          },
          {
            title: "Underline",
            format: "underline"
          },
          {
            title: "Strikethrough",
            format: "strikethrough"
          },
          {
            title: "Superscript",
            format: "superscript"
          },
          {
            title: "Subscript",
            format: "subscript"
          },
          {
            title: "Code",
            format: "code"
          }
        ]
      },
      {
        title: "Blocks",
        items: [
          {
            title: "Paragraph",
            format: "p"
          },
          {
            title: "Blockquote",
            format: "blockquote"
          },
          {
            title: "Div",
            format: "div"
          },
          {
            title: "Pre",
            format: "pre"
          }
        ]
      },
      {
        title: "Align",
        items: [
          {
            title: "Left",
            format: "alignleft"
          },
          {
            title: "Center",
            format: "aligncenter"
          },
          {
            title: "Right",
            format: "alignright"
          },
          {
            title: "Justify",
            format: "alignjustify"
          }
        ]
      }
    ];
    var isNestedFormat = function(format3) {
      return has$2(format3, "items");
    };
    var isBlockFormat = function(format3) {
      return has$2(format3, "block");
    };
    var isInlineFormat = function(format3) {
      return has$2(format3, "inline");
    };
    var isSelectorFormat = function(format3) {
      return has$2(format3, "selector");
    };
    var mapFormats = function(userFormats) {
      return foldl(userFormats, function(acc, fmt) {
        if (isNestedFormat(fmt)) {
          var result = mapFormats(fmt.items);
          return {
            customFormats: acc.customFormats.concat(result.customFormats),
            formats: acc.formats.concat([{
              title: fmt.title,
              items: result.formats
            }])
          };
        } else if (isInlineFormat(fmt) || isBlockFormat(fmt) || isSelectorFormat(fmt)) {
          var formatName = isString(fmt.name) ? fmt.name : fmt.title.toLowerCase();
          var formatNameWithPrefix = "custom-" + formatName;
          return {
            customFormats: acc.customFormats.concat([{
              name: formatNameWithPrefix,
              format: fmt
            }]),
            formats: acc.formats.concat([{
              title: fmt.title,
              format: formatNameWithPrefix,
              icon: fmt.icon
            }])
          };
        } else {
          return __assign(__assign({}, acc), { formats: acc.formats.concat(fmt) });
        }
      }, {
        customFormats: [],
        formats: []
      });
    };
    var registerCustomFormats = function(editor, userFormats) {
      var result = mapFormats(userFormats);
      var registerFormats = function(customFormats) {
        each$1(customFormats, function(fmt) {
          if (!editor.formatter.has(fmt.name)) {
            editor.formatter.register(fmt.name, fmt.format);
          }
        });
      };
      if (editor.formatter) {
        registerFormats(result.customFormats);
      } else {
        editor.on("init", function() {
          registerFormats(result.customFormats);
        });
      }
      return result.formats;
    };
    var getStyleFormats = function(editor) {
      return getUserStyleFormats(editor).map(function(userFormats) {
        var registeredUserFormats = registerCustomFormats(editor, userFormats);
        return isMergeStyleFormats(editor) ? defaultStyleFormats.concat(registeredUserFormats) : registeredUserFormats;
      }).getOr(defaultStyleFormats);
    };
    var processBasic = function(item2, isSelectedFor, getPreviewFor) {
      var formatterSpec = {
        type: "formatter",
        isSelected: isSelectedFor(item2.format),
        getStylePreview: getPreviewFor(item2.format)
      };
      return deepMerge(item2, formatterSpec);
    };
    var register$8 = function(editor, formats, isSelectedFor, getPreviewFor) {
      var enrichSupported = function(item2) {
        return processBasic(item2, isSelectedFor, getPreviewFor);
      };
      var enrichMenu = function(item2) {
        var submenuSpec = { type: "submenu" };
        return deepMerge(item2, submenuSpec);
      };
      var enrichCustom = function(item2) {
        var formatName = isString(item2.name) ? item2.name : generate$6(item2.title);
        var formatNameWithPrefix = "custom-" + formatName;
        var customSpec = {
          type: "formatter",
          format: formatNameWithPrefix,
          isSelected: isSelectedFor(formatNameWithPrefix),
          getStylePreview: getPreviewFor(formatNameWithPrefix)
        };
        var newItem = deepMerge(item2, customSpec);
        editor.formatter.register(formatName, newItem);
        return newItem;
      };
      var doEnrich = function(items) {
        return map$2(items, function(item2) {
          var keys$1 = keys(item2);
          if (hasNonNullableKey(item2, "items")) {
            var newItems = doEnrich(item2.items);
            return deepMerge(enrichMenu(item2), { getStyleItems: constant$1(newItems) });
          } else if (hasNonNullableKey(item2, "format")) {
            return enrichSupported(item2);
          } else if (keys$1.length === 1 && contains$2(keys$1, "title")) {
            return deepMerge(item2, { type: "separator" });
          } else {
            return enrichCustom(item2);
          }
        });
      };
      return doEnrich(formats);
    };
    var init$8 = function(editor) {
      var isSelectedFor = function(format3) {
        return function() {
          return editor.formatter.match(format3);
        };
      };
      var getPreviewFor = function(format3) {
        return function() {
          var fmt = editor.formatter.get(format3);
          return fmt !== void 0 ? Optional.some({
            tag: fmt.length > 0 ? fmt[0].inline || fmt[0].block || "div" : "div",
            styles: editor.dom.parseStyle(editor.formatter.getCssText(format3))
          }) : Optional.none();
        };
      };
      var flatten2 = function(fmt) {
        var subs2 = fmt.items;
        return subs2 !== void 0 && subs2.length > 0 ? bind$3(subs2, flatten2) : [fmt.format];
      };
      var settingsFormats = Cell([]);
      var settingsFlattenedFormats = Cell([]);
      var eventsFormats = Cell([]);
      var eventsFlattenedFormats = Cell([]);
      var replaceSettings = Cell(false);
      editor.on("PreInit", function(_e2) {
        var formats = getStyleFormats(editor);
        var enriched = register$8(editor, formats, isSelectedFor, getPreviewFor);
        settingsFormats.set(enriched);
        settingsFlattenedFormats.set(bind$3(enriched, flatten2));
      });
      editor.on("addStyleModifications", function(e2) {
        var modifications = register$8(editor, e2.items, isSelectedFor, getPreviewFor);
        eventsFormats.set(modifications);
        replaceSettings.set(e2.replace);
        eventsFlattenedFormats.set(bind$3(modifications, flatten2));
      });
      var getData2 = function() {
        var fromSettings = replaceSettings.get() ? [] : settingsFormats.get();
        var fromEvents = eventsFormats.get();
        return fromSettings.concat(fromEvents);
      };
      var getFlattenedKeys = function() {
        var fromSettings = replaceSettings.get() ? [] : settingsFlattenedFormats.get();
        var fromEvents = eventsFlattenedFormats.get();
        return fromSettings.concat(fromEvents);
      };
      return {
        getData: getData2,
        getFlattenedKeys
      };
    };
    var isElement3 = function(node) {
      return isNonNullable(node) && node.nodeType === 1;
    };
    var trim = global$5.trim;
    var hasContentEditableState = function(value2) {
      return function(node) {
        if (isElement3(node)) {
          if (node.contentEditable === value2) {
            return true;
          }
          if (node.getAttribute("data-mce-contenteditable") === value2) {
            return true;
          }
        }
        return false;
      };
    };
    var isContentEditableTrue = hasContentEditableState("true");
    var isContentEditableFalse = hasContentEditableState("false");
    var create = function(type2, title, url, level, attach2) {
      return {
        type: type2,
        title,
        url,
        level,
        attach: attach2
      };
    };
    var isChildOfContentEditableTrue = function(node) {
      while (node = node.parentNode) {
        var value2 = node.contentEditable;
        if (value2 && value2 !== "inherit") {
          return isContentEditableTrue(node);
        }
      }
      return false;
    };
    var select = function(selector, root) {
      return map$2(descendants(SugarElement.fromDom(root), selector), function(element2) {
        return element2.dom;
      });
    };
    var getElementText = function(elm) {
      return elm.innerText || elm.textContent;
    };
    var getOrGenerateId = function(elm) {
      return elm.id ? elm.id : generate$6("h");
    };
    var isAnchor = function(elm) {
      return elm && elm.nodeName === "A" && (elm.id || elm.name) !== void 0;
    };
    var isValidAnchor = function(elm) {
      return isAnchor(elm) && isEditable(elm);
    };
    var isHeader = function(elm) {
      return elm && /^(H[1-6])$/.test(elm.nodeName);
    };
    var isEditable = function(elm) {
      return isChildOfContentEditableTrue(elm) && !isContentEditableFalse(elm);
    };
    var isValidHeader = function(elm) {
      return isHeader(elm) && isEditable(elm);
    };
    var getLevel = function(elm) {
      return isHeader(elm) ? parseInt(elm.nodeName.substr(1), 10) : 0;
    };
    var headerTarget = function(elm) {
      var headerId = getOrGenerateId(elm);
      var attach2 = function() {
        elm.id = headerId;
      };
      return create("header", getElementText(elm), "#" + headerId, getLevel(elm), attach2);
    };
    var anchorTarget = function(elm) {
      var anchorId = elm.id || elm.name;
      var anchorText = getElementText(elm);
      return create("anchor", anchorText ? anchorText : "#" + anchorId, "#" + anchorId, 0, noop3);
    };
    var getHeaderTargets = function(elms) {
      return map$2(filter$2(elms, isValidHeader), headerTarget);
    };
    var getAnchorTargets = function(elms) {
      return map$2(filter$2(elms, isValidAnchor), anchorTarget);
    };
    var getTargetElements = function(elm) {
      var elms = select("h1,h2,h3,h4,h5,h6,a:not([href])", elm);
      return elms;
    };
    var hasTitle = function(target) {
      return trim(target.title).length > 0;
    };
    var find = function(elm) {
      var elms = getTargetElements(elm);
      return filter$2(getHeaderTargets(elms).concat(getAnchorTargets(elms)), hasTitle);
    };
    var LinkTargets = { find };
    var STORAGE_KEY = "tinymce-url-history";
    var HISTORY_LENGTH = 5;
    var isHttpUrl = function(url) {
      return isString(url) && /^https?/.test(url);
    };
    var isArrayOfUrl = function(a2) {
      return isArray2(a2) && a2.length <= HISTORY_LENGTH && forall(a2, isHttpUrl);
    };
    var isRecordOfUrlArray = function(r3) {
      return isObject2(r3) && find$4(r3, function(value2) {
        return !isArrayOfUrl(value2);
      }).isNone();
    };
    var getAllHistory = function() {
      var unparsedHistory = global$8.getItem(STORAGE_KEY);
      if (unparsedHistory === null) {
        return {};
      }
      var history2;
      try {
        history2 = JSON.parse(unparsedHistory);
      } catch (e2) {
        if (e2 instanceof SyntaxError) {
          console.log("Local storage " + STORAGE_KEY + " was not valid JSON", e2);
          return {};
        }
        throw e2;
      }
      if (!isRecordOfUrlArray(history2)) {
        console.log("Local storage " + STORAGE_KEY + " was not valid format", history2);
        return {};
      }
      return history2;
    };
    var setAllHistory = function(history2) {
      if (!isRecordOfUrlArray(history2)) {
        throw new Error("Bad format for history:\n" + JSON.stringify(history2));
      }
      global$8.setItem(STORAGE_KEY, JSON.stringify(history2));
    };
    var getHistory = function(fileType) {
      var history2 = getAllHistory();
      return get$e(history2, fileType).getOr([]);
    };
    var addToHistory = function(url, fileType) {
      if (!isHttpUrl(url)) {
        return;
      }
      var history2 = getAllHistory();
      var items = get$e(history2, fileType).getOr([]);
      var itemsWithoutUrl = filter$2(items, function(item2) {
        return item2 !== url;
      });
      history2[fileType] = [url].concat(itemsWithoutUrl).slice(0, HISTORY_LENGTH);
      setAllHistory(history2);
    };
    var isTruthy = function(value2) {
      return !!value2;
    };
    var makeMap = function(value2) {
      return map$12(global$5.makeMap(value2, /[, ]/), isTruthy);
    };
    var getPicker = function(editor) {
      return Optional.from(getFilePickerCallback(editor)).filter(isFunction2);
    };
    var getPickerTypes = function(editor) {
      var optFileTypes = Optional.some(getFilePickerTypes(editor)).filter(isTruthy);
      var optLegacyTypes = Optional.some(getFileBrowserCallbackTypes(editor)).filter(isTruthy);
      var optTypes = optFileTypes.or(optLegacyTypes).map(makeMap);
      return getPicker(editor).fold(never, function(_picker) {
        return optTypes.fold(always, function(types2) {
          return keys(types2).length > 0 ? types2 : false;
        });
      });
    };
    var getPickerSetting = function(editor, filetype) {
      var pickerTypes = getPickerTypes(editor);
      if (isBoolean(pickerTypes)) {
        return pickerTypes ? getPicker(editor) : Optional.none();
      } else {
        return pickerTypes[filetype] ? getPicker(editor) : Optional.none();
      }
    };
    var getUrlPicker = function(editor, filetype) {
      return getPickerSetting(editor, filetype).map(function(picker) {
        return function(entry) {
          return Future.nu(function(completer) {
            var handler = function(value2, meta2) {
              if (!isString(value2)) {
                throw new Error("Expected value to be string");
              }
              if (meta2 !== void 0 && !isObject2(meta2)) {
                throw new Error("Expected meta to be a object");
              }
              var r3 = {
                value: value2,
                meta: meta2
              };
              completer(r3);
            };
            var meta = __assign({
              filetype,
              fieldname: entry.fieldname
            }, Optional.from(entry.meta).getOr({}));
            picker.call(editor, handler, entry.value, meta);
          });
        };
      });
    };
    var getTextSetting = function(value2) {
      return Optional.from(value2).filter(isString).getOrUndefined();
    };
    var getLinkInformation = function(editor) {
      if (noTypeaheadUrls(editor)) {
        return Optional.none();
      }
      return Optional.some({
        targets: LinkTargets.find(editor.getBody()),
        anchorTop: getTextSetting(getAnchorTop(editor)),
        anchorBottom: getTextSetting(getAnchorBottom(editor))
      });
    };
    var getValidationHandler = function(editor) {
      return Optional.from(getFilePickerValidatorHandler(editor));
    };
    var UrlInputBackstage = function(editor) {
      return {
        getHistory,
        addToHistory,
        getLinkInformation: function() {
          return getLinkInformation(editor);
        },
        getValidationHandler: function() {
          return getValidationHandler(editor);
        },
        getUrlPicker: function(filetype) {
          return getUrlPicker(editor, filetype);
        }
      };
    };
    var init$7 = function(sink, editor, lazyAnchorbar) {
      var contextMenuState = Cell(false);
      var toolbar = HeaderBackstage(editor);
      var backstage = {
        shared: {
          providers: {
            icons: function() {
              return editor.ui.registry.getAll().icons;
            },
            menuItems: function() {
              return editor.ui.registry.getAll().menuItems;
            },
            translate: global$e.translate,
            isDisabled: function() {
              return editor.mode.isReadOnly() || editor.ui.isDisabled();
            },
            getSetting: editor.getParam.bind(editor)
          },
          interpreter: function(s2) {
            return interpretWithoutForm(s2, backstage);
          },
          anchors: getAnchors(editor, lazyAnchorbar, toolbar.isPositionedAtTop),
          header: toolbar,
          getSink: function() {
            return Result.value(sink);
          }
        },
        urlinput: UrlInputBackstage(editor),
        styleselect: init$8(editor),
        colorinput: ColorInputBackstage(editor),
        dialog: DialogBackstage(editor),
        isContextMenuOpen: function() {
          return contextMenuState.get();
        },
        setContextMenuState: function(state) {
          return contextMenuState.set(state);
        }
      };
      return backstage;
    };
    var setup$b = function(editor, mothership, uiMothership) {
      var broadcastEvent = function(name2, evt) {
        each$1([
          mothership,
          uiMothership
        ], function(ship) {
          ship.broadcastEvent(name2, evt);
        });
      };
      var broadcastOn = function(channel, message) {
        each$1([
          mothership,
          uiMothership
        ], function(ship) {
          ship.broadcastOn([channel], message);
        });
      };
      var fireDismissPopups = function(evt) {
        return broadcastOn(dismissPopups(), { target: evt.target });
      };
      var doc = getDocument();
      var onTouchstart = bind(doc, "touchstart", fireDismissPopups);
      var onTouchmove = bind(doc, "touchmove", function(evt) {
        return broadcastEvent(documentTouchmove(), evt);
      });
      var onTouchend = bind(doc, "touchend", function(evt) {
        return broadcastEvent(documentTouchend(), evt);
      });
      var onMousedown = bind(doc, "mousedown", fireDismissPopups);
      var onMouseup = bind(doc, "mouseup", function(evt) {
        if (evt.raw.button === 0) {
          broadcastOn(mouseReleased(), { target: evt.target });
        }
      });
      var onContentClick = function(raw) {
        return broadcastOn(dismissPopups(), { target: SugarElement.fromDom(raw.target) });
      };
      var onContentMouseup = function(raw) {
        if (raw.button === 0) {
          broadcastOn(mouseReleased(), { target: SugarElement.fromDom(raw.target) });
        }
      };
      var onContentMousedown = function() {
        each$1(editor.editorManager.get(), function(loopEditor) {
          if (editor !== loopEditor) {
            loopEditor.fire("DismissPopups", { relatedTarget: editor });
          }
        });
      };
      var onWindowScroll = function(evt) {
        return broadcastEvent(windowScroll(), fromRawEvent(evt));
      };
      var onWindowResize2 = function(evt) {
        broadcastOn(repositionPopups(), {});
        broadcastEvent(windowResize(), fromRawEvent(evt));
      };
      var onEditorResize = function() {
        return broadcastOn(repositionPopups(), {});
      };
      var onEditorProgress = function(evt) {
        if (evt.state) {
          broadcastOn(dismissPopups(), { target: SugarElement.fromDom(editor.getContainer()) });
        }
      };
      var onDismissPopups = function(event) {
        broadcastOn(dismissPopups(), { target: SugarElement.fromDom(event.relatedTarget.getContainer()) });
      };
      editor.on("PostRender", function() {
        editor.on("click", onContentClick);
        editor.on("tap", onContentClick);
        editor.on("mouseup", onContentMouseup);
        editor.on("mousedown", onContentMousedown);
        editor.on("ScrollWindow", onWindowScroll);
        editor.on("ResizeWindow", onWindowResize2);
        editor.on("ResizeEditor", onEditorResize);
        editor.on("AfterProgressState", onEditorProgress);
        editor.on("DismissPopups", onDismissPopups);
      });
      editor.on("remove", function() {
        editor.off("click", onContentClick);
        editor.off("tap", onContentClick);
        editor.off("mouseup", onContentMouseup);
        editor.off("mousedown", onContentMousedown);
        editor.off("ScrollWindow", onWindowScroll);
        editor.off("ResizeWindow", onWindowResize2);
        editor.off("ResizeEditor", onEditorResize);
        editor.off("AfterProgressState", onEditorProgress);
        editor.off("DismissPopups", onDismissPopups);
        onMousedown.unbind();
        onTouchstart.unbind();
        onTouchmove.unbind();
        onTouchend.unbind();
        onMouseup.unbind();
      });
      editor.on("detach", function() {
        detachSystem(mothership);
        detachSystem(uiMothership);
        mothership.destroy();
        uiMothership.destroy();
      });
    };
    var parts$a = AlloyParts;
    var partType = PartType;
    var schema$f = constant$1([
      defaulted("shell", false),
      required$1("makeItem"),
      defaulted("setupItem", noop3),
      SketchBehaviours.field("listBehaviours", [Replacing])
    ]);
    var customListDetail = function() {
      return { behaviours: derive$1([Replacing.config({})]) };
    };
    var itemsPart = optional({
      name: "items",
      overrides: customListDetail
    });
    var parts$9 = constant$1([itemsPart]);
    var name = constant$1("CustomList");
    var factory$d = function(detail, components2, _spec, _external) {
      var setItems = function(list, items) {
        getListContainer(list).fold(function() {
          console.error("Custom List was defined to not be a shell, but no item container was specified in components");
          throw new Error("Custom List was defined to not be a shell, but no item container was specified in components");
        }, function(container) {
          var itemComps = Replacing.contents(container);
          var numListsRequired = items.length;
          var numListsToAdd = numListsRequired - itemComps.length;
          var itemsToAdd = numListsToAdd > 0 ? range$2(numListsToAdd, function() {
            return detail.makeItem();
          }) : [];
          var itemsToRemove = itemComps.slice(numListsRequired);
          each$1(itemsToRemove, function(item2) {
            return Replacing.remove(container, item2);
          });
          each$1(itemsToAdd, function(item2) {
            return Replacing.append(container, item2);
          });
          var builtLists = Replacing.contents(container);
          each$1(builtLists, function(item2, i2) {
            detail.setupItem(list, item2, items[i2], i2);
          });
        });
      };
      var extra = detail.shell ? {
        behaviours: [Replacing.config({})],
        components: []
      } : {
        behaviours: [],
        components: components2
      };
      var getListContainer = function(component) {
        return detail.shell ? Optional.some(component) : getPart(component, detail, "items");
      };
      return {
        uid: detail.uid,
        dom: detail.dom,
        components: extra.components,
        behaviours: augment(detail.listBehaviours, extra.behaviours),
        apis: { setItems }
      };
    };
    var CustomList = composite({
      name: name(),
      configFields: schema$f(),
      partFields: parts$9(),
      factory: factory$d,
      apis: {
        setItems: function(apis, list, items) {
          apis.setItems(list, items);
        }
      }
    });
    var schema$e = constant$1([
      required$1("dom"),
      defaulted("shell", true),
      field("toolbarBehaviours", [Replacing])
    ]);
    var enhanceGroups = function() {
      return { behaviours: derive$1([Replacing.config({})]) };
    };
    var parts$8 = constant$1([optional({
      name: "groups",
      overrides: enhanceGroups
    })]);
    var factory$c = function(detail, components2, _spec, _externals) {
      var setGroups2 = function(toolbar, groups) {
        getGroupContainer(toolbar).fold(function() {
          console.error("Toolbar was defined to not be a shell, but no groups container was specified in components");
          throw new Error("Toolbar was defined to not be a shell, but no groups container was specified in components");
        }, function(container) {
          Replacing.set(container, groups);
        });
      };
      var getGroupContainer = function(component) {
        return detail.shell ? Optional.some(component) : getPart(component, detail, "groups");
      };
      var extra = detail.shell ? {
        behaviours: [Replacing.config({})],
        components: []
      } : {
        behaviours: [],
        components: components2
      };
      return {
        uid: detail.uid,
        dom: detail.dom,
        components: extra.components,
        behaviours: augment(detail.toolbarBehaviours, extra.behaviours),
        apis: { setGroups: setGroups2 },
        domModification: { attributes: { role: "group" } }
      };
    };
    var Toolbar = composite({
      name: "Toolbar",
      configFields: schema$e(),
      partFields: parts$8(),
      factory: factory$c,
      apis: {
        setGroups: function(apis, toolbar, groups) {
          apis.setGroups(toolbar, groups);
        }
      }
    });
    var setup$a = noop3;
    var isDocked$2 = never;
    var getBehaviours$1 = constant$1([]);
    var StaticHeader = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      setup: setup$a,
      isDocked: isDocked$2,
      getBehaviours: getBehaviours$1
    });
    var getOffsetParent2 = function(element2) {
      var isFixed = is$1(getRaw(element2, "position"), "fixed");
      var offsetParent$1 = isFixed ? Optional.none() : offsetParent(element2);
      return offsetParent$1.orThunk(function() {
        var marker = SugarElement.fromTag("span");
        return parent(element2).bind(function(parent2) {
          append$2(parent2, marker);
          var offsetParent$12 = offsetParent(marker);
          remove$5(marker);
          return offsetParent$12;
        });
      });
    };
    var getOrigin = function(element2) {
      return getOffsetParent2(element2).map(absolute$3).getOrThunk(function() {
        return SugarPosition(0, 0);
      });
    };
    var morphAdt = Adt.generate([
      { static: [] },
      { absolute: ["positionCss"] },
      { fixed: ["positionCss"] }
    ]);
    var appear = function(component, contextualInfo) {
      var elem = component.element;
      add$2(elem, contextualInfo.transitionClass);
      remove$2(elem, contextualInfo.fadeOutClass);
      add$2(elem, contextualInfo.fadeInClass);
      contextualInfo.onShow(component);
    };
    var disappear = function(component, contextualInfo) {
      var elem = component.element;
      add$2(elem, contextualInfo.transitionClass);
      remove$2(elem, contextualInfo.fadeInClass);
      add$2(elem, contextualInfo.fadeOutClass);
      contextualInfo.onHide(component);
    };
    var isPartiallyVisible = function(box2, viewport3) {
      return box2.y < viewport3.bottom && box2.bottom > viewport3.y;
    };
    var isTopCompletelyVisible = function(box2, viewport3) {
      return box2.y >= viewport3.y;
    };
    var isBottomCompletelyVisible = function(box2, viewport3) {
      return box2.bottom <= viewport3.bottom;
    };
    var isVisibleForModes = function(modes, box2, viewport3) {
      return forall(modes, function(mode) {
        switch (mode) {
          case "bottom":
            return isBottomCompletelyVisible(box2, viewport3);
          case "top":
            return isTopCompletelyVisible(box2, viewport3);
        }
      });
    };
    var getPrior = function(elem, state) {
      return state.getInitialPos().map(function(pos) {
        return bounds(pos.bounds.x, pos.bounds.y, get$a(elem), get$b(elem));
      });
    };
    var storePrior = function(elem, box2, state) {
      state.setInitialPos({
        style: getAllRaw(elem),
        position: get$c(elem, "position") || "static",
        bounds: box2
      });
    };
    var revertToOriginal = function(elem, box2, state) {
      return state.getInitialPos().bind(function(position2) {
        state.clearInitialPos();
        switch (position2.position) {
          case "static":
            return Optional.some(morphAdt.static());
          case "absolute":
            var offsetBox_1 = getOffsetParent2(elem).map(box$1).getOrThunk(function() {
              return box$1(body());
            });
            return Optional.some(morphAdt.absolute(NuPositionCss("absolute", get$e(position2.style, "left").map(function(_left) {
              return box2.x - offsetBox_1.x;
            }), get$e(position2.style, "top").map(function(_top) {
              return box2.y - offsetBox_1.y;
            }), get$e(position2.style, "right").map(function(_right) {
              return offsetBox_1.right - box2.right;
            }), get$e(position2.style, "bottom").map(function(_bottom) {
              return offsetBox_1.bottom - box2.bottom;
            }))));
          default:
            return Optional.none();
        }
      });
    };
    var morphToOriginal = function(elem, viewport3, state) {
      return getPrior(elem, state).filter(function(box2) {
        return isVisibleForModes(state.getModes(), box2, viewport3);
      }).bind(function(box2) {
        return revertToOriginal(elem, box2, state);
      });
    };
    var morphToFixed = function(elem, viewport3, state) {
      var box2 = box$1(elem);
      if (!isVisibleForModes(state.getModes(), box2, viewport3)) {
        storePrior(elem, box2, state);
        var winBox = win();
        var left3 = box2.x - winBox.x;
        var top_1 = viewport3.y - winBox.y;
        var bottom3 = winBox.bottom - viewport3.bottom;
        var isTop = box2.y <= viewport3.y;
        return Optional.some(morphAdt.fixed(NuPositionCss("fixed", Optional.some(left3), isTop ? Optional.some(top_1) : Optional.none(), Optional.none(), !isTop ? Optional.some(bottom3) : Optional.none())));
      } else {
        return Optional.none();
      }
    };
    var getMorph = function(component, viewport3, state) {
      var elem = component.element;
      var isDocked2 = is$1(getRaw(elem, "position"), "fixed");
      return isDocked2 ? morphToOriginal(elem, viewport3, state) : morphToFixed(elem, viewport3, state);
    };
    var getMorphToOriginal = function(component, state) {
      var elem = component.element;
      return getPrior(elem, state).bind(function(box2) {
        return revertToOriginal(elem, box2, state);
      });
    };
    var morphToStatic = function(component, config2, state) {
      state.setDocked(false);
      each$1([
        "left",
        "right",
        "top",
        "bottom",
        "position"
      ], function(prop) {
        return remove$6(component.element, prop);
      });
      config2.onUndocked(component);
    };
    var morphToCoord = function(component, config2, state, position2) {
      var isDocked2 = position2.position === "fixed";
      state.setDocked(isDocked2);
      applyPositionCss(component.element, position2);
      var method = isDocked2 ? config2.onDocked : config2.onUndocked;
      method(component);
    };
    var updateVisibility = function(component, config2, state, viewport3, morphToDocked) {
      if (morphToDocked === void 0) {
        morphToDocked = false;
      }
      config2.contextual.each(function(contextInfo) {
        contextInfo.lazyContext(component).each(function(box2) {
          var isVisible3 = isPartiallyVisible(box2, viewport3);
          if (isVisible3 !== state.isVisible()) {
            state.setVisible(isVisible3);
            if (morphToDocked && !isVisible3) {
              add$1(component.element, [contextInfo.fadeOutClass]);
              contextInfo.onHide(component);
            } else {
              var method = isVisible3 ? appear : disappear;
              method(component, contextInfo);
            }
          }
        });
      });
    };
    var refreshInternal = function(component, config2, state) {
      var viewport3 = config2.lazyViewport(component);
      var isDocked2 = state.isDocked();
      if (isDocked2) {
        updateVisibility(component, config2, state, viewport3);
      }
      getMorph(component, viewport3, state).each(function(morph) {
        morph.fold(function() {
          return morphToStatic(component, config2, state);
        }, function(position2) {
          return morphToCoord(component, config2, state, position2);
        }, function(position2) {
          updateVisibility(component, config2, state, viewport3, true);
          morphToCoord(component, config2, state, position2);
        });
      });
    };
    var resetInternal = function(component, config2, state) {
      var elem = component.element;
      state.setDocked(false);
      getMorphToOriginal(component, state).each(function(morph) {
        morph.fold(function() {
          return morphToStatic(component, config2, state);
        }, function(position2) {
          return morphToCoord(component, config2, state, position2);
        }, noop3);
      });
      state.setVisible(true);
      config2.contextual.each(function(contextInfo) {
        remove$1(elem, [
          contextInfo.fadeInClass,
          contextInfo.fadeOutClass,
          contextInfo.transitionClass
        ]);
        contextInfo.onShow(component);
      });
      refresh$4(component, config2, state);
    };
    var refresh$4 = function(component, config2, state) {
      if (component.getSystem().isConnected()) {
        refreshInternal(component, config2, state);
      }
    };
    var reset = function(component, config2, state) {
      if (state.isDocked()) {
        resetInternal(component, config2, state);
      }
    };
    var isDocked$1 = function(component, config2, state) {
      return state.isDocked();
    };
    var setModes = function(component, config2, state, modes) {
      return state.setModes(modes);
    };
    var getModes = function(component, config2, state) {
      return state.getModes();
    };
    var DockingApis = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      refresh: refresh$4,
      reset,
      isDocked: isDocked$1,
      getModes,
      setModes
    });
    var events$5 = function(dockInfo, dockState) {
      return derive$2([
        runOnSource(transitionend(), function(component, simulatedEvent) {
          dockInfo.contextual.each(function(contextInfo) {
            if (has(component.element, contextInfo.transitionClass)) {
              remove$1(component.element, [
                contextInfo.transitionClass,
                contextInfo.fadeInClass
              ]);
              var notify2 = dockState.isVisible() ? contextInfo.onShown : contextInfo.onHidden;
              notify2(component);
            }
            simulatedEvent.stop();
          });
        }),
        run$1(windowScroll(), function(component, _2) {
          refresh$4(component, dockInfo, dockState);
        }),
        run$1(windowResize(), function(component, _2) {
          reset(component, dockInfo, dockState);
        })
      ]);
    };
    var ActiveDocking = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      events: events$5
    });
    var DockingSchema = [
      optionObjOf("contextual", [
        requiredString("fadeInClass"),
        requiredString("fadeOutClass"),
        requiredString("transitionClass"),
        requiredFunction("lazyContext"),
        onHandler("onShow"),
        onHandler("onShown"),
        onHandler("onHide"),
        onHandler("onHidden")
      ]),
      defaultedFunction("lazyViewport", win),
      defaultedArrayOf("modes", [
        "top",
        "bottom"
      ], string),
      onHandler("onDocked"),
      onHandler("onUndocked")
    ];
    var init$6 = function(spec) {
      var docked = Cell(false);
      var visible = Cell(true);
      var initialBounds = value$1();
      var modes = Cell(spec.modes);
      var readState = function() {
        return "docked:  " + docked.get() + ", visible: " + visible.get() + ", modes: " + modes.get().join(",");
      };
      return nu$8({
        isDocked: docked.get,
        setDocked: docked.set,
        getInitialPos: initialBounds.get,
        setInitialPos: initialBounds.set,
        clearInitialPos: initialBounds.clear,
        isVisible: visible.get,
        setVisible: visible.set,
        getModes: modes.get,
        setModes: modes.set,
        readState
      });
    };
    var DockingState = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      init: init$6
    });
    var Docking = create$7({
      fields: DockingSchema,
      name: "docking",
      active: ActiveDocking,
      apis: DockingApis,
      state: DockingState
    });
    var toolbarHeightChange = constant$1(generate$6("toolbar-height-change"));
    var visibility = {
      fadeInClass: "tox-editor-dock-fadein",
      fadeOutClass: "tox-editor-dock-fadeout",
      transitionClass: "tox-editor-dock-transition"
    };
    var editorStickyOnClass = "tox-tinymce--toolbar-sticky-on";
    var editorStickyOffClass = "tox-tinymce--toolbar-sticky-off";
    var scrollFromBehindHeader = function(e2, containerHeader) {
      var doc = owner$4(containerHeader);
      var viewHeight = doc.dom.defaultView.innerHeight;
      var scrollPos = get$9(doc);
      var markerElement = SugarElement.fromDom(e2.elm);
      var markerPos = absolute$2(markerElement);
      var markerHeight = get$b(markerElement);
      var markerTop = markerPos.y;
      var markerBottom = markerTop + markerHeight;
      var editorHeaderPos = absolute$3(containerHeader);
      var editorHeaderHeight = get$b(containerHeader);
      var editorHeaderTop = editorHeaderPos.top;
      var editorHeaderBottom = editorHeaderTop + editorHeaderHeight;
      var editorHeaderDockedAtTop = Math.abs(editorHeaderTop - scrollPos.top) < 2;
      var editorHeaderDockedAtBottom = Math.abs(editorHeaderBottom - (scrollPos.top + viewHeight)) < 2;
      if (editorHeaderDockedAtTop && markerTop < editorHeaderBottom) {
        to(scrollPos.left, markerTop - editorHeaderHeight, doc);
      } else if (editorHeaderDockedAtBottom && markerBottom > editorHeaderTop) {
        var y2 = markerTop - viewHeight + markerHeight + editorHeaderHeight;
        to(scrollPos.left, y2, doc);
      }
    };
    var isDockedMode = function(header, mode) {
      return contains$2(Docking.getModes(header), mode);
    };
    var updateIframeContentFlow = function(header) {
      var getOccupiedHeight = function(elm2) {
        return getOuter$2(elm2) + (parseInt(get$c(elm2, "margin-top"), 10) || 0) + (parseInt(get$c(elm2, "margin-bottom"), 10) || 0);
      };
      var elm = header.element;
      parent(elm).each(function(parentElem) {
        var padding = "padding-" + Docking.getModes(header)[0];
        if (Docking.isDocked(header)) {
          var parentWidth = get$a(parentElem);
          set$7(elm, "width", parentWidth + "px");
          set$7(parentElem, padding, getOccupiedHeight(elm) + "px");
        } else {
          remove$6(elm, "width");
          remove$6(parentElem, padding);
        }
      });
    };
    var updateSinkVisibility = function(sinkElem, visible) {
      if (visible) {
        remove$2(sinkElem, visibility.fadeOutClass);
        add$1(sinkElem, [
          visibility.transitionClass,
          visibility.fadeInClass
        ]);
      } else {
        remove$2(sinkElem, visibility.fadeInClass);
        add$1(sinkElem, [
          visibility.fadeOutClass,
          visibility.transitionClass
        ]);
      }
    };
    var updateEditorClasses = function(editor, docked) {
      var editorContainer = SugarElement.fromDom(editor.getContainer());
      if (docked) {
        add$2(editorContainer, editorStickyOnClass);
        remove$2(editorContainer, editorStickyOffClass);
      } else {
        add$2(editorContainer, editorStickyOffClass);
        remove$2(editorContainer, editorStickyOnClass);
      }
    };
    var restoreFocus = function(headerElem, focusedElem) {
      var ownerDoc = owner$4(focusedElem);
      active(ownerDoc).filter(function(activeElm) {
        return !eq2(focusedElem, activeElm);
      }).filter(function(activeElm) {
        return eq2(activeElm, SugarElement.fromDom(ownerDoc.dom.body)) || contains2(headerElem, activeElm);
      }).each(function() {
        return focus$3(focusedElem);
      });
    };
    var findFocusedElem = function(rootElm, lazySink) {
      return search(rootElm).orThunk(function() {
        return lazySink().toOptional().bind(function(sink) {
          return search(sink.element);
        });
      });
    };
    var setup$9 = function(editor, sharedBackstage, lazyHeader) {
      if (!editor.inline) {
        if (!sharedBackstage.header.isPositionedAtTop()) {
          editor.on("ResizeEditor", function() {
            lazyHeader().each(Docking.reset);
          });
        }
        editor.on("ResizeWindow ResizeEditor", function() {
          lazyHeader().each(updateIframeContentFlow);
        });
        editor.on("SkinLoaded", function() {
          lazyHeader().each(function(comp) {
            Docking.isDocked(comp) ? Docking.reset(comp) : Docking.refresh(comp);
          });
        });
        editor.on("FullscreenStateChanged", function() {
          lazyHeader().each(Docking.reset);
        });
      }
      editor.on("AfterScrollIntoView", function(e2) {
        lazyHeader().each(function(header) {
          Docking.refresh(header);
          var headerElem = header.element;
          if (isVisible2(headerElem)) {
            scrollFromBehindHeader(e2, headerElem);
          }
        });
      });
      editor.on("PostRender", function() {
        updateEditorClasses(editor, false);
      });
    };
    var isDocked = function(lazyHeader) {
      return lazyHeader().map(Docking.isDocked).getOr(false);
    };
    var getIframeBehaviours = function() {
      var _a2;
      return [Receiving.config({ channels: (_a2 = {}, _a2[toolbarHeightChange()] = { onReceive: updateIframeContentFlow }, _a2) })];
    };
    var getBehaviours = function(editor, sharedBackstage) {
      var focusedElm = value$1();
      var lazySink = sharedBackstage.getSink;
      var runOnSinkElement = function(f2) {
        lazySink().each(function(sink) {
          return f2(sink.element);
        });
      };
      var onDockingSwitch = function(comp) {
        if (!editor.inline) {
          updateIframeContentFlow(comp);
        }
        updateEditorClasses(editor, Docking.isDocked(comp));
        comp.getSystem().broadcastOn([repositionPopups()], {});
        lazySink().each(function(sink) {
          return sink.getSystem().broadcastOn([repositionPopups()], {});
        });
      };
      var additionalBehaviours = editor.inline ? [] : getIframeBehaviours();
      return __spreadArray([
        Focusing.config({}),
        Docking.config({
          contextual: __assign({
            lazyContext: function(comp) {
              var headerHeight = getOuter$2(comp.element);
              var container = editor.inline ? editor.getContentAreaContainer() : editor.getContainer();
              var box2 = box$1(SugarElement.fromDom(container));
              var boxHeight = box2.height - headerHeight;
              var topBound = box2.y + (isDockedMode(comp, "top") ? 0 : headerHeight);
              return Optional.some(bounds(box2.x, topBound, box2.width, boxHeight));
            },
            onShow: function() {
              runOnSinkElement(function(elem) {
                return updateSinkVisibility(elem, true);
              });
            },
            onShown: function(comp) {
              runOnSinkElement(function(elem) {
                return remove$1(elem, [
                  visibility.transitionClass,
                  visibility.fadeInClass
                ]);
              });
              focusedElm.get().each(function(elem) {
                restoreFocus(comp.element, elem);
                focusedElm.clear();
              });
            },
            onHide: function(comp) {
              findFocusedElem(comp.element, lazySink).fold(focusedElm.clear, focusedElm.set);
              runOnSinkElement(function(elem) {
                return updateSinkVisibility(elem, false);
              });
            },
            onHidden: function() {
              runOnSinkElement(function(elem) {
                return remove$1(elem, [visibility.transitionClass]);
              });
            }
          }, visibility),
          lazyViewport: function(comp) {
            var win$1 = win();
            var offset3 = getStickyToolbarOffset(editor);
            var top3 = win$1.y + (isDockedMode(comp, "top") ? offset3 : 0);
            var height2 = win$1.height - (isDockedMode(comp, "bottom") ? offset3 : 0);
            return bounds(win$1.x, top3, win$1.width, height2);
          },
          modes: [sharedBackstage.header.getDockingMode()],
          onDocked: onDockingSwitch,
          onUndocked: onDockingSwitch
        })
      ], additionalBehaviours, true);
    };
    var StickyHeader = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      setup: setup$9,
      isDocked,
      getBehaviours
    });
    var renderHeader = function(spec) {
      var editor = spec.editor;
      var getBehaviours$22 = spec.sticky ? getBehaviours : getBehaviours$1;
      return {
        uid: spec.uid,
        dom: spec.dom,
        components: spec.components,
        behaviours: derive$1(getBehaviours$22(editor, spec.sharedBackstage))
      };
    };
    var groupToolbarButtonSchema = objOf([
      requiredString("type"),
      requiredOf("items", oneOf([
        arrOfObj([
          requiredString("name"),
          requiredArrayOf("items", string)
        ]),
        string
      ]))
    ].concat(baseToolbarButtonFields));
    var createGroupToolbarButton = function(spec) {
      return asRaw("GroupToolbarButton", groupToolbarButtonSchema, spec);
    };
    var baseMenuButtonFields = [
      optionString("text"),
      optionString("tooltip"),
      optionString("icon"),
      requiredFunction("fetch"),
      defaultedFunction("onSetup", function() {
        return noop3;
      })
    ];
    var MenuButtonSchema = objOf(__spreadArray([requiredString("type")], baseMenuButtonFields, true));
    var createMenuButton = function(spec) {
      return asRaw("menubutton", MenuButtonSchema, spec);
    };
    var splitButtonSchema = objOf([
      requiredString("type"),
      optionString("tooltip"),
      optionString("icon"),
      optionString("text"),
      optionFunction("select"),
      requiredFunction("fetch"),
      defaultedFunction("onSetup", function() {
        return noop3;
      }),
      defaultedStringEnum("presets", "normal", [
        "normal",
        "color",
        "listpreview"
      ]),
      defaulted("columns", 1),
      requiredFunction("onAction"),
      requiredFunction("onItemAction")
    ]);
    var createSplitButton = function(spec) {
      return asRaw("SplitButton", splitButtonSchema, spec);
    };
    var factory$b = function(detail, spec) {
      var setMenus = function(comp, menus) {
        var newMenus = map$2(menus, function(m2) {
          var buttonSpec = {
            type: "menubutton",
            text: m2.text,
            fetch: function(callback2) {
              callback2(m2.getItems());
            }
          };
          var internal2 = createMenuButton(buttonSpec).mapError(function(errInfo) {
            return formatError(errInfo);
          }).getOrDie();
          return renderMenuButton(internal2, "tox-mbtn", spec.backstage, Optional.some("menuitem"));
        });
        Replacing.set(comp, newMenus);
      };
      var apis = {
        focus: Keying.focusIn,
        setMenus
      };
      return {
        uid: detail.uid,
        dom: detail.dom,
        components: [],
        behaviours: derive$1([
          Replacing.config({}),
          config("menubar-events", [
            runOnAttached(function(component) {
              detail.onSetup(component);
            }),
            run$1(mouseover(), function(comp, se2) {
              descendant(comp.element, ".tox-mbtn--active").each(function(activeButton) {
                closest$1(se2.event.target, ".tox-mbtn").each(function(hoveredButton) {
                  if (!eq2(activeButton, hoveredButton)) {
                    comp.getSystem().getByDom(activeButton).each(function(activeComp) {
                      comp.getSystem().getByDom(hoveredButton).each(function(hoveredComp) {
                        Dropdown2.expand(hoveredComp);
                        Dropdown2.close(activeComp);
                        Focusing.focus(hoveredComp);
                      });
                    });
                  }
                });
              });
            }),
            run$1(focusShifted(), function(comp, se2) {
              se2.event.prevFocus.bind(function(prev) {
                return comp.getSystem().getByDom(prev).toOptional();
              }).each(function(prev) {
                se2.event.newFocus.bind(function(nu2) {
                  return comp.getSystem().getByDom(nu2).toOptional();
                }).each(function(nu2) {
                  if (Dropdown2.isOpen(prev)) {
                    Dropdown2.expand(nu2);
                    Dropdown2.close(prev);
                  }
                });
              });
            })
          ]),
          Keying.config({
            mode: "flow",
            selector: ".tox-mbtn",
            onEscape: function(comp) {
              detail.onEscape(comp);
              return Optional.some(true);
            }
          }),
          Tabstopping.config({})
        ]),
        apis,
        domModification: { attributes: { role: "menubar" } }
      };
    };
    var SilverMenubar = single({
      factory: factory$b,
      name: "silver.Menubar",
      configFields: [
        required$1("dom"),
        required$1("uid"),
        required$1("onEscape"),
        required$1("backstage"),
        defaulted("onSetup", noop3)
      ],
      apis: {
        focus: function(apis, comp) {
          apis.focus(comp);
        },
        setMenus: function(apis, comp, menus) {
          apis.setMenus(comp, menus);
        }
      }
    });
    var getAnimationRoot = function(component, slideConfig) {
      return slideConfig.getAnimationRoot.fold(function() {
        return component.element;
      }, function(get2) {
        return get2(component);
      });
    };
    var getDimensionProperty = function(slideConfig) {
      return slideConfig.dimension.property;
    };
    var getDimension = function(slideConfig, elem) {
      return slideConfig.dimension.getDimension(elem);
    };
    var disableTransitions = function(component, slideConfig) {
      var root = getAnimationRoot(component, slideConfig);
      remove$1(root, [
        slideConfig.shrinkingClass,
        slideConfig.growingClass
      ]);
    };
    var setShrunk = function(component, slideConfig) {
      remove$2(component.element, slideConfig.openClass);
      add$2(component.element, slideConfig.closedClass);
      set$7(component.element, getDimensionProperty(slideConfig), "0px");
      reflow2(component.element);
    };
    var setGrown = function(component, slideConfig) {
      remove$2(component.element, slideConfig.closedClass);
      add$2(component.element, slideConfig.openClass);
      remove$6(component.element, getDimensionProperty(slideConfig));
    };
    var doImmediateShrink = function(component, slideConfig, slideState, _calculatedSize) {
      slideState.setCollapsed();
      set$7(component.element, getDimensionProperty(slideConfig), getDimension(slideConfig, component.element));
      reflow2(component.element);
      disableTransitions(component, slideConfig);
      setShrunk(component, slideConfig);
      slideConfig.onStartShrink(component);
      slideConfig.onShrunk(component);
    };
    var doStartShrink = function(component, slideConfig, slideState, calculatedSize) {
      var size = calculatedSize.getOrThunk(function() {
        return getDimension(slideConfig, component.element);
      });
      slideState.setCollapsed();
      set$7(component.element, getDimensionProperty(slideConfig), size);
      reflow2(component.element);
      var root = getAnimationRoot(component, slideConfig);
      remove$2(root, slideConfig.growingClass);
      add$2(root, slideConfig.shrinkingClass);
      setShrunk(component, slideConfig);
      slideConfig.onStartShrink(component);
    };
    var doStartSmartShrink = function(component, slideConfig, slideState) {
      var size = getDimension(slideConfig, component.element);
      var shrinker = size === "0px" ? doImmediateShrink : doStartShrink;
      shrinker(component, slideConfig, slideState, Optional.some(size));
    };
    var doStartGrow = function(component, slideConfig, slideState) {
      var root = getAnimationRoot(component, slideConfig);
      var wasShrinking = has(root, slideConfig.shrinkingClass);
      var beforeSize = getDimension(slideConfig, component.element);
      setGrown(component, slideConfig);
      var fullSize = getDimension(slideConfig, component.element);
      var startPartialGrow = function() {
        set$7(component.element, getDimensionProperty(slideConfig), beforeSize);
        reflow2(component.element);
      };
      var startCompleteGrow = function() {
        setShrunk(component, slideConfig);
      };
      var setStartSize = wasShrinking ? startPartialGrow : startCompleteGrow;
      setStartSize();
      remove$2(root, slideConfig.shrinkingClass);
      add$2(root, slideConfig.growingClass);
      setGrown(component, slideConfig);
      set$7(component.element, getDimensionProperty(slideConfig), fullSize);
      slideState.setExpanded();
      slideConfig.onStartGrow(component);
    };
    var refresh$3 = function(component, slideConfig, slideState) {
      if (slideState.isExpanded()) {
        remove$6(component.element, getDimensionProperty(slideConfig));
        var fullSize = getDimension(slideConfig, component.element);
        set$7(component.element, getDimensionProperty(slideConfig), fullSize);
      }
    };
    var grow = function(component, slideConfig, slideState) {
      if (!slideState.isExpanded()) {
        doStartGrow(component, slideConfig, slideState);
      }
    };
    var shrink = function(component, slideConfig, slideState) {
      if (slideState.isExpanded()) {
        doStartSmartShrink(component, slideConfig, slideState);
      }
    };
    var immediateShrink = function(component, slideConfig, slideState) {
      if (slideState.isExpanded()) {
        doImmediateShrink(component, slideConfig, slideState);
      }
    };
    var hasGrown = function(component, slideConfig, slideState) {
      return slideState.isExpanded();
    };
    var hasShrunk = function(component, slideConfig, slideState) {
      return slideState.isCollapsed();
    };
    var isGrowing = function(component, slideConfig, _slideState) {
      var root = getAnimationRoot(component, slideConfig);
      return has(root, slideConfig.growingClass) === true;
    };
    var isShrinking = function(component, slideConfig, _slideState) {
      var root = getAnimationRoot(component, slideConfig);
      return has(root, slideConfig.shrinkingClass) === true;
    };
    var isTransitioning = function(component, slideConfig, slideState) {
      return isGrowing(component, slideConfig) || isShrinking(component, slideConfig);
    };
    var toggleGrow = function(component, slideConfig, slideState) {
      var f2 = slideState.isExpanded() ? doStartSmartShrink : doStartGrow;
      f2(component, slideConfig, slideState);
    };
    var SlidingApis = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      refresh: refresh$3,
      grow,
      shrink,
      immediateShrink,
      hasGrown,
      hasShrunk,
      isGrowing,
      isShrinking,
      isTransitioning,
      toggleGrow,
      disableTransitions
    });
    var exhibit = function(base2, slideConfig, _slideState) {
      var expanded = slideConfig.expanded;
      return expanded ? nu$7({
        classes: [slideConfig.openClass],
        styles: {}
      }) : nu$7({
        classes: [slideConfig.closedClass],
        styles: wrap$1(slideConfig.dimension.property, "0px")
      });
    };
    var events$4 = function(slideConfig, slideState) {
      return derive$2([runOnSource(transitionend(), function(component, simulatedEvent) {
        var raw = simulatedEvent.event.raw;
        if (raw.propertyName === slideConfig.dimension.property) {
          disableTransitions(component, slideConfig);
          if (slideState.isExpanded()) {
            remove$6(component.element, slideConfig.dimension.property);
          }
          var notify2 = slideState.isExpanded() ? slideConfig.onGrown : slideConfig.onShrunk;
          notify2(component);
        }
      })]);
    };
    var ActiveSliding = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      exhibit,
      events: events$4
    });
    var SlidingSchema = [
      required$1("closedClass"),
      required$1("openClass"),
      required$1("shrinkingClass"),
      required$1("growingClass"),
      option("getAnimationRoot"),
      onHandler("onShrunk"),
      onHandler("onStartShrink"),
      onHandler("onGrown"),
      onHandler("onStartGrow"),
      defaulted("expanded", false),
      requiredOf("dimension", choose$1("property", {
        width: [
          output$1("property", "width"),
          output$1("getDimension", function(elem) {
            return get$a(elem) + "px";
          })
        ],
        height: [
          output$1("property", "height"),
          output$1("getDimension", function(elem) {
            return get$b(elem) + "px";
          })
        ]
      }))
    ];
    var init$5 = function(spec) {
      var state = Cell(spec.expanded);
      var readState = function() {
        return "expanded: " + state.get();
      };
      return nu$8({
        isExpanded: function() {
          return state.get() === true;
        },
        isCollapsed: function() {
          return state.get() === false;
        },
        setCollapsed: curry(state.set, false),
        setExpanded: curry(state.set, true),
        readState
      });
    };
    var SlidingState = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      init: init$5
    });
    var Sliding = create$7({
      fields: SlidingSchema,
      name: "sliding",
      active: ActiveSliding,
      apis: SlidingApis,
      state: SlidingState
    });
    var owner = "container";
    var schema$d = [field("slotBehaviours", [])];
    var getPartName = function(name2) {
      return "<alloy.field." + name2 + ">";
    };
    var sketch = function(sSpec) {
      var parts2 = function() {
        var record2 = [];
        var slot = function(name2, config2) {
          record2.push(name2);
          return generateOne$1(owner, getPartName(name2), config2);
        };
        return {
          slot,
          record: constant$1(record2)
        };
      }();
      var spec = sSpec(parts2);
      var partNames = parts2.record();
      var fieldParts = map$2(partNames, function(n2) {
        return required({
          name: n2,
          pname: getPartName(n2)
        });
      });
      return composite$1(owner, schema$d, fieldParts, make$1, spec);
    };
    var make$1 = function(detail, components2) {
      var getSlotNames = function(_2) {
        return getAllPartNames(detail);
      };
      var getSlot = function(container, key) {
        return getPart(container, detail, key);
      };
      var onSlot = function(f2, def) {
        return function(container, key) {
          return getPart(container, detail, key).map(function(slot) {
            return f2(slot, key);
          }).getOr(def);
        };
      };
      var onSlots = function(f2) {
        return function(container, keys2) {
          each$1(keys2, function(key) {
            return f2(container, key);
          });
        };
      };
      var doShowing = function(comp, _key) {
        return get$d(comp.element, "aria-hidden") !== "true";
      };
      var doShow = function(comp, key) {
        if (!doShowing(comp)) {
          var element2 = comp.element;
          remove$6(element2, "display");
          remove$7(element2, "aria-hidden");
          emitWith(comp, slotVisibility(), {
            name: key,
            visible: true
          });
        }
      };
      var doHide = function(comp, key) {
        if (doShowing(comp)) {
          var element2 = comp.element;
          set$7(element2, "display", "none");
          set$8(element2, "aria-hidden", "true");
          emitWith(comp, slotVisibility(), {
            name: key,
            visible: false
          });
        }
      };
      var isShowing = onSlot(doShowing, false);
      var hideSlot = onSlot(doHide);
      var hideSlots = onSlots(hideSlot);
      var hideAllSlots = function(container) {
        return hideSlots(container, getSlotNames());
      };
      var showSlot = onSlot(doShow);
      var apis = {
        getSlotNames,
        getSlot,
        isShowing,
        hideSlot,
        hideAllSlots,
        showSlot
      };
      return {
        uid: detail.uid,
        dom: detail.dom,
        components: components2,
        behaviours: get$2(detail.slotBehaviours),
        apis
      };
    };
    var slotApis = map$12({
      getSlotNames: function(apis, c2) {
        return apis.getSlotNames(c2);
      },
      getSlot: function(apis, c2, key) {
        return apis.getSlot(c2, key);
      },
      isShowing: function(apis, c2, key) {
        return apis.isShowing(c2, key);
      },
      hideSlot: function(apis, c2, key) {
        return apis.hideSlot(c2, key);
      },
      hideAllSlots: function(apis, c2) {
        return apis.hideAllSlots(c2);
      },
      showSlot: function(apis, c2, key) {
        return apis.showSlot(c2, key);
      }
    }, function(value2) {
      return makeApi(value2);
    });
    var SlotContainer = __assign(__assign({}, slotApis), { sketch });
    var sidebarSchema = objOf([
      optionString("icon"),
      optionString("tooltip"),
      defaultedFunction("onShow", noop3),
      defaultedFunction("onHide", noop3),
      defaultedFunction("onSetup", function() {
        return noop3;
      })
    ]);
    var createSidebar = function(spec) {
      return asRaw("sidebar", sidebarSchema, spec);
    };
    var setup$8 = function(editor) {
      var sidebars = editor.ui.registry.getAll().sidebars;
      each$1(keys(sidebars), function(name2) {
        var spec = sidebars[name2];
        var isActive = function() {
          return is$1(Optional.from(editor.queryCommandValue("ToggleSidebar")), name2);
        };
        editor.ui.registry.addToggleButton(name2, {
          icon: spec.icon,
          tooltip: spec.tooltip,
          onAction: function(buttonApi) {
            editor.execCommand("ToggleSidebar", false, name2);
            buttonApi.setActive(isActive());
          },
          onSetup: function(buttonApi) {
            var handleToggle = function() {
              return buttonApi.setActive(isActive());
            };
            editor.on("ToggleSidebar", handleToggle);
            return function() {
              editor.off("ToggleSidebar", handleToggle);
            };
          }
        });
      });
    };
    var getApi = function(comp) {
      return {
        element: function() {
          return comp.element.dom;
        }
      };
    };
    var makePanels = function(parts2, panelConfigs) {
      var specs = map$2(keys(panelConfigs), function(name2) {
        var spec = panelConfigs[name2];
        var bridged = getOrDie(createSidebar(spec));
        return {
          name: name2,
          getApi,
          onSetup: bridged.onSetup,
          onShow: bridged.onShow,
          onHide: bridged.onHide
        };
      });
      return map$2(specs, function(spec) {
        var editorOffCell = Cell(noop3);
        return parts2.slot(spec.name, {
          dom: {
            tag: "div",
            classes: ["tox-sidebar__pane"]
          },
          behaviours: SimpleBehaviours.unnamedEvents([
            onControlAttached(spec, editorOffCell),
            onControlDetached(spec, editorOffCell),
            run$1(slotVisibility(), function(sidepanel, se2) {
              var data = se2.event;
              var optSidePanelSpec = find$5(specs, function(config2) {
                return config2.name === data.name;
              });
              optSidePanelSpec.each(function(sidePanelSpec) {
                var handler = data.visible ? sidePanelSpec.onShow : sidePanelSpec.onHide;
                handler(sidePanelSpec.getApi(sidepanel));
              });
            })
          ])
        });
      });
    };
    var makeSidebar = function(panelConfigs) {
      return SlotContainer.sketch(function(parts2) {
        return {
          dom: {
            tag: "div",
            classes: ["tox-sidebar__pane-container"]
          },
          components: makePanels(parts2, panelConfigs),
          slotBehaviours: SimpleBehaviours.unnamedEvents([runOnAttached(function(slotContainer) {
            return SlotContainer.hideAllSlots(slotContainer);
          })])
        };
      });
    };
    var setSidebar = function(sidebar, panelConfigs) {
      var optSlider = Composing.getCurrent(sidebar);
      optSlider.each(function(slider) {
        return Replacing.set(slider, [makeSidebar(panelConfigs)]);
      });
    };
    var toggleSidebar = function(sidebar, name2) {
      var optSlider = Composing.getCurrent(sidebar);
      optSlider.each(function(slider) {
        var optSlotContainer = Composing.getCurrent(slider);
        optSlotContainer.each(function(slotContainer) {
          if (Sliding.hasGrown(slider)) {
            if (SlotContainer.isShowing(slotContainer, name2)) {
              Sliding.shrink(slider);
            } else {
              SlotContainer.hideAllSlots(slotContainer);
              SlotContainer.showSlot(slotContainer, name2);
            }
          } else {
            SlotContainer.hideAllSlots(slotContainer);
            SlotContainer.showSlot(slotContainer, name2);
            Sliding.grow(slider);
          }
        });
      });
    };
    var whichSidebar = function(sidebar) {
      var optSlider = Composing.getCurrent(sidebar);
      return optSlider.bind(function(slider) {
        var sidebarOpen = Sliding.isGrowing(slider) || Sliding.hasGrown(slider);
        if (sidebarOpen) {
          var optSlotContainer = Composing.getCurrent(slider);
          return optSlotContainer.bind(function(slotContainer) {
            return find$5(SlotContainer.getSlotNames(slotContainer), function(name2) {
              return SlotContainer.isShowing(slotContainer, name2);
            });
          });
        } else {
          return Optional.none();
        }
      });
    };
    var fixSize = generate$6("FixSizeEvent");
    var autoSize = generate$6("AutoSizeEvent");
    var renderSidebar = function(spec) {
      return {
        uid: spec.uid,
        dom: {
          tag: "div",
          classes: ["tox-sidebar"],
          attributes: { role: "complementary" }
        },
        components: [{
          dom: {
            tag: "div",
            classes: ["tox-sidebar__slider"]
          },
          components: [],
          behaviours: derive$1([
            Tabstopping.config({}),
            Focusing.config({}),
            Sliding.config({
              dimension: { property: "width" },
              closedClass: "tox-sidebar--sliding-closed",
              openClass: "tox-sidebar--sliding-open",
              shrinkingClass: "tox-sidebar--sliding-shrinking",
              growingClass: "tox-sidebar--sliding-growing",
              onShrunk: function(slider) {
                var optSlotContainer = Composing.getCurrent(slider);
                optSlotContainer.each(SlotContainer.hideAllSlots);
                emit(slider, autoSize);
              },
              onGrown: function(slider) {
                emit(slider, autoSize);
              },
              onStartGrow: function(slider) {
                emitWith(slider, fixSize, { width: getRaw(slider.element, "width").getOr("") });
              },
              onStartShrink: function(slider) {
                emitWith(slider, fixSize, { width: get$a(slider.element) + "px" });
              }
            }),
            Replacing.config({}),
            Composing.config({
              find: function(comp) {
                var children2 = Replacing.contents(comp);
                return head(children2);
              }
            })
          ])
        }],
        behaviours: derive$1([
          ComposingConfigs.childAt(0),
          config("sidebar-sliding-events", [
            run$1(fixSize, function(comp, se2) {
              set$7(comp.element, "width", se2.event.width);
            }),
            run$1(autoSize, function(comp, _se) {
              remove$6(comp.element, "width");
            })
          ])
        ])
      };
    };
    var block = function(component, config2, state, getBusySpec2) {
      set$8(component.element, "aria-busy", true);
      var root = config2.getRoot(component).getOr(component);
      var blockerBehaviours = derive$1([
        Keying.config({
          mode: "special",
          onTab: function() {
            return Optional.some(true);
          },
          onShiftTab: function() {
            return Optional.some(true);
          }
        }),
        Focusing.config({})
      ]);
      var blockSpec = getBusySpec2(root, blockerBehaviours);
      var blocker = root.getSystem().build(blockSpec);
      Replacing.append(root, premade(blocker));
      if (blocker.hasConfigured(Keying) && config2.focus) {
        Keying.focusIn(blocker);
      }
      if (!state.isBlocked()) {
        config2.onBlock(component);
      }
      state.blockWith(function() {
        return Replacing.remove(root, blocker);
      });
    };
    var unblock = function(component, config2, state) {
      remove$7(component.element, "aria-busy");
      if (state.isBlocked()) {
        config2.onUnblock(component);
      }
      state.clear();
    };
    var BlockingApis = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      block,
      unblock
    });
    var BlockingSchema = [
      defaultedFunction("getRoot", Optional.none),
      defaultedBoolean("focus", true),
      onHandler("onBlock"),
      onHandler("onUnblock")
    ];
    var init$4 = function() {
      var blocker = destroyable();
      var blockWith = function(destroy) {
        blocker.set({ destroy });
      };
      return nu$8({
        readState: blocker.isSet,
        blockWith,
        clear: blocker.clear,
        isBlocked: blocker.isSet
      });
    };
    var BlockingState = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      init: init$4
    });
    var Blocking = create$7({
      fields: BlockingSchema,
      name: "blocking",
      apis: BlockingApis,
      state: BlockingState
    });
    var getAttrs = function(elem) {
      var attributes = elem.dom.attributes !== void 0 ? elem.dom.attributes : [];
      return foldl(attributes, function(b3, attr) {
        var _a2;
        if (attr.name === "class") {
          return b3;
        } else {
          return __assign(__assign({}, b3), (_a2 = {}, _a2[attr.name] = attr.value, _a2));
        }
      }, {});
    };
    var getClasses = function(elem) {
      return Array.prototype.slice.call(elem.dom.classList, 0);
    };
    var fromHtml = function(html) {
      var elem = SugarElement.fromHtml(html);
      var children$1 = children(elem);
      var attrs = getAttrs(elem);
      var classes2 = getClasses(elem);
      var contents2 = children$1.length === 0 ? {} : { innerHtml: get$7(elem) };
      return __assign({
        tag: name$2(elem),
        classes: classes2,
        attributes: attrs
      }, contents2);
    };
    var getBusySpec$1 = function(providerBackstage) {
      return function(_root, _behaviours) {
        return {
          dom: {
            tag: "div",
            attributes: {
              "aria-label": providerBackstage.translate("Loading..."),
              "tabindex": "0"
            },
            classes: ["tox-throbber__busy-spinner"]
          },
          components: [{ dom: fromHtml('<div class="tox-spinner"><div></div><div></div><div></div></div>') }]
        };
      };
    };
    var focusBusyComponent = function(throbber) {
      return Composing.getCurrent(throbber).each(function(comp) {
        return focus$3(comp.element);
      });
    };
    var toggleEditorTabIndex = function(editor, state) {
      var tabIndexAttr = "tabindex";
      var dataTabIndexAttr = "data-mce-" + tabIndexAttr;
      Optional.from(editor.iframeElement).map(SugarElement.fromDom).each(function(iframe2) {
        if (state) {
          getOpt(iframe2, tabIndexAttr).each(function(tabIndex) {
            return set$8(iframe2, dataTabIndexAttr, tabIndex);
          });
          set$8(iframe2, tabIndexAttr, -1);
        } else {
          remove$7(iframe2, tabIndexAttr);
          getOpt(iframe2, dataTabIndexAttr).each(function(tabIndex) {
            set$8(iframe2, tabIndexAttr, tabIndex);
            remove$7(iframe2, dataTabIndexAttr);
          });
        }
      });
    };
    var toggleThrobber = function(editor, comp, state, providerBackstage) {
      var element2 = comp.element;
      toggleEditorTabIndex(editor, state);
      if (state) {
        Blocking.block(comp, getBusySpec$1(providerBackstage));
        remove$6(element2, "display");
        remove$7(element2, "aria-hidden");
        if (editor.hasFocus()) {
          focusBusyComponent(comp);
        }
      } else {
        var throbberFocus = Composing.getCurrent(comp).exists(function(busyComp) {
          return hasFocus(busyComp.element);
        });
        Blocking.unblock(comp);
        set$7(element2, "display", "none");
        set$8(element2, "aria-hidden", "true");
        if (throbberFocus) {
          editor.focus();
        }
      }
    };
    var renderThrobber = function(spec) {
      return {
        uid: spec.uid,
        dom: {
          tag: "div",
          attributes: { "aria-hidden": "true" },
          classes: ["tox-throbber"],
          styles: { display: "none" }
        },
        behaviours: derive$1([
          Replacing.config({}),
          Blocking.config({ focus: false }),
          Composing.config({
            find: function(comp) {
              return head(comp.components());
            }
          })
        ]),
        components: []
      };
    };
    var isFocusEvent = function(event) {
      return event.type === "focusin";
    };
    var isPasteBinTarget = function(event) {
      if (isFocusEvent(event)) {
        var node = event.composed ? head(event.composedPath()) : Optional.from(event.target);
        return node.map(SugarElement.fromDom).filter(isElement$2).exists(function(targetElm) {
          return has(targetElm, "mce-pastebin");
        });
      } else {
        return false;
      }
    };
    var setup$7 = function(editor, lazyThrobber, sharedBackstage) {
      var throbberState = Cell(false);
      var timer = value$1();
      var stealFocus = function(e2) {
        if (throbberState.get() && !isPasteBinTarget(e2)) {
          e2.preventDefault();
          focusBusyComponent(lazyThrobber());
          editor.editorManager.setActive(editor);
        }
      };
      if (!editor.inline) {
        editor.on("PreInit", function() {
          editor.dom.bind(editor.getWin(), "focusin", stealFocus);
          editor.on("BeforeExecCommand", function(e2) {
            if (e2.command.toLowerCase() === "mcefocus" && e2.value !== true) {
              stealFocus(e2);
            }
          });
        });
      }
      var toggle2 = function(state) {
        if (state !== throbberState.get()) {
          throbberState.set(state);
          toggleThrobber(editor, lazyThrobber(), state, sharedBackstage.providers);
          editor.fire("AfterProgressState", { state });
        }
      };
      editor.on("ProgressState", function(e2) {
        timer.on(global$f.clearTimeout);
        if (isNumber2(e2.time)) {
          var timerId = global$f.setEditorTimeout(editor, function() {
            return toggle2(e2.state);
          }, e2.time);
          timer.set(timerId);
        } else {
          toggle2(e2.state);
          timer.clear();
        }
      });
    };
    var generate$1 = function(xs, f2) {
      var init2 = {
        len: 0,
        list: []
      };
      var r3 = foldl(xs, function(b3, a2) {
        var value2 = f2(a2, b3.len);
        return value2.fold(constant$1(b3), function(v2) {
          return {
            len: v2.finish,
            list: b3.list.concat([v2])
          };
        });
      }, init2);
      return r3.list;
    };
    var output = function(within2, extra, withinWidth) {
      return {
        within: within2,
        extra,
        withinWidth
      };
    };
    var apportion = function(units2, total, len) {
      var parray = generate$1(units2, function(unit, current) {
        var width2 = len(unit);
        return Optional.some({
          element: unit,
          start: current,
          finish: current + width2,
          width: width2
        });
      });
      var within2 = filter$2(parray, function(unit) {
        return unit.finish <= total;
      });
      var withinWidth = foldr(within2, function(acc, el) {
        return acc + el.width;
      }, 0);
      var extra = parray.slice(within2.length);
      return {
        within: within2,
        extra,
        withinWidth
      };
    };
    var toUnit = function(parray) {
      return map$2(parray, function(unit) {
        return unit.element;
      });
    };
    var fitLast = function(within2, extra, withinWidth) {
      var fits = toUnit(within2.concat(extra));
      return output(fits, [], withinWidth);
    };
    var overflow = function(within2, extra, overflower, withinWidth) {
      var fits = toUnit(within2).concat([overflower]);
      return output(fits, toUnit(extra), withinWidth);
    };
    var fitAll = function(within2, extra, withinWidth) {
      return output(toUnit(within2), [], withinWidth);
    };
    var tryFit = function(total, units2, len) {
      var divide = apportion(units2, total, len);
      return divide.extra.length === 0 ? Optional.some(divide) : Optional.none();
    };
    var partition = function(total, units2, len, overflower) {
      var divide = tryFit(total, units2, len).getOrThunk(function() {
        return apportion(units2, total - len(overflower), len);
      });
      var within2 = divide.within;
      var extra = divide.extra;
      var withinWidth = divide.withinWidth;
      if (extra.length === 1 && extra[0].width <= len(overflower)) {
        return fitLast(within2, extra, withinWidth);
      } else if (extra.length >= 1) {
        return overflow(within2, extra, overflower, withinWidth);
      } else {
        return fitAll(within2, extra, withinWidth);
      }
    };
    var setGroups$1 = function(toolbar, storedGroups) {
      var bGroups = map$2(storedGroups, function(g2) {
        return premade(g2);
      });
      Toolbar.setGroups(toolbar, bGroups);
    };
    var findFocusedComp = function(comps) {
      return findMap(comps, function(comp) {
        return search(comp.element).bind(function(focusedElm) {
          return comp.getSystem().getByDom(focusedElm).toOptional();
        });
      });
    };
    var refresh$2 = function(toolbar, detail, setOverflow) {
      var builtGroups = detail.builtGroups.get();
      if (builtGroups.length === 0) {
        return;
      }
      var primary = getPartOrDie(toolbar, detail, "primary");
      var overflowGroup = Coupling.getCoupled(toolbar, "overflowGroup");
      set$7(primary.element, "visibility", "hidden");
      var groups = builtGroups.concat([overflowGroup]);
      var focusedComp = findFocusedComp(groups);
      setOverflow([]);
      setGroups$1(primary, groups);
      var availableWidth = get$a(primary.element);
      var overflows = partition(availableWidth, detail.builtGroups.get(), function(comp) {
        return get$a(comp.element);
      }, overflowGroup);
      if (overflows.extra.length === 0) {
        Replacing.remove(primary, overflowGroup);
        setOverflow([]);
      } else {
        setGroups$1(primary, overflows.within);
        setOverflow(overflows.extra);
      }
      remove$6(primary.element, "visibility");
      reflow2(primary.element);
      focusedComp.each(Focusing.focus);
    };
    var schema$c = constant$1([
      field("splitToolbarBehaviours", [Coupling]),
      customField("builtGroups", function() {
        return Cell([]);
      })
    ]);
    var schema$b = constant$1([
      markers$1(["overflowToggledClass"]),
      optionFunction("getOverflowBounds"),
      required$1("lazySink"),
      customField("overflowGroups", function() {
        return Cell([]);
      })
    ].concat(schema$c()));
    var parts$7 = constant$1([
      required({
        factory: Toolbar,
        schema: schema$e(),
        name: "primary"
      }),
      external$1({
        schema: schema$e(),
        name: "overflow"
      }),
      external$1({ name: "overflow-button" }),
      external$1({ name: "overflow-group" })
    ]);
    var expandable = constant$1(function(element2, available) {
      setMax(element2, Math.floor(available));
    });
    var schema$a = constant$1([
      markers$1(["toggledClass"]),
      required$1("lazySink"),
      requiredFunction("fetch"),
      optionFunction("getBounds"),
      optionObjOf("fireDismissalEventInstead", [defaulted("event", dismissRequested())]),
      schema$y()
    ]);
    var parts$6 = constant$1([
      external$1({
        name: "button",
        overrides: function(detail) {
          return {
            dom: { attributes: { "aria-haspopup": "true" } },
            buttonBehaviours: derive$1([Toggling.config({
              toggleClass: detail.markers.toggledClass,
              aria: { mode: "expanded" },
              toggleOnExecute: false
            })])
          };
        }
      }),
      external$1({
        factory: Toolbar,
        schema: schema$e(),
        name: "toolbar",
        overrides: function(detail) {
          return {
            toolbarBehaviours: derive$1([Keying.config({
              mode: "cyclic",
              onEscape: function(comp) {
                getPart(comp, detail, "button").each(Focusing.focus);
                return Optional.none();
              }
            })])
          };
        }
      })
    ]);
    var toggle = function(button2, externals) {
      var toolbarSandbox = Coupling.getCoupled(button2, "toolbarSandbox");
      if (Sandboxing.isOpen(toolbarSandbox)) {
        Sandboxing.close(toolbarSandbox);
      } else {
        Sandboxing.open(toolbarSandbox, externals.toolbar());
      }
    };
    var position = function(button2, toolbar, detail, layouts3) {
      var bounds2 = detail.getBounds.map(function(bounder) {
        return bounder();
      });
      var sink = detail.lazySink(button2).getOrDie();
      Positioning.positionWithinBounds(sink, toolbar, {
        anchor: {
          type: "hotspot",
          hotspot: button2,
          layouts: layouts3,
          overrides: { maxWidthFunction: expandable() }
        }
      }, bounds2);
    };
    var setGroups = function(button2, toolbar, detail, layouts3, groups) {
      Toolbar.setGroups(toolbar, groups);
      position(button2, toolbar, detail, layouts3);
      Toggling.on(button2);
    };
    var makeSandbox = function(button2, spec, detail) {
      var ariaOwner = manager();
      var onOpen = function(sandbox, toolbar) {
        detail.fetch().get(function(groups) {
          setGroups(button2, toolbar, detail, spec.layouts, groups);
          ariaOwner.link(button2.element);
          Keying.focusIn(toolbar);
        });
      };
      var onClose = function() {
        Toggling.off(button2);
        Focusing.focus(button2);
        ariaOwner.unlink(button2.element);
      };
      return {
        dom: {
          tag: "div",
          attributes: { id: ariaOwner.id }
        },
        behaviours: derive$1([
          Keying.config({
            mode: "special",
            onEscape: function(comp) {
              Sandboxing.close(comp);
              return Optional.some(true);
            }
          }),
          Sandboxing.config({
            onOpen,
            onClose,
            isPartOf: function(container, data, queryElem) {
              return isPartOf$1(data, queryElem) || isPartOf$1(button2, queryElem);
            },
            getAttachPoint: function() {
              return detail.lazySink(button2).getOrDie();
            }
          }),
          Receiving.config({
            channels: __assign(__assign({}, receivingChannel$1(__assign({ isExtraPart: never }, detail.fireDismissalEventInstead.map(function(fe2) {
              return { fireEventInstead: { event: fe2.event } };
            }).getOr({})))), receivingChannel({
              doReposition: function() {
                Sandboxing.getState(Coupling.getCoupled(button2, "toolbarSandbox")).each(function(toolbar) {
                  position(button2, toolbar, detail, spec.layouts);
                });
              }
            }))
          })
        ])
      };
    };
    var factory$a = function(detail, components2, spec, externals) {
      return __assign(__assign({}, Button2.sketch(__assign(__assign({}, externals.button()), {
        action: function(button2) {
          toggle(button2, externals);
        },
        buttonBehaviours: SketchBehaviours.augment({ dump: externals.button().buttonBehaviours }, [Coupling.config({
          others: {
            toolbarSandbox: function(button2) {
              return makeSandbox(button2, spec, detail);
            }
          }
        })])
      }))), {
        apis: {
          setGroups: function(button2, groups) {
            Sandboxing.getState(Coupling.getCoupled(button2, "toolbarSandbox")).each(function(toolbar) {
              setGroups(button2, toolbar, detail, spec.layouts, groups);
            });
          },
          reposition: function(button2) {
            Sandboxing.getState(Coupling.getCoupled(button2, "toolbarSandbox")).each(function(toolbar) {
              position(button2, toolbar, detail, spec.layouts);
            });
          },
          toggle: function(button2) {
            toggle(button2, externals);
          },
          getToolbar: function(button2) {
            return Sandboxing.getState(Coupling.getCoupled(button2, "toolbarSandbox"));
          },
          isOpen: function(button2) {
            return Sandboxing.isOpen(Coupling.getCoupled(button2, "toolbarSandbox"));
          }
        }
      });
    };
    var FloatingToolbarButton = composite({
      name: "FloatingToolbarButton",
      factory: factory$a,
      configFields: schema$a(),
      partFields: parts$6(),
      apis: {
        setGroups: function(apis, button2, groups) {
          apis.setGroups(button2, groups);
        },
        reposition: function(apis, button2) {
          apis.reposition(button2);
        },
        toggle: function(apis, button2) {
          apis.toggle(button2);
        },
        getToolbar: function(apis, button2) {
          return apis.getToolbar(button2);
        },
        isOpen: function(apis, button2) {
          return apis.isOpen(button2);
        }
      }
    });
    var schema$9 = constant$1([
      required$1("items"),
      markers$1(["itemSelector"]),
      field("tgroupBehaviours", [Keying])
    ]);
    var parts$5 = constant$1([group({
      name: "items",
      unit: "item"
    })]);
    var factory$9 = function(detail, components2, _spec, _externals) {
      return {
        uid: detail.uid,
        dom: detail.dom,
        components: components2,
        behaviours: augment(detail.tgroupBehaviours, [Keying.config({
          mode: "flow",
          selector: detail.markers.itemSelector
        })]),
        domModification: { attributes: { role: "toolbar" } }
      };
    };
    var ToolbarGroup = composite({
      name: "ToolbarGroup",
      configFields: schema$9(),
      partFields: parts$5(),
      factory: factory$9
    });
    var buildGroups = function(comps) {
      return map$2(comps, function(g2) {
        return premade(g2);
      });
    };
    var refresh$1 = function(toolbar, memFloatingToolbarButton, detail) {
      refresh$2(toolbar, detail, function(overflowGroups) {
        detail.overflowGroups.set(overflowGroups);
        memFloatingToolbarButton.getOpt(toolbar).each(function(floatingToolbarButton) {
          FloatingToolbarButton.setGroups(floatingToolbarButton, buildGroups(overflowGroups));
        });
      });
    };
    var factory$8 = function(detail, components2, spec, externals) {
      var memFloatingToolbarButton = record(FloatingToolbarButton.sketch({
        fetch: function() {
          return Future.nu(function(resolve2) {
            resolve2(buildGroups(detail.overflowGroups.get()));
          });
        },
        layouts: {
          onLtr: function() {
            return [
              southwest$2,
              southeast$2
            ];
          },
          onRtl: function() {
            return [
              southeast$2,
              southwest$2
            ];
          },
          onBottomLtr: function() {
            return [
              northwest$2,
              northeast$2
            ];
          },
          onBottomRtl: function() {
            return [
              northeast$2,
              northwest$2
            ];
          }
        },
        getBounds: spec.getOverflowBounds,
        lazySink: detail.lazySink,
        fireDismissalEventInstead: {},
        markers: { toggledClass: detail.markers.overflowToggledClass },
        parts: {
          button: externals["overflow-button"](),
          toolbar: externals.overflow()
        }
      }));
      return {
        uid: detail.uid,
        dom: detail.dom,
        components: components2,
        behaviours: augment(detail.splitToolbarBehaviours, [Coupling.config({
          others: {
            overflowGroup: function() {
              return ToolbarGroup.sketch(__assign(__assign({}, externals["overflow-group"]()), { items: [memFloatingToolbarButton.asSpec()] }));
            }
          }
        })]),
        apis: {
          setGroups: function(toolbar, groups) {
            detail.builtGroups.set(map$2(groups, toolbar.getSystem().build));
            refresh$1(toolbar, memFloatingToolbarButton, detail);
          },
          refresh: function(toolbar) {
            return refresh$1(toolbar, memFloatingToolbarButton, detail);
          },
          toggle: function(toolbar) {
            memFloatingToolbarButton.getOpt(toolbar).each(function(floatingToolbarButton) {
              FloatingToolbarButton.toggle(floatingToolbarButton);
            });
          },
          isOpen: function(toolbar) {
            return memFloatingToolbarButton.getOpt(toolbar).map(FloatingToolbarButton.isOpen).getOr(false);
          },
          reposition: function(toolbar) {
            memFloatingToolbarButton.getOpt(toolbar).each(function(floatingToolbarButton) {
              FloatingToolbarButton.reposition(floatingToolbarButton);
            });
          },
          getOverflow: function(toolbar) {
            return memFloatingToolbarButton.getOpt(toolbar).bind(FloatingToolbarButton.getToolbar);
          }
        },
        domModification: { attributes: { role: "group" } }
      };
    };
    var SplitFloatingToolbar = composite({
      name: "SplitFloatingToolbar",
      configFields: schema$b(),
      partFields: parts$7(),
      factory: factory$8,
      apis: {
        setGroups: function(apis, toolbar, groups) {
          apis.setGroups(toolbar, groups);
        },
        refresh: function(apis, toolbar) {
          apis.refresh(toolbar);
        },
        reposition: function(apis, toolbar) {
          apis.reposition(toolbar);
        },
        toggle: function(apis, toolbar) {
          apis.toggle(toolbar);
        },
        isOpen: function(apis, toolbar) {
          return apis.isOpen(toolbar);
        },
        getOverflow: function(apis, toolbar) {
          return apis.getOverflow(toolbar);
        }
      }
    });
    var schema$8 = constant$1([
      markers$1([
        "closedClass",
        "openClass",
        "shrinkingClass",
        "growingClass",
        "overflowToggledClass"
      ]),
      onHandler("onOpened"),
      onHandler("onClosed")
    ].concat(schema$c()));
    var parts$4 = constant$1([
      required({
        factory: Toolbar,
        schema: schema$e(),
        name: "primary"
      }),
      required({
        factory: Toolbar,
        schema: schema$e(),
        name: "overflow",
        overrides: function(detail) {
          return {
            toolbarBehaviours: derive$1([
              Sliding.config({
                dimension: { property: "height" },
                closedClass: detail.markers.closedClass,
                openClass: detail.markers.openClass,
                shrinkingClass: detail.markers.shrinkingClass,
                growingClass: detail.markers.growingClass,
                onShrunk: function(comp) {
                  getPart(comp, detail, "overflow-button").each(function(button2) {
                    Toggling.off(button2);
                    Focusing.focus(button2);
                  });
                  detail.onClosed(comp);
                },
                onGrown: function(comp) {
                  Keying.focusIn(comp);
                  detail.onOpened(comp);
                },
                onStartGrow: function(comp) {
                  getPart(comp, detail, "overflow-button").each(Toggling.on);
                }
              }),
              Keying.config({
                mode: "acyclic",
                onEscape: function(comp) {
                  getPart(comp, detail, "overflow-button").each(Focusing.focus);
                  return Optional.some(true);
                }
              })
            ])
          };
        }
      }),
      external$1({
        name: "overflow-button",
        overrides: function(detail) {
          return {
            buttonBehaviours: derive$1([Toggling.config({
              toggleClass: detail.markers.overflowToggledClass,
              aria: { mode: "pressed" },
              toggleOnExecute: false
            })])
          };
        }
      }),
      external$1({ name: "overflow-group" })
    ]);
    var isOpen = function(toolbar, detail) {
      return getPart(toolbar, detail, "overflow").map(Sliding.hasGrown).getOr(false);
    };
    var toggleToolbar = function(toolbar, detail) {
      getPart(toolbar, detail, "overflow-button").bind(function() {
        return getPart(toolbar, detail, "overflow");
      }).each(function(overf) {
        refresh(toolbar, detail);
        Sliding.toggleGrow(overf);
      });
    };
    var refresh = function(toolbar, detail) {
      getPart(toolbar, detail, "overflow").each(function(overflow2) {
        refresh$2(toolbar, detail, function(groups) {
          var builtGroups = map$2(groups, function(g2) {
            return premade(g2);
          });
          Toolbar.setGroups(overflow2, builtGroups);
        });
        getPart(toolbar, detail, "overflow-button").each(function(button2) {
          if (Sliding.hasGrown(overflow2)) {
            Toggling.on(button2);
          }
        });
        Sliding.refresh(overflow2);
      });
    };
    var factory$7 = function(detail, components2, spec, externals) {
      var toolbarToggleEvent = "alloy.toolbar.toggle";
      var doSetGroups = function(toolbar, groups) {
        var built = map$2(groups, toolbar.getSystem().build);
        detail.builtGroups.set(built);
      };
      return {
        uid: detail.uid,
        dom: detail.dom,
        components: components2,
        behaviours: augment(detail.splitToolbarBehaviours, [
          Coupling.config({
            others: {
              overflowGroup: function(toolbar) {
                return ToolbarGroup.sketch(__assign(__assign({}, externals["overflow-group"]()), {
                  items: [Button2.sketch(__assign(__assign({}, externals["overflow-button"]()), {
                    action: function(_button) {
                      emit(toolbar, toolbarToggleEvent);
                    }
                  }))]
                }));
              }
            }
          }),
          config("toolbar-toggle-events", [run$1(toolbarToggleEvent, function(toolbar) {
            toggleToolbar(toolbar, detail);
          })])
        ]),
        apis: {
          setGroups: function(toolbar, groups) {
            doSetGroups(toolbar, groups);
            refresh(toolbar, detail);
          },
          refresh: function(toolbar) {
            return refresh(toolbar, detail);
          },
          toggle: function(toolbar) {
            return toggleToolbar(toolbar, detail);
          },
          isOpen: function(toolbar) {
            return isOpen(toolbar, detail);
          }
        },
        domModification: { attributes: { role: "group" } }
      };
    };
    var SplitSlidingToolbar = composite({
      name: "SplitSlidingToolbar",
      configFields: schema$8(),
      partFields: parts$4(),
      factory: factory$7,
      apis: {
        setGroups: function(apis, toolbar, groups) {
          apis.setGroups(toolbar, groups);
        },
        refresh: function(apis, toolbar) {
          apis.refresh(toolbar);
        },
        toggle: function(apis, toolbar) {
          apis.toggle(toolbar);
        },
        isOpen: function(apis, toolbar) {
          return apis.isOpen(toolbar);
        }
      }
    });
    var renderToolbarGroupCommon = function(toolbarGroup) {
      var attributes = toolbarGroup.title.fold(function() {
        return {};
      }, function(title) {
        return { attributes: { title } };
      });
      return {
        dom: __assign({
          tag: "div",
          classes: ["tox-toolbar__group"]
        }, attributes),
        components: [ToolbarGroup.parts.items({})],
        items: toolbarGroup.items,
        markers: { itemSelector: "*:not(.tox-split-button) > .tox-tbtn:not([disabled]), .tox-split-button:not([disabled]), .tox-toolbar-nav-js:not([disabled])" },
        tgroupBehaviours: derive$1([
          Tabstopping.config({}),
          Focusing.config({})
        ])
      };
    };
    var renderToolbarGroup = function(toolbarGroup) {
      return ToolbarGroup.sketch(renderToolbarGroupCommon(toolbarGroup));
    };
    var getToolbarbehaviours = function(toolbarSpec, modeName) {
      var onAttached = runOnAttached(function(component) {
        var groups = map$2(toolbarSpec.initGroups, renderToolbarGroup);
        Toolbar.setGroups(component, groups);
      });
      return derive$1([
        DisablingConfigs.toolbarButton(toolbarSpec.providers.isDisabled),
        receivingConfig(),
        Keying.config({
          mode: modeName,
          onEscape: toolbarSpec.onEscape,
          selector: ".tox-toolbar__group"
        }),
        config("toolbar-events", [onAttached])
      ]);
    };
    var renderMoreToolbarCommon = function(toolbarSpec) {
      var modeName = toolbarSpec.cyclicKeying ? "cyclic" : "acyclic";
      return {
        uid: toolbarSpec.uid,
        dom: {
          tag: "div",
          classes: ["tox-toolbar-overlord"]
        },
        parts: {
          "overflow-group": renderToolbarGroupCommon({
            title: Optional.none(),
            items: []
          }),
          "overflow-button": renderIconButtonSpec({
            name: "more",
            icon: Optional.some("more-drawer"),
            disabled: false,
            tooltip: Optional.some("More..."),
            primary: false,
            borderless: false
          }, Optional.none(), toolbarSpec.providers)
        },
        splitToolbarBehaviours: getToolbarbehaviours(toolbarSpec, modeName)
      };
    };
    var renderFloatingMoreToolbar = function(toolbarSpec) {
      var baseSpec = renderMoreToolbarCommon(toolbarSpec);
      var overflowXOffset = 4;
      var primary = SplitFloatingToolbar.parts.primary({
        dom: {
          tag: "div",
          classes: ["tox-toolbar__primary"]
        }
      });
      return SplitFloatingToolbar.sketch(__assign(__assign({}, baseSpec), {
        lazySink: toolbarSpec.getSink,
        getOverflowBounds: function() {
          var headerElem = toolbarSpec.moreDrawerData.lazyHeader().element;
          var headerBounds = absolute$2(headerElem);
          var docElem = documentElement(headerElem);
          var docBounds = absolute$2(docElem);
          var height2 = Math.max(docElem.dom.scrollHeight, docBounds.height);
          return bounds(headerBounds.x + overflowXOffset, docBounds.y, headerBounds.width - overflowXOffset * 2, height2);
        },
        parts: __assign(__assign({}, baseSpec.parts), {
          overflow: {
            dom: {
              tag: "div",
              classes: ["tox-toolbar__overflow"],
              attributes: toolbarSpec.attributes
            }
          }
        }),
        components: [primary],
        markers: { overflowToggledClass: "tox-tbtn--enabled" }
      }));
    };
    var renderSlidingMoreToolbar = function(toolbarSpec) {
      var primary = SplitSlidingToolbar.parts.primary({
        dom: {
          tag: "div",
          classes: ["tox-toolbar__primary"]
        }
      });
      var overflow2 = SplitSlidingToolbar.parts.overflow({
        dom: {
          tag: "div",
          classes: ["tox-toolbar__overflow"]
        }
      });
      var baseSpec = renderMoreToolbarCommon(toolbarSpec);
      return SplitSlidingToolbar.sketch(__assign(__assign({}, baseSpec), {
        components: [
          primary,
          overflow2
        ],
        markers: {
          openClass: "tox-toolbar__overflow--open",
          closedClass: "tox-toolbar__overflow--closed",
          growingClass: "tox-toolbar__overflow--growing",
          shrinkingClass: "tox-toolbar__overflow--shrinking",
          overflowToggledClass: "tox-tbtn--enabled"
        },
        onOpened: function(comp) {
          comp.getSystem().broadcastOn([toolbarHeightChange()], { type: "opened" });
        },
        onClosed: function(comp) {
          comp.getSystem().broadcastOn([toolbarHeightChange()], { type: "closed" });
        }
      }));
    };
    var renderToolbar = function(toolbarSpec) {
      var modeName = toolbarSpec.cyclicKeying ? "cyclic" : "acyclic";
      return Toolbar.sketch({
        uid: toolbarSpec.uid,
        dom: {
          tag: "div",
          classes: ["tox-toolbar"].concat(toolbarSpec.type === ToolbarMode.scrolling ? ["tox-toolbar--scrolling"] : [])
        },
        components: [Toolbar.parts.groups({})],
        toolbarBehaviours: getToolbarbehaviours(toolbarSpec, modeName)
      });
    };
    var factory$6 = function(detail, components2, _spec) {
      var apis = {
        getSocket: function(comp) {
          return parts$a.getPart(comp, detail, "socket");
        },
        setSidebar: function(comp, panelConfigs) {
          parts$a.getPart(comp, detail, "sidebar").each(function(sidebar) {
            return setSidebar(sidebar, panelConfigs);
          });
        },
        toggleSidebar: function(comp, name2) {
          parts$a.getPart(comp, detail, "sidebar").each(function(sidebar) {
            return toggleSidebar(sidebar, name2);
          });
        },
        whichSidebar: function(comp) {
          return parts$a.getPart(comp, detail, "sidebar").bind(whichSidebar).getOrNull();
        },
        getHeader: function(comp) {
          return parts$a.getPart(comp, detail, "header");
        },
        getToolbar: function(comp) {
          return parts$a.getPart(comp, detail, "toolbar");
        },
        setToolbar: function(comp, groups) {
          parts$a.getPart(comp, detail, "toolbar").each(function(toolbar) {
            toolbar.getApis().setGroups(toolbar, groups);
          });
        },
        setToolbars: function(comp, toolbars) {
          parts$a.getPart(comp, detail, "multiple-toolbar").each(function(mToolbar) {
            CustomList.setItems(mToolbar, toolbars);
          });
        },
        refreshToolbar: function(comp) {
          var toolbar = parts$a.getPart(comp, detail, "toolbar");
          toolbar.each(function(toolbar2) {
            return toolbar2.getApis().refresh(toolbar2);
          });
        },
        toggleToolbarDrawer: function(comp) {
          parts$a.getPart(comp, detail, "toolbar").each(function(toolbar) {
            mapFrom(toolbar.getApis().toggle, function(toggle2) {
              return toggle2(toolbar);
            });
          });
        },
        isToolbarDrawerToggled: function(comp) {
          return parts$a.getPart(comp, detail, "toolbar").bind(function(toolbar) {
            return Optional.from(toolbar.getApis().isOpen).map(function(isOpen2) {
              return isOpen2(toolbar);
            });
          }).getOr(false);
        },
        getThrobber: function(comp) {
          return parts$a.getPart(comp, detail, "throbber");
        },
        focusToolbar: function(comp) {
          var optToolbar = parts$a.getPart(comp, detail, "toolbar").orThunk(function() {
            return parts$a.getPart(comp, detail, "multiple-toolbar");
          });
          optToolbar.each(function(toolbar) {
            Keying.focusIn(toolbar);
          });
        },
        setMenubar: function(comp, menus) {
          parts$a.getPart(comp, detail, "menubar").each(function(menubar) {
            SilverMenubar.setMenus(menubar, menus);
          });
        },
        focusMenubar: function(comp) {
          parts$a.getPart(comp, detail, "menubar").each(function(menubar) {
            SilverMenubar.focus(menubar);
          });
        }
      };
      return {
        uid: detail.uid,
        dom: detail.dom,
        components: components2,
        apis,
        behaviours: detail.behaviours
      };
    };
    var partMenubar = partType.optional({
      factory: SilverMenubar,
      name: "menubar",
      schema: [required$1("backstage")]
    });
    var toolbarFactory = function(spec) {
      if (spec.type === ToolbarMode.sliding) {
        return renderSlidingMoreToolbar;
      } else if (spec.type === ToolbarMode.floating) {
        return renderFloatingMoreToolbar;
      } else {
        return renderToolbar;
      }
    };
    var partMultipleToolbar = partType.optional({
      factory: {
        sketch: function(spec) {
          return CustomList.sketch({
            uid: spec.uid,
            dom: spec.dom,
            listBehaviours: derive$1([Keying.config({
              mode: "acyclic",
              selector: ".tox-toolbar"
            })]),
            makeItem: function() {
              return renderToolbar({
                type: spec.type,
                uid: generate$6("multiple-toolbar-item"),
                cyclicKeying: false,
                initGroups: [],
                providers: spec.providers,
                onEscape: function() {
                  spec.onEscape();
                  return Optional.some(true);
                }
              });
            },
            setupItem: function(_mToolbar, tc, data, _index) {
              Toolbar.setGroups(tc, data);
            },
            shell: true
          });
        }
      },
      name: "multiple-toolbar",
      schema: [
        required$1("dom"),
        required$1("onEscape")
      ]
    });
    var partToolbar = partType.optional({
      factory: {
        sketch: function(spec) {
          var renderer = toolbarFactory(spec);
          var toolbarSpec = {
            type: spec.type,
            uid: spec.uid,
            onEscape: function() {
              spec.onEscape();
              return Optional.some(true);
            },
            cyclicKeying: false,
            initGroups: [],
            getSink: spec.getSink,
            providers: spec.providers,
            moreDrawerData: {
              lazyToolbar: spec.lazyToolbar,
              lazyMoreButton: spec.lazyMoreButton,
              lazyHeader: spec.lazyHeader
            },
            attributes: spec.attributes
          };
          return renderer(toolbarSpec);
        }
      },
      name: "toolbar",
      schema: [
        required$1("dom"),
        required$1("onEscape"),
        required$1("getSink")
      ]
    });
    var partHeader = partType.optional({
      factory: { sketch: renderHeader },
      name: "header",
      schema: [required$1("dom")]
    });
    var partSocket = partType.optional({
      name: "socket",
      schema: [required$1("dom")]
    });
    var partSidebar = partType.optional({
      factory: { sketch: renderSidebar },
      name: "sidebar",
      schema: [required$1("dom")]
    });
    var partThrobber = partType.optional({
      factory: { sketch: renderThrobber },
      name: "throbber",
      schema: [required$1("dom")]
    });
    var OuterContainer = composite({
      name: "OuterContainer",
      factory: factory$6,
      configFields: [
        required$1("dom"),
        required$1("behaviours")
      ],
      partFields: [
        partHeader,
        partMenubar,
        partToolbar,
        partMultipleToolbar,
        partSocket,
        partSidebar,
        partThrobber
      ],
      apis: {
        getSocket: function(apis, comp) {
          return apis.getSocket(comp);
        },
        setSidebar: function(apis, comp, panelConfigs) {
          apis.setSidebar(comp, panelConfigs);
        },
        toggleSidebar: function(apis, comp, name2) {
          apis.toggleSidebar(comp, name2);
        },
        whichSidebar: function(apis, comp) {
          return apis.whichSidebar(comp);
        },
        getHeader: function(apis, comp) {
          return apis.getHeader(comp);
        },
        getToolbar: function(apis, comp) {
          return apis.getToolbar(comp);
        },
        setToolbar: function(apis, comp, grps) {
          var groups = map$2(grps, function(grp) {
            return renderToolbarGroup(grp);
          });
          apis.setToolbar(comp, groups);
        },
        setToolbars: function(apis, comp, ts) {
          var renderedToolbars = map$2(ts, function(g2) {
            return map$2(g2, renderToolbarGroup);
          });
          apis.setToolbars(comp, renderedToolbars);
        },
        refreshToolbar: function(apis, comp) {
          return apis.refreshToolbar(comp);
        },
        toggleToolbarDrawer: function(apis, comp) {
          apis.toggleToolbarDrawer(comp);
        },
        isToolbarDrawerToggled: function(apis, comp) {
          return apis.isToolbarDrawerToggled(comp);
        },
        getThrobber: function(apis, comp) {
          return apis.getThrobber(comp);
        },
        setMenubar: function(apis, comp, menus) {
          apis.setMenubar(comp, menus);
        },
        focusMenubar: function(apis, comp) {
          apis.focusMenubar(comp);
        },
        focusToolbar: function(apis, comp) {
          apis.focusToolbar(comp);
        }
      }
    });
    var defaultMenubar = "file edit view insert format tools table help";
    var defaultMenus = {
      file: {
        title: "File",
        items: "newdocument restoredraft | preview | export print | deleteallconversations"
      },
      edit: {
        title: "Edit",
        items: "undo redo | cut copy paste pastetext | selectall | searchreplace"
      },
      view: {
        title: "View",
        items: "code | visualaid visualchars visualblocks | spellchecker | preview fullscreen | showcomments"
      },
      insert: {
        title: "Insert",
        items: "image link media addcomment pageembed template codesample inserttable | charmap emoticons hr | pagebreak nonbreaking anchor toc | insertdatetime"
      },
      format: {
        title: "Format",
        items: "bold italic underline strikethrough superscript subscript codeformat | formats blockformats fontformats fontsizes align lineheight | forecolor backcolor | language | removeformat"
      },
      tools: {
        title: "Tools",
        items: "spellchecker spellcheckerlanguage | a11ycheck code wordcount"
      },
      table: {
        title: "Table",
        items: "inserttable | cell row column | advtablesort | tableprops deletetable"
      },
      help: {
        title: "Help",
        items: "help"
      }
    };
    var make = function(menu2, registry2, editor) {
      var removedMenuItems = getRemovedMenuItems(editor).split(/[ ,]/);
      return {
        text: menu2.title,
        getItems: function() {
          return bind$3(menu2.items, function(i2) {
            var itemName = i2.toLowerCase();
            if (itemName.trim().length === 0) {
              return [];
            } else if (exists(removedMenuItems, function(removedMenuItem) {
              return removedMenuItem === itemName;
            })) {
              return [];
            } else if (itemName === "separator" || itemName === "|") {
              return [{ type: "separator" }];
            } else if (registry2.menuItems[itemName]) {
              return [registry2.menuItems[itemName]];
            } else {
              return [];
            }
          });
        }
      };
    };
    var parseItemsString = function(items) {
      if (typeof items === "string") {
        return items.split(" ");
      }
      return items;
    };
    var identifyMenus = function(editor, registry2) {
      var rawMenuData = __assign(__assign({}, defaultMenus), registry2.menus);
      var userDefinedMenus = keys(registry2.menus).length > 0;
      var menubar = registry2.menubar === void 0 || registry2.menubar === true ? parseItemsString(defaultMenubar) : parseItemsString(registry2.menubar === false ? "" : registry2.menubar);
      var validMenus = filter$2(menubar, function(menuName) {
        var isDefaultMenu = has$2(defaultMenus, menuName);
        if (userDefinedMenus) {
          return isDefaultMenu || get$e(registry2.menus, menuName).exists(function(menu2) {
            return has$2(menu2, "items");
          });
        } else {
          return isDefaultMenu;
        }
      });
      var menus = map$2(validMenus, function(menuName) {
        var menuData = rawMenuData[menuName];
        return make({
          title: menuData.title,
          items: parseItemsString(menuData.items)
        }, registry2, editor);
      });
      return filter$2(menus, function(menu2) {
        var isNotSeparator = function(item2) {
          return item2.type !== "separator";
        };
        return menu2.getItems().length > 0 && exists(menu2.getItems(), isNotSeparator);
      });
    };
    var fireSkinLoaded = function(editor) {
      var done = function() {
        editor._skinLoaded = true;
        fireSkinLoaded$1(editor);
      };
      return function() {
        if (editor.initialized) {
          done();
        } else {
          editor.on("init", done);
        }
      };
    };
    var fireSkinLoadError = function(editor, err) {
      return function() {
        return fireSkinLoadError$1(editor, { message: err });
      };
    };
    var loadStylesheet = function(editor, stylesheetUrl, styleSheetLoader) {
      return new global$c(function(resolve2, reject) {
        styleSheetLoader.load(stylesheetUrl, resolve2, reject);
        editor.on("remove", function() {
          return styleSheetLoader.unload(stylesheetUrl);
        });
      });
    };
    var loadUiSkins = function(editor, skinUrl) {
      var skinUiCss = skinUrl + "/skin.min.css";
      return loadStylesheet(editor, skinUiCss, editor.ui.styleSheetLoader);
    };
    var loadShadowDomUiSkins = function(editor, skinUrl) {
      var isInShadowRoot$1 = isInShadowRoot(SugarElement.fromDom(editor.getElement()));
      if (isInShadowRoot$1) {
        var shadowDomSkinCss = skinUrl + "/skin.shadowdom.min.css";
        return loadStylesheet(editor, shadowDomSkinCss, global$b.DOM.styleSheetLoader);
      } else {
        return global$c.resolve();
      }
    };
    var loadSkin = function(isInline, editor) {
      var skinUrl = getSkinUrl(editor);
      if (skinUrl) {
        editor.contentCSS.push(skinUrl + (isInline ? "/content.inline" : "/content") + ".min.css");
      }
      if (isSkinDisabled(editor) === false && isString(skinUrl)) {
        global$c.all([
          loadUiSkins(editor, skinUrl),
          loadShadowDomUiSkins(editor, skinUrl)
        ]).then(fireSkinLoaded(editor), fireSkinLoadError(editor, "Skin could not be loaded"));
      } else {
        fireSkinLoaded(editor)();
      }
    };
    var iframe = curry(loadSkin, false);
    var inline = curry(loadSkin, true);
    var onSetupFormatToggle = function(editor, name2) {
      return function(api2) {
        var boundCallback = unbindable();
        var init2 = function() {
          api2.setActive(editor.formatter.match(name2));
          var binding = editor.formatter.formatChanged(name2, api2.setActive);
          boundCallback.set(binding);
        };
        editor.initialized ? init2() : editor.once("init", init2);
        return function() {
          editor.off("init", init2);
          boundCallback.clear();
        };
      };
    };
    var onSetupEvent = function(editor, event, f2) {
      return function(api2) {
        var handleEvent = function() {
          return f2(api2);
        };
        var init2 = function() {
          f2(api2);
          editor.on(event, handleEvent);
        };
        editor.initialized ? init2() : editor.once("init", init2);
        return function() {
          editor.off("init", init2);
          editor.off(event, handleEvent);
        };
      };
    };
    var onActionToggleFormat$1 = function(editor) {
      return function(rawItem) {
        return function() {
          editor.undoManager.transact(function() {
            editor.focus();
            editor.execCommand("mceToggleFormat", false, rawItem.format);
          });
        };
      };
    };
    var onActionExecCommand = function(editor, command) {
      return function() {
        return editor.execCommand(command);
      };
    };
    var generateSelectItems = function(_editor, backstage, spec) {
      var generateItem = function(rawItem, response, disabled, value2) {
        var translatedText = backstage.shared.providers.translate(rawItem.title);
        if (rawItem.type === "separator") {
          return Optional.some({
            type: "separator",
            text: translatedText
          });
        } else if (rawItem.type === "submenu") {
          var items = bind$3(rawItem.getStyleItems(), function(si2) {
            return validate(si2, response, value2);
          });
          if (response === 0 && items.length <= 0) {
            return Optional.none();
          } else {
            return Optional.some({
              type: "nestedmenuitem",
              text: translatedText,
              disabled: items.length <= 0,
              getSubmenuItems: function() {
                return bind$3(rawItem.getStyleItems(), function(si2) {
                  return validate(si2, response, value2);
                });
              }
            });
          }
        } else {
          return Optional.some(__assign({
            type: "togglemenuitem",
            text: translatedText,
            icon: rawItem.icon,
            active: rawItem.isSelected(value2),
            disabled,
            onAction: spec.onAction(rawItem)
          }, rawItem.getStylePreview().fold(function() {
            return {};
          }, function(preview) {
            return { meta: { style: preview } };
          })));
        }
      };
      var validate = function(item2, response, value2) {
        var invalid = item2.type === "formatter" && spec.isInvalid(item2);
        if (response === 0) {
          return invalid ? [] : generateItem(item2, response, false, value2).toArray();
        } else {
          return generateItem(item2, response, invalid, value2).toArray();
        }
      };
      var validateItems = function(preItems) {
        var value2 = spec.getCurrentValue();
        var response = spec.shouldHide ? 0 : 1;
        return bind$3(preItems, function(item2) {
          return validate(item2, response, value2);
        });
      };
      var getFetch2 = function(backstage2, getStyleItems) {
        return function(comp, callback2) {
          var preItems = getStyleItems();
          var items = validateItems(preItems);
          var menu2 = build(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage2, false);
          callback2(menu2);
        };
      };
      return {
        validateItems,
        getFetch: getFetch2
      };
    };
    var createMenuItems = function(editor, backstage, spec) {
      var dataset2 = spec.dataset;
      var getStyleItems = dataset2.type === "basic" ? function() {
        return map$2(dataset2.data, function(d2) {
          return processBasic(d2, spec.isSelectedFor, spec.getPreviewFor);
        });
      } : dataset2.getData;
      return {
        items: generateSelectItems(editor, backstage, spec),
        getStyleItems
      };
    };
    var createSelectButton = function(editor, backstage, spec) {
      var _a2 = createMenuItems(editor, backstage, spec), items = _a2.items, getStyleItems = _a2.getStyleItems;
      var getApi2 = function(comp) {
        return { getComponent: constant$1(comp) };
      };
      var onSetup = onSetupEvent(editor, "NodeChange", function(api2) {
        var comp = api2.getComponent();
        spec.updateText(comp);
      });
      return renderCommonDropdown({
        text: spec.icon.isSome() ? Optional.none() : spec.text,
        icon: spec.icon,
        tooltip: Optional.from(spec.tooltip),
        role: Optional.none(),
        fetch: items.getFetch(backstage, getStyleItems),
        onSetup,
        getApi: getApi2,
        columns: 1,
        presets: "normal",
        classes: spec.icon.isSome() ? [] : ["bespoke"],
        dropdownBehaviours: []
      }, "tox-tbtn", backstage.shared);
    };
    var process2 = function(rawFormats) {
      return map$2(rawFormats, function(item2) {
        var title = item2, format3 = item2;
        var values2 = item2.split("=");
        if (values2.length > 1) {
          title = values2[0];
          format3 = values2[1];
        }
        return {
          title,
          format: format3
        };
      });
    };
    var buildBasicStaticDataset = function(data) {
      return {
        type: "basic",
        data
      };
    };
    var Delimiter;
    (function(Delimiter2) {
      Delimiter2[Delimiter2["SemiColon"] = 0] = "SemiColon";
      Delimiter2[Delimiter2["Space"] = 1] = "Space";
    })(Delimiter || (Delimiter = {}));
    var split = function(rawFormats, delimiter) {
      if (delimiter === Delimiter.SemiColon) {
        return rawFormats.replace(/;$/, "").split(";");
      } else {
        return rawFormats.split(" ");
      }
    };
    var buildBasicSettingsDataset = function(editor, settingName, defaults2, delimiter) {
      var rawFormats = editor.getParam(settingName, defaults2, "string");
      var data = process2(split(rawFormats, delimiter));
      return {
        type: "basic",
        data
      };
    };
    var alignMenuItems = [
      {
        title: "Left",
        icon: "align-left",
        format: "alignleft",
        command: "JustifyLeft"
      },
      {
        title: "Center",
        icon: "align-center",
        format: "aligncenter",
        command: "JustifyCenter"
      },
      {
        title: "Right",
        icon: "align-right",
        format: "alignright",
        command: "JustifyRight"
      },
      {
        title: "Justify",
        icon: "align-justify",
        format: "alignjustify",
        command: "JustifyFull"
      }
    ];
    var getSpec$4 = function(editor) {
      var getMatchingValue = function() {
        return find$5(alignMenuItems, function(item2) {
          return editor.formatter.match(item2.format);
        });
      };
      var isSelectedFor = function(format3) {
        return function() {
          return editor.formatter.match(format3);
        };
      };
      var getPreviewFor = function(_format) {
        return Optional.none;
      };
      var updateSelectMenuIcon = function(comp) {
        var match2 = getMatchingValue();
        var alignment = match2.fold(constant$1("left"), function(item2) {
          return item2.title.toLowerCase();
        });
        emitWith(comp, updateMenuIcon, { icon: "align-" + alignment });
      };
      var dataset2 = buildBasicStaticDataset(alignMenuItems);
      var onAction = function(rawItem) {
        return function() {
          return find$5(alignMenuItems, function(item2) {
            return item2.format === rawItem.format;
          }).each(function(item2) {
            return editor.execCommand(item2.command);
          });
        };
      };
      return {
        tooltip: "Align",
        text: Optional.none(),
        icon: Optional.some("align-left"),
        isSelectedFor,
        getCurrentValue: Optional.none,
        getPreviewFor,
        onAction,
        updateText: updateSelectMenuIcon,
        dataset: dataset2,
        shouldHide: false,
        isInvalid: function(item2) {
          return !editor.formatter.canApply(item2.format);
        }
      };
    };
    var createAlignSelect = function(editor, backstage) {
      return createSelectButton(editor, backstage, getSpec$4(editor));
    };
    var alignSelectMenu = function(editor, backstage) {
      var menuItems = createMenuItems(editor, backstage, getSpec$4(editor));
      editor.ui.registry.addNestedMenuItem("align", {
        text: backstage.shared.providers.translate("Align"),
        getSubmenuItems: function() {
          return menuItems.items.validateItems(menuItems.getStyleItems());
        }
      });
    };
    var defaultFontsFormats = "Andale Mono=andale mono,monospace;Arial=arial,helvetica,sans-serif;Arial Black=arial black,sans-serif;Book Antiqua=book antiqua,palatino,serif;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier,monospace;Georgia=georgia,palatino,serif;Helvetica=helvetica,arial,sans-serif;Impact=impact,sans-serif;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco,monospace;Times New Roman=times new roman,times,serif;Trebuchet MS=trebuchet ms,geneva,sans-serif;Verdana=verdana,geneva,sans-serif;Webdings=webdings;Wingdings=wingdings,zapf dingbats";
    var systemStackFonts = [
      "-apple-system",
      "Segoe UI",
      "Roboto",
      "Helvetica Neue",
      "sans-serif"
    ];
    var splitFonts = function(fontFamily) {
      var fonts = fontFamily.split(/\s*,\s*/);
      return map$2(fonts, function(font) {
        return font.replace(/^['"]+|['"]+$/g, "");
      });
    };
    var isSystemFontStack = function(fontFamily) {
      var matchesSystemStack = function() {
        var fonts = splitFonts(fontFamily.toLowerCase());
        return forall(systemStackFonts, function(font) {
          return fonts.indexOf(font.toLowerCase()) > -1;
        });
      };
      return fontFamily.indexOf("-apple-system") === 0 && matchesSystemStack();
    };
    var getSpec$3 = function(editor) {
      var systemFont = "System Font";
      var getMatchingValue = function() {
        var getFirstFont = function(fontFamily2) {
          return fontFamily2 ? splitFonts(fontFamily2)[0] : "";
        };
        var fontFamily = editor.queryCommandValue("FontName");
        var items = dataset2.data;
        var font = fontFamily ? fontFamily.toLowerCase() : "";
        var matchOpt = find$5(items, function(item2) {
          var format3 = item2.format;
          return format3.toLowerCase() === font || getFirstFont(format3).toLowerCase() === getFirstFont(font).toLowerCase();
        }).orThunk(function() {
          return someIf(isSystemFontStack(font), {
            title: systemFont,
            format: font
          });
        });
        return {
          matchOpt,
          font: fontFamily
        };
      };
      var isSelectedFor = function(item2) {
        return function(valueOpt) {
          return valueOpt.exists(function(value2) {
            return value2.format === item2;
          });
        };
      };
      var getCurrentValue = function() {
        var matchOpt = getMatchingValue().matchOpt;
        return matchOpt;
      };
      var getPreviewFor = function(item2) {
        return function() {
          return Optional.some({
            tag: "div",
            styles: item2.indexOf("dings") === -1 ? { "font-family": item2 } : {}
          });
        };
      };
      var onAction = function(rawItem) {
        return function() {
          editor.undoManager.transact(function() {
            editor.focus();
            editor.execCommand("FontName", false, rawItem.format);
          });
        };
      };
      var updateSelectMenuText = function(comp) {
        var _a2 = getMatchingValue(), matchOpt = _a2.matchOpt, font = _a2.font;
        var text2 = matchOpt.fold(constant$1(font), function(item2) {
          return item2.title;
        });
        emitWith(comp, updateMenuText, { text: text2 });
      };
      var dataset2 = buildBasicSettingsDataset(editor, "font_formats", defaultFontsFormats, Delimiter.SemiColon);
      return {
        tooltip: "Fonts",
        text: Optional.some(systemFont),
        icon: Optional.none(),
        isSelectedFor,
        getCurrentValue,
        getPreviewFor,
        onAction,
        updateText: updateSelectMenuText,
        dataset: dataset2,
        shouldHide: false,
        isInvalid: never
      };
    };
    var createFontSelect = function(editor, backstage) {
      return createSelectButton(editor, backstage, getSpec$3(editor));
    };
    var fontSelectMenu = function(editor, backstage) {
      var menuItems = createMenuItems(editor, backstage, getSpec$3(editor));
      editor.ui.registry.addNestedMenuItem("fontformats", {
        text: backstage.shared.providers.translate("Fonts"),
        getSubmenuItems: function() {
          return menuItems.items.validateItems(menuItems.getStyleItems());
        }
      });
    };
    var defaultFontsizeFormats = "8pt 10pt 12pt 14pt 18pt 24pt 36pt";
    var legacyFontSizes = {
      "8pt": "1",
      "10pt": "2",
      "12pt": "3",
      "14pt": "4",
      "18pt": "5",
      "24pt": "6",
      "36pt": "7"
    };
    var keywordFontSizes = {
      "xx-small": "7pt",
      "x-small": "8pt",
      "small": "10pt",
      "medium": "12pt",
      "large": "14pt",
      "x-large": "18pt",
      "xx-large": "24pt"
    };
    var round3 = function(number2, precision) {
      var factor = Math.pow(10, precision);
      return Math.round(number2 * factor) / factor;
    };
    var toPt = function(fontSize, precision) {
      if (/[0-9.]+px$/.test(fontSize)) {
        return round3(parseInt(fontSize, 10) * 72 / 96, precision || 0) + "pt";
      } else {
        return get$e(keywordFontSizes, fontSize).getOr(fontSize);
      }
    };
    var toLegacy = function(fontSize) {
      return get$e(legacyFontSizes, fontSize).getOr("");
    };
    var getSpec$2 = function(editor) {
      var getMatchingValue = function() {
        var matchOpt = Optional.none();
        var items = dataset2.data;
        var fontSize = editor.queryCommandValue("FontSize");
        if (fontSize) {
          var _loop_1 = function(precision2) {
            var pt2 = toPt(fontSize, precision2);
            var legacy = toLegacy(pt2);
            matchOpt = find$5(items, function(item2) {
              return item2.format === fontSize || item2.format === pt2 || item2.format === legacy;
            });
          };
          for (var precision = 3; matchOpt.isNone() && precision >= 0; precision--) {
            _loop_1(precision);
          }
        }
        return {
          matchOpt,
          size: fontSize
        };
      };
      var isSelectedFor = function(item2) {
        return function(valueOpt) {
          return valueOpt.exists(function(value2) {
            return value2.format === item2;
          });
        };
      };
      var getCurrentValue = function() {
        var matchOpt = getMatchingValue().matchOpt;
        return matchOpt;
      };
      var getPreviewFor = constant$1(Optional.none);
      var onAction = function(rawItem) {
        return function() {
          editor.undoManager.transact(function() {
            editor.focus();
            editor.execCommand("FontSize", false, rawItem.format);
          });
        };
      };
      var updateSelectMenuText = function(comp) {
        var _a2 = getMatchingValue(), matchOpt = _a2.matchOpt, size = _a2.size;
        var text2 = matchOpt.fold(constant$1(size), function(match2) {
          return match2.title;
        });
        emitWith(comp, updateMenuText, { text: text2 });
      };
      var dataset2 = buildBasicSettingsDataset(editor, "fontsize_formats", defaultFontsizeFormats, Delimiter.Space);
      return {
        tooltip: "Font sizes",
        text: Optional.some("12pt"),
        icon: Optional.none(),
        isSelectedFor,
        getPreviewFor,
        getCurrentValue,
        onAction,
        updateText: updateSelectMenuText,
        dataset: dataset2,
        shouldHide: false,
        isInvalid: never
      };
    };
    var createFontsizeSelect = function(editor, backstage) {
      return createSelectButton(editor, backstage, getSpec$2(editor));
    };
    var fontsizeSelectMenu = function(editor, backstage) {
      var menuItems = createMenuItems(editor, backstage, getSpec$2(editor));
      editor.ui.registry.addNestedMenuItem("fontsizes", {
        text: "Font sizes",
        getSubmenuItems: function() {
          return menuItems.items.validateItems(menuItems.getStyleItems());
        }
      });
    };
    var findNearest = function(editor, getStyles) {
      var styles = getStyles();
      var formats = map$2(styles, function(style) {
        return style.format;
      });
      return Optional.from(editor.formatter.closest(formats)).bind(function(fmt) {
        return find$5(styles, function(data) {
          return data.format === fmt;
        });
      }).orThunk(function() {
        return someIf(editor.formatter.match("p"), {
          title: "Paragraph",
          format: "p"
        });
      });
    };
    var defaultBlocks = "Paragraph=p;Heading 1=h1;Heading 2=h2;Heading 3=h3;Heading 4=h4;Heading 5=h5;Heading 6=h6;Preformatted=pre";
    var getSpec$1 = function(editor) {
      var fallbackFormat = "Paragraph";
      var isSelectedFor = function(format3) {
        return function() {
          return editor.formatter.match(format3);
        };
      };
      var getPreviewFor = function(format3) {
        return function() {
          var fmt = editor.formatter.get(format3);
          return Optional.some({
            tag: fmt.length > 0 ? fmt[0].inline || fmt[0].block || "div" : "div",
            styles: editor.dom.parseStyle(editor.formatter.getCssText(format3))
          });
        };
      };
      var updateSelectMenuText = function(comp) {
        var detectedFormat = findNearest(editor, function() {
          return dataset2.data;
        });
        var text2 = detectedFormat.fold(constant$1(fallbackFormat), function(fmt) {
          return fmt.title;
        });
        emitWith(comp, updateMenuText, { text: text2 });
      };
      var dataset2 = buildBasicSettingsDataset(editor, "block_formats", defaultBlocks, Delimiter.SemiColon);
      return {
        tooltip: "Blocks",
        text: Optional.some(fallbackFormat),
        icon: Optional.none(),
        isSelectedFor,
        getCurrentValue: Optional.none,
        getPreviewFor,
        onAction: onActionToggleFormat$1(editor),
        updateText: updateSelectMenuText,
        dataset: dataset2,
        shouldHide: false,
        isInvalid: function(item2) {
          return !editor.formatter.canApply(item2.format);
        }
      };
    };
    var createFormatSelect = function(editor, backstage) {
      return createSelectButton(editor, backstage, getSpec$1(editor));
    };
    var formatSelectMenu = function(editor, backstage) {
      var menuItems = createMenuItems(editor, backstage, getSpec$1(editor));
      editor.ui.registry.addNestedMenuItem("blockformats", {
        text: "Blocks",
        getSubmenuItems: function() {
          return menuItems.items.validateItems(menuItems.getStyleItems());
        }
      });
    };
    var getSpec = function(editor, dataset2) {
      var fallbackFormat = "Paragraph";
      var isSelectedFor = function(format3) {
        return function() {
          return editor.formatter.match(format3);
        };
      };
      var getPreviewFor = function(format3) {
        return function() {
          var fmt = editor.formatter.get(format3);
          return fmt !== void 0 ? Optional.some({
            tag: fmt.length > 0 ? fmt[0].inline || fmt[0].block || "div" : "div",
            styles: editor.dom.parseStyle(editor.formatter.getCssText(format3))
          }) : Optional.none();
        };
      };
      var updateSelectMenuText = function(comp) {
        var getFormatItems = function(fmt) {
          var subs2 = fmt.items;
          return subs2 !== void 0 && subs2.length > 0 ? bind$3(subs2, getFormatItems) : [{
            title: fmt.title,
            format: fmt.format
          }];
        };
        var flattenedItems = bind$3(getStyleFormats(editor), getFormatItems);
        var detectedFormat = findNearest(editor, constant$1(flattenedItems));
        var text2 = detectedFormat.fold(constant$1(fallbackFormat), function(fmt) {
          return fmt.title;
        });
        emitWith(comp, updateMenuText, { text: text2 });
      };
      return {
        tooltip: "Formats",
        text: Optional.some(fallbackFormat),
        icon: Optional.none(),
        isSelectedFor,
        getCurrentValue: Optional.none,
        getPreviewFor,
        onAction: onActionToggleFormat$1(editor),
        updateText: updateSelectMenuText,
        shouldHide: editor.getParam("style_formats_autohide", false, "boolean"),
        isInvalid: function(item2) {
          return !editor.formatter.canApply(item2.format);
        },
        dataset: dataset2
      };
    };
    var createStyleSelect = function(editor, backstage) {
      var dataset2 = __assign({ type: "advanced" }, backstage.styleselect);
      return createSelectButton(editor, backstage, getSpec(editor, dataset2));
    };
    var styleSelectMenu = function(editor, backstage) {
      var dataset2 = __assign({ type: "advanced" }, backstage.styleselect);
      var menuItems = createMenuItems(editor, backstage, getSpec(editor, dataset2));
      editor.ui.registry.addNestedMenuItem("formats", {
        text: "Formats",
        getSubmenuItems: function() {
          return menuItems.items.validateItems(menuItems.getStyleItems());
        }
      });
    };
    var events$3 = function(reflectingConfig, reflectingState) {
      var update = function(component, data) {
        reflectingConfig.updateState.each(function(updateState) {
          var newState = updateState(component, data);
          reflectingState.set(newState);
        });
        reflectingConfig.renderComponents.each(function(renderComponents2) {
          var newComponents = renderComponents2(data, reflectingState.get());
          var newChildren = map$2(newComponents, component.getSystem().build);
          replaceChildren(component, newChildren);
        });
      };
      return derive$2([
        run$1(receive(), function(component, message) {
          var receivingData = message;
          if (!receivingData.universal) {
            var channel = reflectingConfig.channel;
            if (contains$2(receivingData.channels, channel)) {
              update(component, receivingData.data);
            }
          }
        }),
        runOnAttached(function(comp, _se) {
          reflectingConfig.initialData.each(function(rawData) {
            update(comp, rawData);
          });
        })
      ]);
    };
    var ActiveReflecting = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      events: events$3
    });
    var getState = function(component, replaceConfig, reflectState) {
      return reflectState;
    };
    var ReflectingApis = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      getState
    });
    var ReflectingSchema = [
      required$1("channel"),
      option("renderComponents"),
      option("updateState"),
      option("initialData")
    ];
    var init$3 = function() {
      var cell = Cell(Optional.none());
      var clear2 = function() {
        return cell.set(Optional.none());
      };
      var readState = function() {
        return cell.get().getOr("none");
      };
      return {
        readState,
        get: cell.get,
        set: cell.set,
        clear: clear2
      };
    };
    var ReflectingState = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      init: init$3
    });
    var Reflecting = create$7({
      fields: ReflectingSchema,
      name: "reflecting",
      active: ActiveReflecting,
      apis: ReflectingApis,
      state: ReflectingState
    });
    var schema$7 = constant$1([
      required$1("toggleClass"),
      required$1("fetch"),
      onStrictHandler("onExecute"),
      defaulted("getHotspot", Optional.some),
      defaulted("getAnchorOverrides", constant$1({})),
      schema$y(),
      onStrictHandler("onItemExecute"),
      option("lazySink"),
      required$1("dom"),
      onHandler("onOpen"),
      field("splitDropdownBehaviours", [
        Coupling,
        Keying,
        Focusing
      ]),
      defaulted("matchWidth", false),
      defaulted("useMinWidth", false),
      defaulted("eventOrder", {}),
      option("role")
    ].concat(sandboxFields()));
    var arrowPart = required({
      factory: Button2,
      schema: [required$1("dom")],
      name: "arrow",
      defaults: function() {
        return { buttonBehaviours: derive$1([Focusing.revoke()]) };
      },
      overrides: function(detail) {
        return {
          dom: {
            tag: "span",
            attributes: { role: "presentation" }
          },
          action: function(arrow2) {
            arrow2.getSystem().getByUid(detail.uid).each(emitExecute);
          },
          buttonBehaviours: derive$1([Toggling.config({
            toggleOnExecute: false,
            toggleClass: detail.toggleClass
          })])
        };
      }
    });
    var buttonPart = required({
      factory: Button2,
      schema: [required$1("dom")],
      name: "button",
      defaults: function() {
        return { buttonBehaviours: derive$1([Focusing.revoke()]) };
      },
      overrides: function(detail) {
        return {
          dom: {
            tag: "span",
            attributes: { role: "presentation" }
          },
          action: function(btn) {
            btn.getSystem().getByUid(detail.uid).each(function(splitDropdown) {
              detail.onExecute(splitDropdown, btn);
            });
          }
        };
      }
    });
    var parts$3 = constant$1([
      arrowPart,
      buttonPart,
      optional({
        factory: {
          sketch: function(spec) {
            return {
              uid: spec.uid,
              dom: {
                tag: "span",
                styles: { display: "none" },
                attributes: { "aria-hidden": "true" },
                innerHtml: spec.text
              }
            };
          }
        },
        schema: [required$1("text")],
        name: "aria-descriptor"
      }),
      external$1({
        schema: [tieredMenuMarkers()],
        name: "menu",
        defaults: function(detail) {
          return {
            onExecute: function(tmenu, item2) {
              tmenu.getSystem().getByUid(detail.uid).each(function(splitDropdown) {
                detail.onItemExecute(splitDropdown, tmenu, item2);
              });
            }
          };
        }
      }),
      partType$1()
    ]);
    var factory$5 = function(detail, components2, spec, externals) {
      var _a2;
      var switchToMenu = function(sandbox) {
        Composing.getCurrent(sandbox).each(function(current) {
          Highlighting.highlightFirst(current);
          Keying.focusIn(current);
        });
      };
      var action = function(component) {
        var onOpenSync = switchToMenu;
        togglePopup(detail, identity$1, component, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop3);
      };
      var openMenu = function(comp) {
        action(comp);
        return Optional.some(true);
      };
      var executeOnButton = function(comp) {
        var button2 = getPartOrDie(comp, detail, "button");
        emitExecute(button2);
        return Optional.some(true);
      };
      var buttonEvents = __assign(__assign({}, derive$2([runOnAttached(function(component, _simulatedEvent) {
        var ariaDescriptor = getPart(component, detail, "aria-descriptor");
        ariaDescriptor.each(function(descriptor) {
          var descriptorId = generate$6("aria");
          set$8(descriptor.element, "id", descriptorId);
          set$8(component.element, "aria-describedby", descriptorId);
        });
      })])), events$a(Optional.some(action)));
      var apis = {
        repositionMenus: function(comp) {
          if (Toggling.isOn(comp)) {
            repositionMenus(comp);
          }
        }
      };
      return {
        uid: detail.uid,
        dom: detail.dom,
        components: components2,
        apis,
        eventOrder: __assign(__assign({}, detail.eventOrder), (_a2 = {}, _a2[execute$5()] = [
          "disabling",
          "toggling",
          "alloy.base.behaviour"
        ], _a2)),
        events: buttonEvents,
        behaviours: augment(detail.splitDropdownBehaviours, [
          Coupling.config({
            others: {
              sandbox: function(hotspot) {
                var arrow2 = getPartOrDie(hotspot, detail, "arrow");
                var extras = {
                  onOpen: function() {
                    Toggling.on(arrow2);
                    Toggling.on(hotspot);
                  },
                  onClose: function() {
                    Toggling.off(arrow2);
                    Toggling.off(hotspot);
                  }
                };
                return makeSandbox$1(detail, hotspot, extras);
              }
            }
          }),
          Keying.config({
            mode: "special",
            onSpace: executeOnButton,
            onEnter: executeOnButton,
            onDown: openMenu
          }),
          Focusing.config({}),
          Toggling.config({
            toggleOnExecute: false,
            aria: { mode: "expanded" }
          })
        ]),
        domModification: {
          attributes: {
            "role": detail.role.getOr("button"),
            "aria-haspopup": true
          }
        }
      };
    };
    var SplitDropdown = composite({
      name: "SplitDropdown",
      configFields: schema$7(),
      partFields: parts$3(),
      factory: factory$5,
      apis: {
        repositionMenus: function(apis, comp) {
          return apis.repositionMenus(comp);
        }
      }
    });
    var getButtonApi = function(component) {
      return {
        isDisabled: function() {
          return Disabling.isDisabled(component);
        },
        setDisabled: function(state) {
          return Disabling.set(component, state);
        }
      };
    };
    var getToggleApi = function(component) {
      return {
        setActive: function(state) {
          Toggling.set(component, state);
        },
        isActive: function() {
          return Toggling.isOn(component);
        },
        isDisabled: function() {
          return Disabling.isDisabled(component);
        },
        setDisabled: function(state) {
          return Disabling.set(component, state);
        }
      };
    };
    var getTooltipAttributes = function(tooltip, providersBackstage) {
      return tooltip.map(function(tooltip2) {
        return {
          "aria-label": providersBackstage.translate(tooltip2),
          "title": providersBackstage.translate(tooltip2)
        };
      }).getOr({});
    };
    var focusButtonEvent = generate$6("focus-button");
    var renderCommonStructure = function(icon, text2, tooltip, receiver, behaviours2, providersBackstage) {
      var _d;
      return {
        dom: {
          tag: "button",
          classes: ["tox-tbtn"].concat(text2.isSome() ? ["tox-tbtn--select"] : []),
          attributes: getTooltipAttributes(tooltip, providersBackstage)
        },
        components: componentRenderPipeline([
          icon.map(function(iconName) {
            return renderIconFromPack(iconName, providersBackstage.icons);
          }),
          text2.map(function(text3) {
            return renderLabel$1(text3, "tox-tbtn", providersBackstage);
          })
        ]),
        eventOrder: (_d = {}, _d[mousedown()] = [
          "focusing",
          "alloy.base.behaviour",
          "common-button-display-events"
        ], _d),
        buttonBehaviours: derive$1([
          DisablingConfigs.toolbarButton(providersBackstage.isDisabled),
          receivingConfig(),
          config("common-button-display-events", [run$1(mousedown(), function(button2, se2) {
            se2.event.prevent();
            emit(button2, focusButtonEvent);
          })])
        ].concat(receiver.map(function(r3) {
          return Reflecting.config({
            channel: r3,
            initialData: {
              icon,
              text: text2
            },
            renderComponents: function(data, _state) {
              return componentRenderPipeline([
                data.icon.map(function(iconName) {
                  return renderIconFromPack(iconName, providersBackstage.icons);
                }),
                data.text.map(function(text3) {
                  return renderLabel$1(text3, "tox-tbtn", providersBackstage);
                })
              ]);
            }
          });
        }).toArray()).concat(behaviours2.getOr([])))
      };
    };
    var renderFloatingToolbarButton = function(spec, backstage, identifyButtons2, attributes) {
      var sharedBackstage = backstage.shared;
      return FloatingToolbarButton.sketch({
        lazySink: sharedBackstage.getSink,
        fetch: function() {
          return Future.nu(function(resolve2) {
            resolve2(map$2(identifyButtons2(spec.items), renderToolbarGroup));
          });
        },
        markers: { toggledClass: "tox-tbtn--enabled" },
        parts: {
          button: renderCommonStructure(spec.icon, spec.text, spec.tooltip, Optional.none(), Optional.none(), sharedBackstage.providers),
          toolbar: {
            dom: {
              tag: "div",
              classes: ["tox-toolbar__overflow"],
              attributes
            }
          }
        }
      });
    };
    var renderCommonToolbarButton = function(spec, specialisation, providersBackstage) {
      var editorOffCell = Cell(noop3);
      var structure = renderCommonStructure(spec.icon, spec.text, spec.tooltip, Optional.none(), Optional.none(), providersBackstage);
      return Button2.sketch({
        dom: structure.dom,
        components: structure.components,
        eventOrder: toolbarButtonEventOrder,
        buttonBehaviours: derive$1([
          config("toolbar-button-events", [
            onToolbarButtonExecute({
              onAction: spec.onAction,
              getApi: specialisation.getApi
            }),
            onControlAttached(specialisation, editorOffCell),
            onControlDetached(specialisation, editorOffCell)
          ]),
          DisablingConfigs.toolbarButton(function() {
            return spec.disabled || providersBackstage.isDisabled();
          }),
          receivingConfig()
        ].concat(specialisation.toolbarButtonBehaviours))
      });
    };
    var renderToolbarButton = function(spec, providersBackstage) {
      return renderToolbarButtonWith(spec, providersBackstage, []);
    };
    var renderToolbarButtonWith = function(spec, providersBackstage, bonusEvents) {
      return renderCommonToolbarButton(spec, {
        toolbarButtonBehaviours: [].concat(bonusEvents.length > 0 ? [config("toolbarButtonWith", bonusEvents)] : []),
        getApi: getButtonApi,
        onSetup: spec.onSetup
      }, providersBackstage);
    };
    var renderToolbarToggleButton = function(spec, providersBackstage) {
      return renderToolbarToggleButtonWith(spec, providersBackstage, []);
    };
    var renderToolbarToggleButtonWith = function(spec, providersBackstage, bonusEvents) {
      return deepMerge(renderCommonToolbarButton(spec, {
        toolbarButtonBehaviours: [
          Replacing.config({}),
          Toggling.config({
            toggleClass: "tox-tbtn--enabled",
            aria: { mode: "pressed" },
            toggleOnExecute: false
          })
        ].concat(bonusEvents.length > 0 ? [config("toolbarToggleButtonWith", bonusEvents)] : []),
        getApi: getToggleApi,
        onSetup: spec.onSetup
      }, providersBackstage));
    };
    var fetchChoices = function(getApi2, spec, providersBackstage) {
      return function(comp) {
        return Future.nu(function(callback2) {
          return spec.fetch(callback2);
        }).map(function(items) {
          return Optional.from(createTieredDataFrom(deepMerge(createPartialChoiceMenu(generate$6("menu-value"), items, function(value2) {
            spec.onItemAction(getApi2(comp), value2);
          }, spec.columns, spec.presets, ItemResponse$1.CLOSE_ON_EXECUTE, spec.select.getOr(never), providersBackstage), {
            movement: deriveMenuMovement(spec.columns, spec.presets),
            menuBehaviours: SimpleBehaviours.unnamedEvents(spec.columns !== "auto" ? [] : [runOnAttached(function(comp2, _se) {
              detectSize(comp2, 4, classForPreset(spec.presets)).each(function(_d) {
                var numRows = _d.numRows, numColumns = _d.numColumns;
                Keying.setGridSize(comp2, numRows, numColumns);
              });
            })])
          })));
        });
      };
    };
    var renderSplitButton = function(spec, sharedBackstage) {
      var _d;
      var displayChannel = generate$6("channel-update-split-dropdown-display");
      var getApi2 = function(comp) {
        return {
          isDisabled: function() {
            return Disabling.isDisabled(comp);
          },
          setDisabled: function(state) {
            return Disabling.set(comp, state);
          },
          setIconFill: function(id2, value2) {
            descendant(comp.element, 'svg path[id="' + id2 + '"], rect[id="' + id2 + '"]').each(function(underlinePath) {
              set$8(underlinePath, "fill", value2);
            });
          },
          setIconStroke: function(id2, value2) {
            descendant(comp.element, 'svg path[id="' + id2 + '"], rect[id="' + id2 + '"]').each(function(underlinePath) {
              set$8(underlinePath, "stroke", value2);
            });
          },
          setActive: function(state) {
            set$8(comp.element, "aria-pressed", state);
            descendant(comp.element, "span").each(function(button2) {
              comp.getSystem().getByDom(button2).each(function(buttonComp) {
                return Toggling.set(buttonComp, state);
              });
            });
          },
          isActive: function() {
            return descendant(comp.element, "span").exists(function(button2) {
              return comp.getSystem().getByDom(button2).exists(Toggling.isOn);
            });
          }
        };
      };
      var editorOffCell = Cell(noop3);
      var specialisation = {
        getApi: getApi2,
        onSetup: spec.onSetup
      };
      return SplitDropdown.sketch({
        dom: {
          tag: "div",
          classes: ["tox-split-button"],
          attributes: __assign({ "aria-pressed": false }, getTooltipAttributes(spec.tooltip, sharedBackstage.providers))
        },
        onExecute: function(button2) {
          spec.onAction(getApi2(button2));
        },
        onItemExecute: function(_a2, _b, _c) {
        },
        splitDropdownBehaviours: derive$1([
          DisablingConfigs.splitButton(sharedBackstage.providers.isDisabled),
          receivingConfig(),
          config("split-dropdown-events", [
            run$1(focusButtonEvent, Focusing.focus),
            onControlAttached(specialisation, editorOffCell),
            onControlDetached(specialisation, editorOffCell)
          ]),
          Unselecting.config({})
        ]),
        eventOrder: (_d = {}, _d[attachedToDom()] = [
          "alloy.base.behaviour",
          "split-dropdown-events"
        ], _d),
        toggleClass: "tox-tbtn--enabled",
        lazySink: sharedBackstage.getSink,
        fetch: fetchChoices(getApi2, spec, sharedBackstage.providers),
        parts: { menu: part(false, spec.columns, spec.presets) },
        components: [
          SplitDropdown.parts.button(renderCommonStructure(spec.icon, spec.text, Optional.none(), Optional.some(displayChannel), Optional.some([Toggling.config({
            toggleClass: "tox-tbtn--enabled",
            toggleOnExecute: false
          })]), sharedBackstage.providers)),
          SplitDropdown.parts.arrow({
            dom: {
              tag: "button",
              classes: [
                "tox-tbtn",
                "tox-split-button__chevron"
              ],
              innerHtml: get$1("chevron-down", sharedBackstage.providers.icons)
            },
            buttonBehaviours: derive$1([
              DisablingConfigs.splitButton(sharedBackstage.providers.isDisabled),
              receivingConfig(),
              addFocusableBehaviour()
            ])
          }),
          SplitDropdown.parts["aria-descriptor"]({ text: sharedBackstage.providers.translate("To open the popup, press Shift+Enter") })
        ]
      });
    };
    var defaultToolbar = [
      {
        name: "history",
        items: [
          "undo",
          "redo"
        ]
      },
      {
        name: "styles",
        items: ["styleselect"]
      },
      {
        name: "formatting",
        items: [
          "bold",
          "italic"
        ]
      },
      {
        name: "alignment",
        items: [
          "alignleft",
          "aligncenter",
          "alignright",
          "alignjustify"
        ]
      },
      {
        name: "indentation",
        items: [
          "outdent",
          "indent"
        ]
      },
      {
        name: "permanent pen",
        items: ["permanentpen"]
      },
      {
        name: "comments",
        items: ["addcomment"]
      }
    ];
    var renderFromBridge = function(bridgeBuilder, render2) {
      return function(spec, extras, editor) {
        var internal2 = bridgeBuilder(spec).mapError(function(errInfo) {
          return formatError(errInfo);
        }).getOrDie();
        return render2(internal2, extras, editor);
      };
    };
    var types = {
      button: renderFromBridge(createToolbarButton, function(s2, extras) {
        return renderToolbarButton(s2, extras.backstage.shared.providers);
      }),
      togglebutton: renderFromBridge(createToggleButton, function(s2, extras) {
        return renderToolbarToggleButton(s2, extras.backstage.shared.providers);
      }),
      menubutton: renderFromBridge(createMenuButton, function(s2, extras) {
        return renderMenuButton(s2, "tox-tbtn", extras.backstage, Optional.none());
      }),
      splitbutton: renderFromBridge(createSplitButton, function(s2, extras) {
        return renderSplitButton(s2, extras.backstage.shared);
      }),
      grouptoolbarbutton: renderFromBridge(createGroupToolbarButton, function(s2, extras, editor) {
        var _a2;
        var buttons = editor.ui.registry.getAll().buttons;
        var identify = function(toolbar) {
          return identifyButtons(editor, {
            buttons,
            toolbar,
            allowToolbarGroups: false
          }, extras, Optional.none());
        };
        var attributes = (_a2 = {}, _a2[Attribute] = extras.backstage.shared.header.isPositionedAtTop() ? AttributeValue.TopToBottom : AttributeValue.BottomToTop, _a2);
        switch (getToolbarMode(editor)) {
          case ToolbarMode.floating:
            return renderFloatingToolbarButton(s2, extras.backstage, identify, attributes);
          default:
            throw new Error("Toolbar groups are only supported when using floating toolbar mode");
        }
      }),
      styleSelectButton: function(editor, extras) {
        return createStyleSelect(editor, extras.backstage);
      },
      fontsizeSelectButton: function(editor, extras) {
        return createFontsizeSelect(editor, extras.backstage);
      },
      fontSelectButton: function(editor, extras) {
        return createFontSelect(editor, extras.backstage);
      },
      formatButton: function(editor, extras) {
        return createFormatSelect(editor, extras.backstage);
      },
      alignMenuButton: function(editor, extras) {
        return createAlignSelect(editor, extras.backstage);
      }
    };
    var extractFrom = function(spec, extras, editor) {
      return get$e(types, spec.type).fold(function() {
        console.error("skipping button defined by", spec);
        return Optional.none();
      }, function(render2) {
        return Optional.some(render2(spec, extras, editor));
      });
    };
    var bespokeButtons = {
      styleselect: types.styleSelectButton,
      fontsizeselect: types.fontsizeSelectButton,
      fontselect: types.fontSelectButton,
      formatselect: types.formatButton,
      align: types.alignMenuButton
    };
    var removeUnusedDefaults = function(buttons) {
      var filteredItemGroups = map$2(defaultToolbar, function(group2) {
        var items = filter$2(group2.items, function(subItem) {
          return has$2(buttons, subItem) || has$2(bespokeButtons, subItem);
        });
        return {
          name: group2.name,
          items
        };
      });
      return filter$2(filteredItemGroups, function(group2) {
        return group2.items.length > 0;
      });
    };
    var convertStringToolbar = function(strToolbar) {
      var groupsStrings = strToolbar.split("|");
      return map$2(groupsStrings, function(g2) {
        return { items: g2.trim().split(" ") };
      });
    };
    var isToolbarGroupSettingArray = function(toolbar) {
      return isArrayOf(toolbar, function(t3) {
        return has$2(t3, "name") && has$2(t3, "items");
      });
    };
    var createToolbar = function(toolbarConfig) {
      var toolbar = toolbarConfig.toolbar;
      var buttons = toolbarConfig.buttons;
      if (toolbar === false) {
        return [];
      } else if (toolbar === void 0 || toolbar === true) {
        return removeUnusedDefaults(buttons);
      } else if (isString(toolbar)) {
        return convertStringToolbar(toolbar);
      } else if (isToolbarGroupSettingArray(toolbar)) {
        return toolbar;
      } else {
        console.error("Toolbar type should be string, string[], boolean or ToolbarGroup[]");
        return [];
      }
    };
    var lookupButton = function(editor, buttons, toolbarItem, allowToolbarGroups, extras, prefixes) {
      return get$e(buttons, toolbarItem.toLowerCase()).orThunk(function() {
        return prefixes.bind(function(ps) {
          return findMap(ps, function(prefix2) {
            return get$e(buttons, prefix2 + toolbarItem.toLowerCase());
          });
        });
      }).fold(function() {
        return get$e(bespokeButtons, toolbarItem.toLowerCase()).map(function(r3) {
          return r3(editor, extras);
        }).orThunk(function() {
          return Optional.none();
        });
      }, function(spec) {
        if (spec.type === "grouptoolbarbutton" && !allowToolbarGroups) {
          console.warn("Ignoring the '" + toolbarItem + "' toolbar button. Group toolbar buttons are only supported when using floating toolbar mode and cannot be nested.");
          return Optional.none();
        } else {
          return extractFrom(spec, extras, editor);
        }
      });
    };
    var identifyButtons = function(editor, toolbarConfig, extras, prefixes) {
      var toolbarGroups = createToolbar(toolbarConfig);
      var groups = map$2(toolbarGroups, function(group2) {
        var items = bind$3(group2.items, function(toolbarItem) {
          return toolbarItem.trim().length === 0 ? [] : lookupButton(editor, toolbarConfig.buttons, toolbarItem, toolbarConfig.allowToolbarGroups, extras, prefixes).toArray();
        });
        return {
          title: Optional.from(editor.translate(group2.name)),
          items
        };
      });
      return filter$2(groups, function(group2) {
        return group2.items.length > 0;
      });
    };
    var setToolbar = function(editor, uiComponents, rawUiConfig, backstage) {
      var comp = uiComponents.outerContainer;
      var toolbarConfig = rawUiConfig.toolbar;
      var toolbarButtonsConfig = rawUiConfig.buttons;
      if (isArrayOf(toolbarConfig, isString)) {
        var toolbars = toolbarConfig.map(function(t3) {
          var config2 = {
            toolbar: t3,
            buttons: toolbarButtonsConfig,
            allowToolbarGroups: rawUiConfig.allowToolbarGroups
          };
          return identifyButtons(editor, config2, { backstage }, Optional.none());
        });
        OuterContainer.setToolbars(comp, toolbars);
      } else {
        OuterContainer.setToolbar(comp, identifyButtons(editor, rawUiConfig, { backstage }, Optional.none()));
      }
    };
    var detection = detect$1();
    var isiOS12 = detection.os.isiOS() && detection.os.version.major <= 12;
    var setupEvents$1 = function(editor, uiComponents) {
      var dom2 = editor.dom;
      var contentWindow = editor.getWin();
      var initialDocEle = editor.getDoc().documentElement;
      var lastWindowDimensions = Cell(SugarPosition(contentWindow.innerWidth, contentWindow.innerHeight));
      var lastDocumentDimensions = Cell(SugarPosition(initialDocEle.offsetWidth, initialDocEle.offsetHeight));
      var resizeWindow = function() {
        var outer = lastWindowDimensions.get();
        if (outer.left !== contentWindow.innerWidth || outer.top !== contentWindow.innerHeight) {
          lastWindowDimensions.set(SugarPosition(contentWindow.innerWidth, contentWindow.innerHeight));
          fireResizeContent(editor);
        }
      };
      var resizeDocument = function() {
        var docEle = editor.getDoc().documentElement;
        var inner = lastDocumentDimensions.get();
        if (inner.left !== docEle.offsetWidth || inner.top !== docEle.offsetHeight) {
          lastDocumentDimensions.set(SugarPosition(docEle.offsetWidth, docEle.offsetHeight));
          fireResizeContent(editor);
        }
      };
      var scroll = function(e2) {
        return fireScrollContent(editor, e2);
      };
      dom2.bind(contentWindow, "resize", resizeWindow);
      dom2.bind(contentWindow, "scroll", scroll);
      var elementLoad = capture(SugarElement.fromDom(editor.getBody()), "load", resizeDocument);
      var mothership = uiComponents.uiMothership.element;
      editor.on("hide", function() {
        set$7(mothership, "display", "none");
      });
      editor.on("show", function() {
        remove$6(mothership, "display");
      });
      editor.on("NodeChange", resizeDocument);
      editor.on("remove", function() {
        elementLoad.unbind();
        dom2.unbind(contentWindow, "resize", resizeWindow);
        dom2.unbind(contentWindow, "scroll", scroll);
        contentWindow = null;
      });
    };
    var render$1 = function(editor, uiComponents, rawUiConfig, backstage, args) {
      var lastToolbarWidth = Cell(0);
      var outerContainer = uiComponents.outerContainer;
      iframe(editor);
      var eTargetNode = SugarElement.fromDom(args.targetNode);
      var uiRoot = getContentContainer(getRootNode(eTargetNode));
      attachSystemAfter(eTargetNode, uiComponents.mothership);
      attachSystem(uiRoot, uiComponents.uiMothership);
      editor.on("PostRender", function() {
        setToolbar(editor, uiComponents, rawUiConfig, backstage);
        lastToolbarWidth.set(editor.getWin().innerWidth);
        OuterContainer.setMenubar(outerContainer, identifyMenus(editor, rawUiConfig));
        OuterContainer.setSidebar(outerContainer, rawUiConfig.sidebar);
        setupEvents$1(editor, uiComponents);
      });
      var socket = OuterContainer.getSocket(outerContainer).getOrDie("Could not find expected socket element");
      if (isiOS12) {
        setAll(socket.element, {
          "overflow": "scroll",
          "-webkit-overflow-scrolling": "touch"
        });
        var limit = first(function() {
          editor.fire("ScrollContent");
        }, 20);
        var unbinder = bind(socket.element, "scroll", limit.throttle);
        editor.on("remove", unbinder.unbind);
      }
      setupReadonlyModeSwitch(editor, uiComponents);
      editor.addCommand("ToggleSidebar", function(_ui, value2) {
        OuterContainer.toggleSidebar(outerContainer, value2);
        editor.fire("ToggleSidebar");
      });
      editor.addQueryValueHandler("ToggleSidebar", function() {
        return OuterContainer.whichSidebar(outerContainer);
      });
      var toolbarMode = getToolbarMode(editor);
      var refreshDrawer = function() {
        OuterContainer.refreshToolbar(uiComponents.outerContainer);
      };
      if (toolbarMode === ToolbarMode.sliding || toolbarMode === ToolbarMode.floating) {
        editor.on("ResizeWindow ResizeEditor ResizeContent", function() {
          var width2 = editor.getWin().innerWidth;
          if (width2 !== lastToolbarWidth.get()) {
            refreshDrawer();
            lastToolbarWidth.set(width2);
          }
        });
      }
      var api2 = {
        enable: function() {
          broadcastReadonly(uiComponents, false);
        },
        disable: function() {
          broadcastReadonly(uiComponents, true);
        },
        isDisabled: function() {
          return Disabling.isDisabled(outerContainer);
        }
      };
      return {
        iframeContainer: socket.element.dom,
        editorContainer: outerContainer.element.dom,
        api: api2
      };
    };
    var Iframe = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      render: render$1
    });
    var parseToInt = function(val) {
      var re2 = /^[0-9\.]+(|px)$/i;
      if (re2.test("" + val)) {
        return Optional.some(parseInt("" + val, 10));
      }
      return Optional.none();
    };
    var numToPx = function(val) {
      return isNumber2(val) ? val + "px" : val;
    };
    var calcCappedSize = function(size, minSize, maxSize) {
      var minOverride = minSize.filter(function(min3) {
        return size < min3;
      });
      var maxOverride = maxSize.filter(function(max3) {
        return size > max3;
      });
      return minOverride.or(maxOverride).getOr(size);
    };
    var getHeight = function(editor) {
      var baseHeight = getHeightSetting(editor);
      var minHeight = getMinHeightSetting(editor);
      var maxHeight = getMaxHeightSetting(editor);
      return parseToInt(baseHeight).map(function(height2) {
        return calcCappedSize(height2, minHeight, maxHeight);
      });
    };
    var getHeightWithFallback = function(editor) {
      var height2 = getHeight(editor);
      return height2.getOr(getHeightSetting(editor));
    };
    var getWidth = function(editor) {
      var baseWidth = getWidthSetting(editor);
      var minWidth = getMinWidthSetting(editor);
      var maxWidth = getMaxWidthSetting(editor);
      return parseToInt(baseWidth).map(function(width2) {
        return calcCappedSize(width2, minWidth, maxWidth);
      });
    };
    var getWidthWithFallback = function(editor) {
      var width2 = getWidth(editor);
      return width2.getOr(getWidthSetting(editor));
    };
    var InlineHeader = function(editor, targetElm, uiComponents, backstage, floatContainer) {
      var uiMothership = uiComponents.uiMothership, outerContainer = uiComponents.outerContainer;
      var DOM = global$b.DOM;
      var useFixedToolbarContainer = useFixedContainer(editor);
      var isSticky = isStickyToolbar(editor);
      var editorMaxWidthOpt = getMaxWidthSetting(editor).or(getWidth(editor));
      var headerBackstage = backstage.shared.header;
      var isPositionedAtTop = headerBackstage.isPositionedAtTop;
      var toolbarMode = getToolbarMode(editor);
      var isSplitToolbar = toolbarMode === ToolbarMode.sliding || toolbarMode === ToolbarMode.floating;
      var visible = Cell(false);
      var isVisible3 = function() {
        return visible.get() && !editor.removed;
      };
      var calcToolbarOffset = function(toolbar) {
        return isSplitToolbar ? toolbar.fold(constant$1(0), function(tbar) {
          return tbar.components().length > 1 ? get$b(tbar.components()[1].element) : 0;
        }) : 0;
      };
      var calcMode = function(container) {
        switch (getToolbarLocation(editor)) {
          case ToolbarLocation.auto:
            var toolbar_1 = OuterContainer.getToolbar(outerContainer);
            var offset3 = calcToolbarOffset(toolbar_1);
            var toolbarHeight = get$b(container.element) - offset3;
            var targetBounds = box$1(targetElm);
            var roomAtTop = targetBounds.y > toolbarHeight;
            if (roomAtTop) {
              return "top";
            } else {
              var doc = documentElement(targetElm);
              var docHeight = Math.max(doc.dom.scrollHeight, get$b(doc));
              var roomAtBottom = targetBounds.bottom < docHeight - toolbarHeight;
              if (roomAtBottom) {
                return "bottom";
              } else {
                var winBounds = win();
                var isRoomAtBottomViewport = winBounds.bottom < targetBounds.bottom - toolbarHeight;
                return isRoomAtBottomViewport ? "bottom" : "top";
              }
            }
          case ToolbarLocation.bottom:
            return "bottom";
          case ToolbarLocation.top:
          default:
            return "top";
        }
      };
      var setupMode = function(mode) {
        var container = floatContainer.get();
        Docking.setModes(container, [mode]);
        headerBackstage.setDockingMode(mode);
        var verticalDir = isPositionedAtTop() ? AttributeValue.TopToBottom : AttributeValue.BottomToTop;
        set$8(container.element, Attribute, verticalDir);
      };
      var updateChromeWidth = function() {
        var maxWidth = editorMaxWidthOpt.getOrThunk(function() {
          var bodyMargin = parseToInt(get$c(body(), "margin-left")).getOr(0);
          return get$a(body()) - absolute$3(targetElm).left + bodyMargin;
        });
        set$7(floatContainer.get().element, "max-width", maxWidth + "px");
      };
      var updateChromePosition = function() {
        var toolbar = OuterContainer.getToolbar(outerContainer);
        var offset3 = calcToolbarOffset(toolbar);
        var targetBounds = box$1(targetElm);
        var top3 = isPositionedAtTop() ? Math.max(targetBounds.y - get$b(floatContainer.get().element) + offset3, 0) : targetBounds.bottom;
        setAll(outerContainer.element, {
          position: "absolute",
          top: Math.round(top3) + "px",
          left: Math.round(targetBounds.x) + "px"
        });
      };
      var repositionPopups$1 = function() {
        uiMothership.broadcastOn([repositionPopups()], {});
      };
      var updateChromeUi = function(resetDocking) {
        if (resetDocking === void 0) {
          resetDocking = false;
        }
        if (!isVisible3()) {
          return;
        }
        if (!useFixedToolbarContainer) {
          updateChromeWidth();
        }
        if (isSplitToolbar) {
          OuterContainer.refreshToolbar(outerContainer);
        }
        if (!useFixedToolbarContainer) {
          updateChromePosition();
        }
        if (isSticky) {
          var floatContainerComp = floatContainer.get();
          resetDocking ? Docking.reset(floatContainerComp) : Docking.refresh(floatContainerComp);
        }
        repositionPopups$1();
      };
      var updateMode = function(updateUi) {
        if (updateUi === void 0) {
          updateUi = true;
        }
        if (useFixedToolbarContainer || !isSticky || !isVisible3()) {
          return;
        }
        var currentMode = headerBackstage.getDockingMode();
        var newMode = calcMode(floatContainer.get());
        if (newMode !== currentMode) {
          setupMode(newMode);
          if (updateUi) {
            updateChromeUi(true);
          }
        }
      };
      var show2 = function() {
        visible.set(true);
        set$7(outerContainer.element, "display", "flex");
        DOM.addClass(editor.getBody(), "mce-edit-focus");
        remove$6(uiMothership.element, "display");
        updateMode(false);
        updateChromeUi();
      };
      var hide2 = function() {
        visible.set(false);
        if (uiComponents.outerContainer) {
          set$7(outerContainer.element, "display", "none");
          DOM.removeClass(editor.getBody(), "mce-edit-focus");
        }
        set$7(uiMothership.element, "display", "none");
      };
      return {
        isVisible: isVisible3,
        isPositionedAtTop,
        show: show2,
        hide: hide2,
        update: updateChromeUi,
        updateMode,
        repositionPopups: repositionPopups$1
      };
    };
    var getTargetPosAndBounds = function(targetElm, isToolbarTop) {
      var bounds2 = box$1(targetElm);
      return {
        pos: isToolbarTop ? bounds2.y : bounds2.bottom,
        bounds: bounds2
      };
    };
    var setupEvents = function(editor, targetElm, ui2, toolbarPersist) {
      var prevPosAndBounds = Cell(getTargetPosAndBounds(targetElm, ui2.isPositionedAtTop()));
      var resizeContent = function(e2) {
        var _a2 = getTargetPosAndBounds(targetElm, ui2.isPositionedAtTop()), pos = _a2.pos, bounds2 = _a2.bounds;
        var _b = prevPosAndBounds.get(), prevPos = _b.pos, prevBounds = _b.bounds;
        var hasResized = bounds2.height !== prevBounds.height || bounds2.width !== prevBounds.width;
        prevPosAndBounds.set({
          pos,
          bounds: bounds2
        });
        if (hasResized) {
          fireResizeContent(editor, e2);
        }
        if (ui2.isVisible()) {
          if (prevPos !== pos) {
            ui2.update(true);
          } else if (hasResized) {
            ui2.updateMode();
            ui2.repositionPopups();
          }
        }
      };
      if (!toolbarPersist) {
        editor.on("activate", ui2.show);
        editor.on("deactivate", ui2.hide);
      }
      editor.on("SkinLoaded ResizeWindow", function() {
        return ui2.update(true);
      });
      editor.on("NodeChange keydown", function(e2) {
        global$f.requestAnimationFrame(function() {
          return resizeContent(e2);
        });
      });
      editor.on("ScrollWindow", function() {
        return ui2.updateMode();
      });
      var elementLoad = unbindable();
      elementLoad.set(capture(SugarElement.fromDom(editor.getBody()), "load", resizeContent));
      editor.on("remove", function() {
        elementLoad.clear();
      });
    };
    var render = function(editor, uiComponents, rawUiConfig, backstage, args) {
      var mothership = uiComponents.mothership, uiMothership = uiComponents.uiMothership, outerContainer = uiComponents.outerContainer;
      var floatContainer = Cell(null);
      var targetElm = SugarElement.fromDom(args.targetNode);
      var ui2 = InlineHeader(editor, targetElm, uiComponents, backstage, floatContainer);
      var toolbarPersist = isToolbarPersist(editor);
      inline(editor);
      var render2 = function() {
        if (floatContainer.get()) {
          ui2.show();
          return;
        }
        floatContainer.set(OuterContainer.getHeader(outerContainer).getOrDie());
        var uiContainer = getUiContainer(editor);
        attachSystem(uiContainer, mothership);
        attachSystem(uiContainer, uiMothership);
        setToolbar(editor, uiComponents, rawUiConfig, backstage);
        OuterContainer.setMenubar(outerContainer, identifyMenus(editor, rawUiConfig));
        ui2.show();
        setupEvents(editor, targetElm, ui2, toolbarPersist);
        editor.nodeChanged();
      };
      var delayedRender = function() {
        return global$f.setEditorTimeout(editor, render2, 0);
      };
      editor.on("show", render2);
      editor.on("hide", ui2.hide);
      if (!toolbarPersist) {
        editor.on("focus", delayedRender);
        editor.on("blur", ui2.hide);
      }
      editor.on("init", function() {
        if (editor.hasFocus() || toolbarPersist) {
          delayedRender();
        }
      });
      setupReadonlyModeSwitch(editor, uiComponents);
      var api2 = {
        show: function() {
          ui2.show();
        },
        hide: function() {
          ui2.hide();
        },
        enable: function() {
          broadcastReadonly(uiComponents, false);
        },
        disable: function() {
          broadcastReadonly(uiComponents, true);
        },
        isDisabled: function() {
          return Disabling.isDisabled(outerContainer);
        }
      };
      return {
        editorContainer: outerContainer.element.dom,
        api: api2
      };
    };
    var Inline = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      render
    });
    var showContextToolbarEvent = "contexttoolbar-show";
    var hideContextToolbarEvent = "contexttoolbar-hide";
    var getFormApi = function(input2) {
      return {
        hide: function() {
          return emit(input2, sandboxClose());
        },
        getValue: function() {
          return Representing.getValue(input2);
        }
      };
    };
    var runOnExecute = function(memInput, original2) {
      return run$1(internalToolbarButtonExecute, function(comp, se2) {
        var input2 = memInput.get(comp);
        var formApi = getFormApi(input2);
        original2.onAction(formApi, se2.event.buttonApi);
      });
    };
    var renderContextButton = function(memInput, button2, extras) {
      var _a2 = button2.original;
      _a2.primary;
      var rest = __rest(_a2, ["primary"]);
      var bridged = getOrDie(createToolbarButton(__assign(__assign({}, rest), {
        type: "button",
        onAction: noop3
      })));
      return renderToolbarButtonWith(bridged, extras.backstage.shared.providers, [runOnExecute(memInput, button2)]);
    };
    var renderContextToggleButton = function(memInput, button2, extras) {
      var _a2 = button2.original;
      _a2.primary;
      var rest = __rest(_a2, ["primary"]);
      var bridged = getOrDie(createToggleButton(__assign(__assign({}, rest), {
        type: "togglebutton",
        onAction: noop3
      })));
      return renderToolbarToggleButtonWith(bridged, extras.backstage.shared.providers, [runOnExecute(memInput, button2)]);
    };
    var generateOne = function(memInput, button2, providersBackstage) {
      var extras = { backstage: { shared: { providers: providersBackstage } } };
      if (button2.type === "contextformtogglebutton") {
        return renderContextToggleButton(memInput, button2, extras);
      } else {
        return renderContextButton(memInput, button2, extras);
      }
    };
    var generate = function(memInput, buttons, providersBackstage) {
      var mementos = map$2(buttons, function(button2) {
        return record(generateOne(memInput, button2, providersBackstage));
      });
      var asSpecs = function() {
        return map$2(mementos, function(mem) {
          return mem.asSpec();
        });
      };
      var findPrimary = function(compInSystem) {
        return findMap(buttons, function(button2, i2) {
          if (button2.primary) {
            return Optional.from(mementos[i2]).bind(function(mem) {
              return mem.getOpt(compInSystem);
            }).filter(not(Disabling.isDisabled));
          } else {
            return Optional.none();
          }
        });
      };
      return {
        asSpecs,
        findPrimary
      };
    };
    var buildInitGroups = function(ctx, providers) {
      var inputAttributes = ctx.label.fold(function() {
        return {};
      }, function(label) {
        return { "aria-label": label };
      });
      var memInput = record(Input.sketch({
        inputClasses: [
          "tox-toolbar-textfield",
          "tox-toolbar-nav-js"
        ],
        data: ctx.initValue(),
        inputAttributes,
        selectOnFocus: true,
        inputBehaviours: derive$1([Keying.config({
          mode: "special",
          onEnter: function(input2) {
            return commands.findPrimary(input2).map(function(primary) {
              emitExecute(primary);
              return true;
            });
          },
          onLeft: function(comp, se2) {
            se2.cut();
            return Optional.none();
          },
          onRight: function(comp, se2) {
            se2.cut();
            return Optional.none();
          }
        })])
      }));
      var commands = generate(memInput, ctx.commands, providers);
      return [
        {
          title: Optional.none(),
          items: [memInput.asSpec()]
        },
        {
          title: Optional.none(),
          items: commands.asSpecs()
        }
      ];
    };
    var renderContextForm = function(toolbarType, ctx, providers) {
      return renderToolbar({
        type: toolbarType,
        uid: generate$6("context-toolbar"),
        initGroups: buildInitGroups(ctx, providers),
        onEscape: Optional.none,
        cyclicKeying: true,
        providers
      });
    };
    var ContextForm = {
      renderContextForm,
      buildInitGroups
    };
    var isVerticalOverlap = function(a2, b3, threshold) {
      if (threshold === void 0) {
        threshold = 0.01;
      }
      return b3.bottom - a2.y >= threshold && a2.bottom - b3.y >= threshold;
    };
    var getRangeRect = function(rng) {
      var rect2 = rng.getBoundingClientRect();
      if (rect2.height <= 0 && rect2.width <= 0) {
        var leaf$1 = leaf(SugarElement.fromDom(rng.startContainer), rng.startOffset).element;
        var elm = isText$1(leaf$1) ? parent(leaf$1) : Optional.some(leaf$1);
        return elm.filter(isElement$2).map(function(e2) {
          return e2.dom.getBoundingClientRect();
        }).getOr(rect2);
      } else {
        return rect2;
      }
    };
    var getSelectionBounds = function(editor) {
      var rng = editor.selection.getRng();
      var rect2 = getRangeRect(rng);
      if (editor.inline) {
        var scroll_1 = get$9();
        return bounds(scroll_1.left + rect2.left, scroll_1.top + rect2.top, rect2.width, rect2.height);
      } else {
        var bodyPos = absolute$2(SugarElement.fromDom(editor.getBody()));
        return bounds(bodyPos.x + rect2.left, bodyPos.y + rect2.top, rect2.width, rect2.height);
      }
    };
    var getAnchorElementBounds = function(editor, lastElement) {
      return lastElement.filter(inBody).map(absolute$2).getOrThunk(function() {
        return getSelectionBounds(editor);
      });
    };
    var getHorizontalBounds = function(contentAreaBox, viewportBounds, margin) {
      var x2 = Math.max(contentAreaBox.x + margin, viewportBounds.x);
      var right3 = Math.min(contentAreaBox.right - margin, viewportBounds.right);
      return {
        x: x2,
        width: right3 - x2
      };
    };
    var getVerticalBounds = function(editor, contentAreaBox, viewportBounds, isToolbarLocationTop, toolbarType, margin) {
      var container = SugarElement.fromDom(editor.getContainer());
      var header = descendant(container, ".tox-editor-header").getOr(container);
      var headerBox = box$1(header);
      var isToolbarBelowContentArea = headerBox.y >= contentAreaBox.bottom;
      var isToolbarAbove = isToolbarLocationTop && !isToolbarBelowContentArea;
      if (editor.inline && isToolbarAbove) {
        return {
          y: Math.max(headerBox.bottom + margin, viewportBounds.y),
          bottom: viewportBounds.bottom
        };
      }
      if (editor.inline && !isToolbarAbove) {
        return {
          y: viewportBounds.y,
          bottom: Math.min(headerBox.y - margin, viewportBounds.bottom)
        };
      }
      var containerBounds = toolbarType === "line" ? box$1(container) : contentAreaBox;
      if (isToolbarAbove) {
        return {
          y: Math.max(headerBox.bottom + margin, viewportBounds.y),
          bottom: Math.min(containerBounds.bottom - margin, viewportBounds.bottom)
        };
      }
      return {
        y: Math.max(containerBounds.y + margin, viewportBounds.y),
        bottom: Math.min(headerBox.y - margin, viewportBounds.bottom)
      };
    };
    var getContextToolbarBounds = function(editor, sharedBackstage, toolbarType, margin) {
      if (margin === void 0) {
        margin = 0;
      }
      var viewportBounds = getBounds$3(window);
      var contentAreaBox = box$1(SugarElement.fromDom(editor.getContentAreaContainer()));
      var toolbarOrMenubarEnabled = isMenubarEnabled(editor) || isToolbarEnabled(editor) || isMultipleToolbars(editor);
      var _a2 = getHorizontalBounds(contentAreaBox, viewportBounds, margin), x2 = _a2.x, width2 = _a2.width;
      if (editor.inline && !toolbarOrMenubarEnabled) {
        return bounds(x2, viewportBounds.y, width2, viewportBounds.height);
      } else {
        var isToolbarTop = sharedBackstage.header.isPositionedAtTop();
        var _b = getVerticalBounds(editor, contentAreaBox, viewportBounds, isToolbarTop, toolbarType, margin), y2 = _b.y, bottom3 = _b.bottom;
        return bounds(x2, y2, width2, bottom3 - y2);
      }
    };
    var bubbleSize$1 = 12;
    var bubbleAlignments$1 = {
      valignCentre: [],
      alignCentre: [],
      alignLeft: ["tox-pop--align-left"],
      alignRight: ["tox-pop--align-right"],
      right: ["tox-pop--right"],
      left: ["tox-pop--left"],
      bottom: ["tox-pop--bottom"],
      top: ["tox-pop--top"],
      inset: ["tox-pop--inset"]
    };
    var anchorOverrides = {
      maxHeightFunction: expandable$1(),
      maxWidthFunction: expandable()
    };
    var isEntireElementSelected = function(editor, elem) {
      var rng = editor.selection.getRng();
      var leaf$1 = leaf(SugarElement.fromDom(rng.startContainer), rng.startOffset);
      return rng.startContainer === rng.endContainer && rng.startOffset === rng.endOffset - 1 && eq2(leaf$1.element, elem);
    };
    var preservePosition = function(elem, position2, f2) {
      var currentPosition = getRaw(elem, "position");
      set$7(elem, "position", position2);
      var result = f2(elem);
      currentPosition.each(function(pos) {
        return set$7(elem, "position", pos);
      });
      return result;
    };
    var shouldUseInsetLayouts = function(position2) {
      return position2 === "node";
    };
    var determineInsetLayout = function(editor, contextbar, elem, data, bounds2) {
      var selectionBounds = getSelectionBounds(editor);
      var isSameAnchorElement = data.lastElement().exists(function(prev) {
        return eq2(elem, prev);
      });
      if (isEntireElementSelected(editor, elem)) {
        return isSameAnchorElement ? preserve : north;
      } else if (isSameAnchorElement) {
        return preservePosition(contextbar, data.getMode(), function() {
          var isOverlapping = isVerticalOverlap(selectionBounds, box$1(contextbar));
          return isOverlapping && !data.isReposition() ? flip$2 : preserve;
        });
      } else {
        var yBounds = data.getMode() === "fixed" ? bounds2.y + get$9().top : bounds2.y;
        var contextbarHeight = get$b(contextbar) + bubbleSize$1;
        return yBounds + contextbarHeight <= selectionBounds.y ? north : south;
      }
    };
    var getAnchorSpec$2 = function(editor, mobile, data, position2) {
      var smartInsetLayout = function(elem) {
        return function(anchor2, element2, bubbles, placee, bounds2) {
          var layout2 = determineInsetLayout(editor, placee, elem, data, bounds2);
          var newAnchor = __assign(__assign({}, anchor2), {
            y: bounds2.y,
            height: bounds2.height
          });
          return __assign(__assign({}, layout2(newAnchor, element2, bubbles, placee, bounds2)), { alwaysFit: true });
        };
      };
      var getInsetLayouts = function(elem) {
        return shouldUseInsetLayouts(position2) ? [smartInsetLayout(elem)] : [];
      };
      var desktopAnchorSpecLayouts = {
        onLtr: function(elem) {
          return [
            north$2,
            south$2,
            northeast$2,
            southeast$2,
            northwest$2,
            southwest$2
          ].concat(getInsetLayouts(elem));
        },
        onRtl: function(elem) {
          return [
            north$2,
            south$2,
            northwest$2,
            southwest$2,
            northeast$2,
            southeast$2
          ].concat(getInsetLayouts(elem));
        }
      };
      var mobileAnchorSpecLayouts = {
        onLtr: function(elem) {
          return [
            south$2,
            southeast$2,
            southwest$2,
            northeast$2,
            northwest$2,
            north$2
          ].concat(getInsetLayouts(elem));
        },
        onRtl: function(elem) {
          return [
            south$2,
            southwest$2,
            southeast$2,
            northwest$2,
            northeast$2,
            north$2
          ].concat(getInsetLayouts(elem));
        }
      };
      return mobile ? mobileAnchorSpecLayouts : desktopAnchorSpecLayouts;
    };
    var getAnchorLayout = function(editor, position2, isTouch2, data) {
      if (position2 === "line") {
        return {
          bubble: nu$5(bubbleSize$1, 0, bubbleAlignments$1),
          layouts: {
            onLtr: function() {
              return [east$2];
            },
            onRtl: function() {
              return [west$2];
            }
          },
          overrides: anchorOverrides
        };
      } else {
        return {
          bubble: nu$5(0, bubbleSize$1, bubbleAlignments$1, 1 / bubbleSize$1),
          layouts: getAnchorSpec$2(editor, isTouch2, data, position2),
          overrides: anchorOverrides
        };
      }
    };
    var matchTargetWith = function(elem, candidates) {
      var ctxs = filter$2(candidates, function(toolbarApi) {
        return toolbarApi.predicate(elem.dom);
      });
      var _a2 = partition$3(ctxs, function(t3) {
        return t3.type === "contexttoolbar";
      }), pass = _a2.pass, fail = _a2.fail;
      return {
        contextToolbars: pass,
        contextForms: fail
      };
    };
    var filterByPositionForStartNode = function(toolbars) {
      if (toolbars.length <= 1) {
        return toolbars;
      } else {
        var doesPositionExist = function(value2) {
          return exists(toolbars, function(t3) {
            return t3.position === value2;
          });
        };
        var filterToolbarsByPosition = function(value2) {
          return filter$2(toolbars, function(t3) {
            return t3.position === value2;
          });
        };
        var hasSelectionToolbars = doesPositionExist("selection");
        var hasNodeToolbars = doesPositionExist("node");
        if (hasSelectionToolbars || hasNodeToolbars) {
          if (hasNodeToolbars && hasSelectionToolbars) {
            var nodeToolbars = filterToolbarsByPosition("node");
            var selectionToolbars = map$2(filterToolbarsByPosition("selection"), function(t3) {
              return __assign(__assign({}, t3), { position: "node" });
            });
            return nodeToolbars.concat(selectionToolbars);
          } else {
            return hasSelectionToolbars ? filterToolbarsByPosition("selection") : filterToolbarsByPosition("node");
          }
        } else {
          return filterToolbarsByPosition("line");
        }
      }
    };
    var filterByPositionForAncestorNode = function(toolbars) {
      if (toolbars.length <= 1) {
        return toolbars;
      } else {
        var findPosition_1 = function(value2) {
          return find$5(toolbars, function(t3) {
            return t3.position === value2;
          });
        };
        var basePosition = findPosition_1("selection").orThunk(function() {
          return findPosition_1("node");
        }).orThunk(function() {
          return findPosition_1("line");
        }).map(function(t3) {
          return t3.position;
        });
        return basePosition.fold(function() {
          return [];
        }, function(pos) {
          return filter$2(toolbars, function(t3) {
            return t3.position === pos;
          });
        });
      }
    };
    var matchStartNode = function(elem, nodeCandidates, editorCandidates) {
      var nodeMatches = matchTargetWith(elem, nodeCandidates);
      if (nodeMatches.contextForms.length > 0) {
        return Optional.some({
          elem,
          toolbars: [nodeMatches.contextForms[0]]
        });
      } else {
        var editorMatches = matchTargetWith(elem, editorCandidates);
        if (editorMatches.contextForms.length > 0) {
          return Optional.some({
            elem,
            toolbars: [editorMatches.contextForms[0]]
          });
        } else if (nodeMatches.contextToolbars.length > 0 || editorMatches.contextToolbars.length > 0) {
          var toolbars = filterByPositionForStartNode(nodeMatches.contextToolbars.concat(editorMatches.contextToolbars));
          return Optional.some({
            elem,
            toolbars
          });
        } else {
          return Optional.none();
        }
      }
    };
    var matchAncestor = function(isRoot, startNode, scopes) {
      if (isRoot(startNode)) {
        return Optional.none();
      } else {
        return ancestor$2(startNode, function(ancestorElem) {
          if (isElement$2(ancestorElem)) {
            var _a2 = matchTargetWith(ancestorElem, scopes.inNodeScope), contextToolbars = _a2.contextToolbars, contextForms = _a2.contextForms;
            var toolbars = contextForms.length > 0 ? contextForms : filterByPositionForAncestorNode(contextToolbars);
            return toolbars.length > 0 ? Optional.some({
              elem: ancestorElem,
              toolbars
            }) : Optional.none();
          } else {
            return Optional.none();
          }
        }, isRoot);
      }
    };
    var lookup$1 = function(scopes, editor) {
      var rootElem = SugarElement.fromDom(editor.getBody());
      var isRoot = function(elem) {
        return eq2(elem, rootElem);
      };
      var isOutsideRoot = function(startNode2) {
        return !isRoot(startNode2) && !contains2(rootElem, startNode2);
      };
      var startNode = SugarElement.fromDom(editor.selection.getNode());
      if (isOutsideRoot(startNode)) {
        return Optional.none();
      }
      return matchStartNode(startNode, scopes.inNodeScope, scopes.inEditorScope).orThunk(function() {
        return matchAncestor(isRoot, startNode, scopes);
      });
    };
    var categorise = function(contextToolbars, navigate) {
      var forms = {};
      var inNodeScope = [];
      var inEditorScope = [];
      var formNavigators = {};
      var lookupTable = {};
      var registerForm = function(key, toolbarSpec) {
        var contextForm = getOrDie(createContextForm(toolbarSpec));
        forms[key] = contextForm;
        contextForm.launch.map(function(launch) {
          formNavigators["form:" + key] = __assign(__assign({}, toolbarSpec.launch), {
            type: launch.type === "contextformtogglebutton" ? "togglebutton" : "button",
            onAction: function() {
              navigate(contextForm);
            }
          });
        });
        if (contextForm.scope === "editor") {
          inEditorScope.push(contextForm);
        } else {
          inNodeScope.push(contextForm);
        }
        lookupTable[key] = contextForm;
      };
      var registerToolbar = function(key, toolbarSpec) {
        createContextToolbar(toolbarSpec).each(function(contextToolbar) {
          if (toolbarSpec.scope === "editor") {
            inEditorScope.push(contextToolbar);
          } else {
            inNodeScope.push(contextToolbar);
          }
          lookupTable[key] = contextToolbar;
        });
      };
      var keys$1 = keys(contextToolbars);
      each$1(keys$1, function(key) {
        var toolbarApi = contextToolbars[key];
        if (toolbarApi.type === "contextform") {
          registerForm(key, toolbarApi);
        } else if (toolbarApi.type === "contexttoolbar") {
          registerToolbar(key, toolbarApi);
        }
      });
      return {
        forms,
        inNodeScope,
        inEditorScope,
        lookupTable,
        formNavigators
      };
    };
    var forwardSlideEvent = generate$6("forward-slide");
    var backSlideEvent = generate$6("backward-slide");
    var changeSlideEvent = generate$6("change-slide-event");
    var resizingClass = "tox-pop--resizing";
    var renderContextToolbar = function(spec) {
      var stack = Cell([]);
      return InlineView.sketch({
        dom: {
          tag: "div",
          classes: ["tox-pop"]
        },
        fireDismissalEventInstead: { event: "doNotDismissYet" },
        onShow: function(comp) {
          stack.set([]);
          InlineView.getContent(comp).each(function(c2) {
            remove$6(c2.element, "visibility");
          });
          remove$2(comp.element, resizingClass);
          remove$6(comp.element, "width");
        },
        inlineBehaviours: derive$1([
          config("context-toolbar-events", [
            runOnSource(transitionend(), function(comp, se2) {
              if (se2.event.raw.propertyName === "width") {
                remove$2(comp.element, resizingClass);
                remove$6(comp.element, "width");
              }
            }),
            run$1(changeSlideEvent, function(comp, se2) {
              var elem = comp.element;
              remove$6(elem, "width");
              var currentWidth = get$a(elem);
              InlineView.setContent(comp, se2.event.contents);
              add$2(elem, resizingClass);
              var newWidth = get$a(elem);
              set$7(elem, "width", currentWidth + "px");
              InlineView.getContent(comp).each(function(newContents) {
                se2.event.focus.bind(function(f2) {
                  focus$3(f2);
                  return search(elem);
                }).orThunk(function() {
                  Keying.focusIn(newContents);
                  return active(getRootNode(elem));
                });
              });
              global$f.setTimeout(function() {
                set$7(comp.element, "width", newWidth + "px");
              }, 0);
            }),
            run$1(forwardSlideEvent, function(comp, se2) {
              InlineView.getContent(comp).each(function(oldContents) {
                stack.set(stack.get().concat([{
                  bar: oldContents,
                  focus: active(getRootNode(comp.element))
                }]));
              });
              emitWith(comp, changeSlideEvent, {
                contents: se2.event.forwardContents,
                focus: Optional.none()
              });
            }),
            run$1(backSlideEvent, function(comp, _se) {
              last$2(stack.get()).each(function(last2) {
                stack.set(stack.get().slice(0, stack.get().length - 1));
                emitWith(comp, changeSlideEvent, {
                  contents: premade(last2.bar),
                  focus: last2.focus
                });
              });
            })
          ]),
          Keying.config({
            mode: "special",
            onEscape: function(comp) {
              return last$2(stack.get()).fold(function() {
                return spec.onEscape();
              }, function(_2) {
                emit(comp, backSlideEvent);
                return Optional.some(true);
              });
            }
          })
        ]),
        lazySink: function() {
          return Result.value(spec.sink);
        }
      });
    };
    var transitionClass = "tox-pop--transition";
    var register$7 = function(editor, registryContextToolbars, sink, extras) {
      var backstage = extras.backstage;
      var sharedBackstage = backstage.shared;
      var isTouch2 = detect$1().deviceType.isTouch;
      var lastElement = value$1();
      var lastTrigger = value$1();
      var lastContextPosition = value$1();
      var contextbar = build$1(renderContextToolbar({
        sink,
        onEscape: function() {
          editor.focus();
          return Optional.some(true);
        }
      }));
      var getBounds3 = function() {
        var position2 = lastContextPosition.get().getOr("node");
        var margin = shouldUseInsetLayouts(position2) ? 1 : 0;
        return getContextToolbarBounds(editor, sharedBackstage, position2, margin);
      };
      var canLaunchToolbar = function() {
        return !editor.removed && !(isTouch2() && backstage.isContextMenuOpen());
      };
      var isSameLaunchElement = function(elem) {
        return is$1(lift2(elem, lastElement.get(), eq2), true);
      };
      var shouldContextToolbarHide = function() {
        if (!canLaunchToolbar()) {
          return true;
        } else {
          var contextToolbarBounds = getBounds3();
          var anchorBounds = is$1(lastContextPosition.get(), "node") ? getAnchorElementBounds(editor, lastElement.get()) : getSelectionBounds(editor);
          return contextToolbarBounds.height <= 0 || !isVerticalOverlap(anchorBounds, contextToolbarBounds);
        }
      };
      var close2 = function() {
        lastElement.clear();
        lastTrigger.clear();
        lastContextPosition.clear();
        InlineView.hide(contextbar);
      };
      var hideOrRepositionIfNecessary = function() {
        if (InlineView.isOpen(contextbar)) {
          var contextBarEle = contextbar.element;
          remove$6(contextBarEle, "display");
          if (shouldContextToolbarHide()) {
            set$7(contextBarEle, "display", "none");
          } else {
            lastTrigger.set(0);
            InlineView.reposition(contextbar);
          }
        }
      };
      var wrapInPopDialog = function(toolbarSpec) {
        return {
          dom: {
            tag: "div",
            classes: ["tox-pop__dialog"]
          },
          components: [toolbarSpec],
          behaviours: derive$1([
            Keying.config({ mode: "acyclic" }),
            config("pop-dialog-wrap-events", [
              runOnAttached(function(comp) {
                editor.shortcuts.add("ctrl+F9", "focus statusbar", function() {
                  return Keying.focusIn(comp);
                });
              }),
              runOnDetached(function(_comp) {
                editor.shortcuts.remove("ctrl+F9");
              })
            ])
          ])
        };
      };
      var getScopes = cached(function() {
        return categorise(registryContextToolbars, function(toolbarApi) {
          var alloySpec = buildToolbar([toolbarApi]);
          emitWith(contextbar, forwardSlideEvent, { forwardContents: wrapInPopDialog(alloySpec) });
        });
      });
      var buildContextToolbarGroups = function(allButtons, ctx) {
        return identifyButtons(editor, {
          buttons: allButtons,
          toolbar: ctx.items,
          allowToolbarGroups: false
        }, extras, Optional.some(["form:"]));
      };
      var buildContextFormGroups = function(ctx, providers) {
        return ContextForm.buildInitGroups(ctx, providers);
      };
      var buildToolbar = function(toolbars) {
        var buttons = editor.ui.registry.getAll().buttons;
        var scopes = getScopes();
        var allButtons = __assign(__assign({}, buttons), scopes.formNavigators);
        var toolbarType = getToolbarMode(editor) === ToolbarMode.scrolling ? ToolbarMode.scrolling : ToolbarMode.default;
        var initGroups = flatten(map$2(toolbars, function(ctx) {
          return ctx.type === "contexttoolbar" ? buildContextToolbarGroups(allButtons, ctx) : buildContextFormGroups(ctx, sharedBackstage.providers);
        }));
        return renderToolbar({
          type: toolbarType,
          uid: generate$6("context-toolbar"),
          initGroups,
          onEscape: Optional.none,
          cyclicKeying: true,
          providers: sharedBackstage.providers
        });
      };
      var getAnchor3 = function(position2, element2) {
        var anchorage = position2 === "node" ? sharedBackstage.anchors.node(element2) : sharedBackstage.anchors.cursor();
        var anchorLayout = getAnchorLayout(editor, position2, isTouch2(), {
          lastElement: lastElement.get,
          isReposition: function() {
            return is$1(lastTrigger.get(), 0);
          },
          getMode: function() {
            return Positioning.getMode(sink);
          }
        });
        return deepMerge(anchorage, anchorLayout);
      };
      var launchContext = function(toolbarApi, elem) {
        launchContextToolbar.cancel();
        if (!canLaunchToolbar()) {
          return;
        }
        var toolbarSpec = buildToolbar(toolbarApi);
        var position2 = toolbarApi[0].position;
        var anchor2 = getAnchor3(position2, elem);
        lastContextPosition.set(position2);
        lastTrigger.set(1);
        var contextBarEle = contextbar.element;
        remove$6(contextBarEle, "display");
        if (!isSameLaunchElement(elem)) {
          remove$2(contextBarEle, transitionClass);
          Positioning.reset(sink, contextbar);
        }
        InlineView.showWithinBounds(contextbar, wrapInPopDialog(toolbarSpec), {
          anchor: anchor2,
          transition: {
            classes: [transitionClass],
            mode: "placement"
          }
        }, function() {
          return Optional.some(getBounds3());
        });
        elem.fold(lastElement.clear, lastElement.set);
        if (shouldContextToolbarHide()) {
          set$7(contextBarEle, "display", "none");
        }
      };
      var launchContextToolbar = last(function() {
        if (!editor.hasFocus() || editor.removed) {
          return;
        }
        if (has(contextbar.element, transitionClass)) {
          launchContextToolbar.throttle();
        } else {
          var scopes = getScopes();
          lookup$1(scopes, editor).fold(close2, function(info) {
            launchContext(info.toolbars, Optional.some(info.elem));
          });
        }
      }, 17);
      editor.on("init", function() {
        editor.on("remove", close2);
        editor.on("ScrollContent ScrollWindow ObjectResized ResizeEditor longpress", hideOrRepositionIfNecessary);
        editor.on("click keyup focus SetContent", launchContextToolbar.throttle);
        editor.on(hideContextToolbarEvent, close2);
        editor.on(showContextToolbarEvent, function(e2) {
          var scopes = getScopes();
          get$e(scopes.lookupTable, e2.toolbarKey).each(function(ctx) {
            launchContext([ctx], someIf(e2.target !== editor, e2.target));
            InlineView.getContent(contextbar).each(Keying.focusIn);
          });
        });
        editor.on("focusout", function(_e2) {
          global$f.setEditorTimeout(editor, function() {
            if (search(sink.element).isNone() && search(contextbar.element).isNone()) {
              close2();
            }
          }, 0);
        });
        editor.on("SwitchMode", function() {
          if (editor.mode.isReadOnly()) {
            close2();
          }
        });
        editor.on("AfterProgressState", function(event) {
          if (event.state) {
            close2();
          } else if (editor.hasFocus()) {
            launchContextToolbar.throttle();
          }
        });
        editor.on("NodeChange", function(_e2) {
          search(contextbar.element).fold(launchContextToolbar.throttle, noop3);
        });
      });
    };
    var register$6 = function(editor) {
      var alignToolbarButtons = [
        {
          name: "alignleft",
          text: "Align left",
          cmd: "JustifyLeft",
          icon: "align-left"
        },
        {
          name: "aligncenter",
          text: "Align center",
          cmd: "JustifyCenter",
          icon: "align-center"
        },
        {
          name: "alignright",
          text: "Align right",
          cmd: "JustifyRight",
          icon: "align-right"
        },
        {
          name: "alignjustify",
          text: "Justify",
          cmd: "JustifyFull",
          icon: "align-justify"
        }
      ];
      each$1(alignToolbarButtons, function(item2) {
        editor.ui.registry.addToggleButton(item2.name, {
          tooltip: item2.text,
          icon: item2.icon,
          onAction: onActionExecCommand(editor, item2.cmd),
          onSetup: onSetupFormatToggle(editor, item2.name)
        });
      });
      editor.ui.registry.addButton("alignnone", {
        tooltip: "No alignment",
        icon: "align-none",
        onAction: onActionExecCommand(editor, "JustifyNone")
      });
    };
    var units = {
      unsupportedLength: [
        "em",
        "ex",
        "cap",
        "ch",
        "ic",
        "rem",
        "lh",
        "rlh",
        "vw",
        "vh",
        "vi",
        "vb",
        "vmin",
        "vmax",
        "cm",
        "mm",
        "Q",
        "in",
        "pc",
        "pt",
        "px"
      ],
      fixed: [
        "px",
        "pt"
      ],
      relative: ["%"],
      empty: [""]
    };
    var pattern = function() {
      var decimalDigits = "[0-9]+";
      var signedInteger = "[+-]?" + decimalDigits;
      var exponentPart = "[eE]" + signedInteger;
      var dot2 = "\\.";
      var opt = function(input2) {
        return "(?:" + input2 + ")?";
      };
      var unsignedDecimalLiteral = [
        "Infinity",
        decimalDigits + dot2 + opt(decimalDigits) + opt(exponentPart),
        dot2 + decimalDigits + opt(exponentPart),
        decimalDigits + opt(exponentPart)
      ].join("|");
      var float = "[+-]?(?:" + unsignedDecimalLiteral + ")";
      return new RegExp("^(" + float + ")(.*)$");
    }();
    var isUnit = function(unit, accepted) {
      return exists(accepted, function(acc) {
        return exists(units[acc], function(check) {
          return unit === check;
        });
      });
    };
    var parse3 = function(input2, accepted) {
      var match2 = Optional.from(pattern.exec(input2));
      return match2.bind(function(array) {
        var value2 = Number(array[1]);
        var unitRaw = array[2];
        if (isUnit(unitRaw, accepted)) {
          return Optional.some({
            value: value2,
            unit: unitRaw
          });
        } else {
          return Optional.none();
        }
      });
    };
    var normalise = function(input2, accepted) {
      return parse3(input2, accepted).map(function(_a2) {
        var value2 = _a2.value, unit = _a2.unit;
        return value2 + unit;
      });
    };
    var registerController = function(editor, spec) {
      var getMenuItems2 = function() {
        var options = spec.getOptions(editor);
        var initial = spec.getCurrent(editor).map(spec.hash);
        var current = value$1();
        return map$2(options, function(value2) {
          return {
            type: "togglemenuitem",
            text: spec.display(value2),
            onSetup: function(api2) {
              var setActive = function(active2) {
                if (active2) {
                  current.on(function(oldApi) {
                    return oldApi.setActive(false);
                  });
                  current.set(api2);
                }
                api2.setActive(active2);
              };
              setActive(is$1(initial, spec.hash(value2)));
              var unbindWatcher = spec.watcher(editor, value2, setActive);
              return function() {
                current.clear();
                unbindWatcher();
              };
            },
            onAction: function() {
              return spec.setCurrent(editor, value2);
            }
          };
        });
      };
      editor.ui.registry.addMenuButton(spec.name, {
        tooltip: spec.text,
        icon: spec.icon,
        fetch: function(callback2) {
          return callback2(getMenuItems2());
        },
        onSetup: spec.onToolbarSetup
      });
      editor.ui.registry.addNestedMenuItem(spec.name, {
        type: "nestedmenuitem",
        text: spec.text,
        getSubmenuItems: getMenuItems2,
        onSetup: spec.onMenuSetup
      });
    };
    var lineHeightSpec = {
      name: "lineheight",
      text: "Line height",
      icon: "line-height",
      getOptions: getLineHeightFormats,
      hash: function(input2) {
        return normalise(input2, [
          "fixed",
          "relative",
          "empty"
        ]).getOr(input2);
      },
      display: identity$1,
      watcher: function(editor, value2, callback2) {
        return editor.formatter.formatChanged("lineheight", callback2, false, { value: value2 }).unbind;
      },
      getCurrent: function(editor) {
        return Optional.from(editor.queryCommandValue("LineHeight"));
      },
      setCurrent: function(editor, value2) {
        return editor.execCommand("LineHeight", false, value2);
      }
    };
    var languageSpec = function(editor) {
      var settingsOpt = Optional.from(getContentLanguages(editor));
      return settingsOpt.map(function(settings) {
        return {
          name: "language",
          text: "Language",
          icon: "language",
          getOptions: constant$1(settings),
          hash: function(input2) {
            return isUndefined(input2.customCode) ? input2.code : input2.code + "/" + input2.customCode;
          },
          display: function(input2) {
            return input2.title;
          },
          watcher: function(editor2, value2, callback2) {
            return editor2.formatter.formatChanged("lang", callback2, false, {
              value: value2.code,
              customValue: value2.customCode
            }).unbind;
          },
          getCurrent: function(editor2) {
            var node = SugarElement.fromDom(editor2.selection.getNode());
            return closest$4(node, function(n2) {
              return Optional.some(n2).filter(isElement$2).bind(function(ele) {
                var codeOpt = getOpt(ele, "lang");
                return codeOpt.map(function(code) {
                  var customCode = getOpt(ele, "data-mce-lang").getOrUndefined();
                  return {
                    code,
                    customCode,
                    title: ""
                  };
                });
              });
            });
          },
          setCurrent: function(editor2, lang) {
            return editor2.execCommand("Lang", false, lang);
          },
          onToolbarSetup: function(api2) {
            var unbinder = unbindable();
            api2.setActive(editor.formatter.match("lang", {}, void 0, true));
            unbinder.set(editor.formatter.formatChanged("lang", api2.setActive, true));
            return unbinder.clear;
          }
        };
      });
    };
    var register$5 = function(editor) {
      registerController(editor, lineHeightSpec);
      languageSpec(editor).each(function(spec) {
        return registerController(editor, spec);
      });
    };
    var register$4 = function(editor, backstage) {
      alignSelectMenu(editor, backstage);
      fontSelectMenu(editor, backstage);
      styleSelectMenu(editor, backstage);
      formatSelectMenu(editor, backstage);
      fontsizeSelectMenu(editor, backstage);
    };
    var onSetupOutdentState = function(editor) {
      return onSetupEvent(editor, "NodeChange", function(api2) {
        api2.setDisabled(!editor.queryCommandState("outdent"));
      });
    };
    var registerButtons$2 = function(editor) {
      editor.ui.registry.addButton("outdent", {
        tooltip: "Decrease indent",
        icon: "outdent",
        onSetup: onSetupOutdentState(editor),
        onAction: onActionExecCommand(editor, "outdent")
      });
      editor.ui.registry.addButton("indent", {
        tooltip: "Increase indent",
        icon: "indent",
        onAction: onActionExecCommand(editor, "indent")
      });
    };
    var register$3 = function(editor) {
      registerButtons$2(editor);
    };
    var onActionToggleFormat = function(editor, fmt) {
      return function() {
        editor.execCommand("mceToggleFormat", false, fmt);
      };
    };
    var registerFormatButtons = function(editor) {
      global$5.each([
        {
          name: "bold",
          text: "Bold",
          icon: "bold"
        },
        {
          name: "italic",
          text: "Italic",
          icon: "italic"
        },
        {
          name: "underline",
          text: "Underline",
          icon: "underline"
        },
        {
          name: "strikethrough",
          text: "Strikethrough",
          icon: "strike-through"
        },
        {
          name: "subscript",
          text: "Subscript",
          icon: "subscript"
        },
        {
          name: "superscript",
          text: "Superscript",
          icon: "superscript"
        }
      ], function(btn, _idx) {
        editor.ui.registry.addToggleButton(btn.name, {
          tooltip: btn.text,
          icon: btn.icon,
          onSetup: onSetupFormatToggle(editor, btn.name),
          onAction: onActionToggleFormat(editor, btn.name)
        });
      });
      for (var i2 = 1; i2 <= 6; i2++) {
        var name_1 = "h" + i2;
        editor.ui.registry.addToggleButton(name_1, {
          text: name_1.toUpperCase(),
          tooltip: "Heading " + i2,
          onSetup: onSetupFormatToggle(editor, name_1),
          onAction: onActionToggleFormat(editor, name_1)
        });
      }
    };
    var registerCommandButtons = function(editor) {
      global$5.each([
        {
          name: "cut",
          text: "Cut",
          action: "Cut",
          icon: "cut"
        },
        {
          name: "copy",
          text: "Copy",
          action: "Copy",
          icon: "copy"
        },
        {
          name: "paste",
          text: "Paste",
          action: "Paste",
          icon: "paste"
        },
        {
          name: "help",
          text: "Help",
          action: "mceHelp",
          icon: "help"
        },
        {
          name: "selectall",
          text: "Select all",
          action: "SelectAll",
          icon: "select-all"
        },
        {
          name: "newdocument",
          text: "New document",
          action: "mceNewDocument",
          icon: "new-document"
        },
        {
          name: "removeformat",
          text: "Clear formatting",
          action: "RemoveFormat",
          icon: "remove-formatting"
        },
        {
          name: "remove",
          text: "Remove",
          action: "Delete",
          icon: "remove"
        }
      ], function(btn) {
        editor.ui.registry.addButton(btn.name, {
          tooltip: btn.text,
          icon: btn.icon,
          onAction: onActionExecCommand(editor, btn.action)
        });
      });
    };
    var registerCommandToggleButtons = function(editor) {
      global$5.each([{
        name: "blockquote",
        text: "Blockquote",
        action: "mceBlockQuote",
        icon: "quote"
      }], function(btn) {
        editor.ui.registry.addToggleButton(btn.name, {
          tooltip: btn.text,
          icon: btn.icon,
          onAction: onActionExecCommand(editor, btn.action),
          onSetup: onSetupFormatToggle(editor, btn.name)
        });
      });
    };
    var registerButtons$1 = function(editor) {
      registerFormatButtons(editor);
      registerCommandButtons(editor);
      registerCommandToggleButtons(editor);
    };
    var registerMenuItems$2 = function(editor) {
      global$5.each([
        {
          name: "bold",
          text: "Bold",
          action: "Bold",
          icon: "bold",
          shortcut: "Meta+B"
        },
        {
          name: "italic",
          text: "Italic",
          action: "Italic",
          icon: "italic",
          shortcut: "Meta+I"
        },
        {
          name: "underline",
          text: "Underline",
          action: "Underline",
          icon: "underline",
          shortcut: "Meta+U"
        },
        {
          name: "strikethrough",
          text: "Strikethrough",
          action: "Strikethrough",
          icon: "strike-through",
          shortcut: ""
        },
        {
          name: "subscript",
          text: "Subscript",
          action: "Subscript",
          icon: "subscript",
          shortcut: ""
        },
        {
          name: "superscript",
          text: "Superscript",
          action: "Superscript",
          icon: "superscript",
          shortcut: ""
        },
        {
          name: "removeformat",
          text: "Clear formatting",
          action: "RemoveFormat",
          icon: "remove-formatting",
          shortcut: ""
        },
        {
          name: "newdocument",
          text: "New document",
          action: "mceNewDocument",
          icon: "new-document",
          shortcut: ""
        },
        {
          name: "cut",
          text: "Cut",
          action: "Cut",
          icon: "cut",
          shortcut: "Meta+X"
        },
        {
          name: "copy",
          text: "Copy",
          action: "Copy",
          icon: "copy",
          shortcut: "Meta+C"
        },
        {
          name: "paste",
          text: "Paste",
          action: "Paste",
          icon: "paste",
          shortcut: "Meta+V"
        },
        {
          name: "selectall",
          text: "Select all",
          action: "SelectAll",
          icon: "select-all",
          shortcut: "Meta+A"
        }
      ], function(btn) {
        editor.ui.registry.addMenuItem(btn.name, {
          text: btn.text,
          icon: btn.icon,
          shortcut: btn.shortcut,
          onAction: onActionExecCommand(editor, btn.action)
        });
      });
      editor.ui.registry.addMenuItem("codeformat", {
        text: "Code",
        icon: "sourcecode",
        onAction: onActionToggleFormat(editor, "code")
      });
    };
    var register$2 = function(editor) {
      registerButtons$1(editor);
      registerMenuItems$2(editor);
    };
    var onSetupUndoRedoState = function(editor, type2) {
      return onSetupEvent(editor, "Undo Redo AddUndo TypingUndo ClearUndos SwitchMode", function(api2) {
        api2.setDisabled(editor.mode.isReadOnly() || !editor.undoManager[type2]());
      });
    };
    var registerMenuItems$1 = function(editor) {
      editor.ui.registry.addMenuItem("undo", {
        text: "Undo",
        icon: "undo",
        shortcut: "Meta+Z",
        onSetup: onSetupUndoRedoState(editor, "hasUndo"),
        onAction: onActionExecCommand(editor, "undo")
      });
      editor.ui.registry.addMenuItem("redo", {
        text: "Redo",
        icon: "redo",
        shortcut: "Meta+Y",
        onSetup: onSetupUndoRedoState(editor, "hasRedo"),
        onAction: onActionExecCommand(editor, "redo")
      });
    };
    var registerButtons = function(editor) {
      editor.ui.registry.addButton("undo", {
        tooltip: "Undo",
        icon: "undo",
        disabled: true,
        onSetup: onSetupUndoRedoState(editor, "hasUndo"),
        onAction: onActionExecCommand(editor, "undo")
      });
      editor.ui.registry.addButton("redo", {
        tooltip: "Redo",
        icon: "redo",
        disabled: true,
        onSetup: onSetupUndoRedoState(editor, "hasRedo"),
        onAction: onActionExecCommand(editor, "redo")
      });
    };
    var register$1 = function(editor) {
      registerMenuItems$1(editor);
      registerButtons(editor);
    };
    var onSetupVisualAidState = function(editor) {
      return onSetupEvent(editor, "VisualAid", function(api2) {
        api2.setActive(editor.hasVisual);
      });
    };
    var registerMenuItems = function(editor) {
      editor.ui.registry.addToggleMenuItem("visualaid", {
        text: "Visual aids",
        onSetup: onSetupVisualAidState(editor),
        onAction: onActionExecCommand(editor, "mceToggleVisualAid")
      });
    };
    var registerToolbarButton = function(editor) {
      editor.ui.registry.addButton("visualaid", {
        tooltip: "Visual aids",
        text: "Visual aids",
        onAction: onActionExecCommand(editor, "mceToggleVisualAid")
      });
    };
    var register = function(editor) {
      registerToolbarButton(editor);
      registerMenuItems(editor);
    };
    var setup$6 = function(editor, backstage) {
      register$6(editor);
      register$2(editor);
      register$4(editor, backstage);
      register$1(editor);
      register$a(editor);
      register(editor);
      register$3(editor);
      register$5(editor);
    };
    var nu = function(x2, y2) {
      return {
        type: "makeshift",
        x: x2,
        y: y2
      };
    };
    var transpose = function(pos, dx, dy) {
      return nu(pos.x + dx, pos.y + dy);
    };
    var isTouchEvent = function(e2) {
      return e2.type === "longpress" || e2.type.indexOf("touch") === 0;
    };
    var fromPageXY = function(e2) {
      if (isTouchEvent(e2)) {
        var touch2 = e2.touches[0];
        return nu(touch2.pageX, touch2.pageY);
      } else {
        return nu(e2.pageX, e2.pageY);
      }
    };
    var fromClientXY = function(e2) {
      if (isTouchEvent(e2)) {
        var touch2 = e2.touches[0];
        return nu(touch2.clientX, touch2.clientY);
      } else {
        return nu(e2.clientX, e2.clientY);
      }
    };
    var transposeContentAreaContainer = function(element2, pos) {
      var containerPos = global$b.DOM.getPos(element2);
      return transpose(pos, containerPos.x, containerPos.y);
    };
    var getPointAnchor = function(editor, e2) {
      if (e2.type === "contextmenu" || e2.type === "longpress") {
        if (editor.inline) {
          return fromPageXY(e2);
        } else {
          return transposeContentAreaContainer(editor.getContentAreaContainer(), fromClientXY(e2));
        }
      } else {
        return getSelectionAnchor(editor);
      }
    };
    var getSelectionAnchor = function(editor) {
      return {
        type: "selection",
        root: SugarElement.fromDom(editor.selection.getNode())
      };
    };
    var getNodeAnchor = function(editor) {
      return {
        type: "node",
        node: Optional.some(SugarElement.fromDom(editor.selection.getNode())),
        root: SugarElement.fromDom(editor.getBody())
      };
    };
    var getAnchorSpec$1 = function(editor, e2, anchorType) {
      switch (anchorType) {
        case "node":
          return getNodeAnchor(editor);
        case "point":
          return getPointAnchor(editor, e2);
        case "selection":
          return getSelectionAnchor(editor);
      }
    };
    var initAndShow$1 = function(editor, e2, buildMenu, backstage, contextmenu, anchorType) {
      var items = buildMenu();
      var anchorSpec = getAnchorSpec$1(editor, e2, anchorType);
      build(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, false).map(function(menuData) {
        e2.preventDefault();
        InlineView.showMenuAt(contextmenu, { anchor: anchorSpec }, {
          menu: { markers: markers("normal") },
          data: menuData
        });
      });
    };
    var layouts2 = {
      onLtr: function() {
        return [
          south$2,
          southeast$2,
          southwest$2,
          northeast$2,
          northwest$2,
          north$2,
          north,
          south,
          northeast,
          southeast,
          northwest,
          southwest
        ];
      },
      onRtl: function() {
        return [
          south$2,
          southwest$2,
          southeast$2,
          northwest$2,
          northeast$2,
          north$2,
          north,
          south,
          northwest,
          southwest,
          northeast,
          southeast
        ];
      }
    };
    var bubbleSize = 12;
    var bubbleAlignments = {
      valignCentre: [],
      alignCentre: [],
      alignLeft: ["tox-pop--align-left"],
      alignRight: ["tox-pop--align-right"],
      right: ["tox-pop--right"],
      left: ["tox-pop--left"],
      bottom: ["tox-pop--bottom"],
      top: ["tox-pop--top"]
    };
    var isTouchWithinSelection = function(editor, e2) {
      var selection = editor.selection;
      if (selection.isCollapsed() || e2.touches.length < 1) {
        return false;
      } else {
        var touch_1 = e2.touches[0];
        var rng = selection.getRng();
        var rngRectOpt = getFirstRect(editor.getWin(), SimSelection.domRange(rng));
        return rngRectOpt.exists(function(rngRect) {
          return rngRect.left <= touch_1.clientX && rngRect.right >= touch_1.clientX && rngRect.top <= touch_1.clientY && rngRect.bottom >= touch_1.clientY;
        });
      }
    };
    var setupiOSOverrides = function(editor) {
      var originalSelection = editor.selection.getRng();
      var selectionReset = function() {
        global$f.setEditorTimeout(editor, function() {
          editor.selection.setRng(originalSelection);
        }, 10);
        unbindEventListeners();
      };
      editor.once("touchend", selectionReset);
      var preventMousedown = function(e2) {
        e2.preventDefault();
        e2.stopImmediatePropagation();
      };
      editor.on("mousedown", preventMousedown, true);
      var clearSelectionReset = function() {
        return unbindEventListeners();
      };
      editor.once("longpresscancel", clearSelectionReset);
      var unbindEventListeners = function() {
        editor.off("touchend", selectionReset);
        editor.off("longpresscancel", clearSelectionReset);
        editor.off("mousedown", preventMousedown);
      };
    };
    var getAnchorSpec = function(editor, e2, anchorType) {
      var anchorSpec = getAnchorSpec$1(editor, e2, anchorType);
      var bubbleYOffset = anchorType === "point" ? bubbleSize : 0;
      return __assign({
        bubble: nu$5(0, bubbleYOffset, bubbleAlignments),
        layouts: layouts2,
        overrides: {
          maxWidthFunction: expandable(),
          maxHeightFunction: expandable$1()
        }
      }, anchorSpec);
    };
    var show = function(editor, e2, items, backstage, contextmenu, anchorType, highlightImmediately) {
      var anchorSpec = getAnchorSpec(editor, e2, anchorType);
      build(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, true).map(function(menuData) {
        e2.preventDefault();
        InlineView.showMenuWithinBounds(contextmenu, { anchor: anchorSpec }, {
          menu: {
            markers: markers("normal"),
            highlightImmediately
          },
          data: menuData,
          type: "horizontal"
        }, function() {
          return Optional.some(getContextToolbarBounds(editor, backstage.shared, anchorType === "node" ? "node" : "selection"));
        });
        editor.fire(hideContextToolbarEvent);
      });
    };
    var initAndShow = function(editor, e2, buildMenu, backstage, contextmenu, anchorType) {
      var detection2 = detect$1();
      var isiOS = detection2.os.isiOS();
      var isOSX = detection2.os.isOSX();
      var isAndroid = detection2.os.isAndroid();
      var isTouch2 = detection2.deviceType.isTouch();
      var shouldHighlightImmediately = function() {
        return !(isAndroid || isiOS || isOSX && isTouch2);
      };
      var open2 = function() {
        var items = buildMenu();
        show(editor, e2, items, backstage, contextmenu, anchorType, shouldHighlightImmediately());
      };
      if ((isOSX || isiOS) && anchorType !== "node") {
        var openiOS_1 = function() {
          setupiOSOverrides(editor);
          open2();
        };
        if (isTouchWithinSelection(editor, e2)) {
          openiOS_1();
        } else {
          editor.once("selectionchange", openiOS_1);
          editor.once("touchend", function() {
            return editor.off("selectionchange", openiOS_1);
          });
        }
      } else {
        open2();
      }
    };
    var patchPipeConfig = function(config2) {
      return typeof config2 === "string" ? config2.split(/[ ,]/) : config2;
    };
    var shouldNeverUseNative = function(editor) {
      return editor.getParam("contextmenu_never_use_native", false, "boolean");
    };
    var getMenuItems = function(editor, name2, defaultItems) {
      var contextMenus = editor.ui.registry.getAll().contextMenus;
      return Optional.from(editor.getParam(name2)).map(patchPipeConfig).getOrThunk(function() {
        return filter$2(patchPipeConfig(defaultItems), function(item2) {
          return has$2(contextMenus, item2);
        });
      });
    };
    var isContextMenuDisabled = function(editor) {
      return editor.getParam("contextmenu") === false;
    };
    var getContextMenu = function(editor) {
      return getMenuItems(editor, "contextmenu", "link linkchecker image imagetools table spellchecker configurepermanentpen");
    };
    var getAvoidOverlapSelector = function(editor) {
      return editor.getParam("contextmenu_avoid_overlap", "", "string");
    };
    var isSeparator = function(item2) {
      return isString(item2) ? item2 === "|" : item2.type === "separator";
    };
    var separator = { type: "separator" };
    var makeContextItem = function(item2) {
      var commonMenuItem = function(item3) {
        return {
          text: item3.text,
          icon: item3.icon,
          disabled: item3.disabled,
          shortcut: item3.shortcut
        };
      };
      if (isString(item2)) {
        return item2;
      } else {
        switch (item2.type) {
          case "separator":
            return separator;
          case "submenu":
            return __assign(__assign({ type: "nestedmenuitem" }, commonMenuItem(item2)), {
              getSubmenuItems: function() {
                var items = item2.getSubmenuItems();
                if (isString(items)) {
                  return items;
                } else {
                  return map$2(items, makeContextItem);
                }
              }
            });
          default:
            return __assign(__assign({ type: "menuitem" }, commonMenuItem(item2)), { onAction: noarg(item2.onAction) });
        }
      }
    };
    var addContextMenuGroup = function(xs, groupItems) {
      if (groupItems.length === 0) {
        return xs;
      }
      var lastMenuItem = last$2(xs).filter(function(item2) {
        return !isSeparator(item2);
      });
      var before2 = lastMenuItem.fold(function() {
        return [];
      }, function(_2) {
        return [separator];
      });
      return xs.concat(before2).concat(groupItems).concat([separator]);
    };
    var generateContextMenu = function(contextMenus, menuConfig, selectedElement) {
      var sections = foldl(menuConfig, function(acc, name2) {
        return get$e(contextMenus, name2.toLowerCase()).map(function(menu2) {
          var items = menu2.update(selectedElement);
          if (isString(items)) {
            return addContextMenuGroup(acc, items.split(" "));
          } else if (items.length > 0) {
            var allItems = map$2(items, makeContextItem);
            return addContextMenuGroup(acc, allItems);
          } else {
            return acc;
          }
        }).getOrThunk(function() {
          return acc.concat([name2]);
        });
      }, []);
      if (sections.length > 0 && isSeparator(sections[sections.length - 1])) {
        sections.pop();
      }
      return sections;
    };
    var isNativeOverrideKeyEvent = function(editor, e2) {
      return e2.ctrlKey && !shouldNeverUseNative(editor);
    };
    var isTriggeredByKeyboard = function(editor, e2) {
      return e2.type !== "longpress" && (e2.button !== 2 || e2.target === editor.getBody() && e2.pointerType === "");
    };
    var getSelectedElement = function(editor, e2) {
      return isTriggeredByKeyboard(editor, e2) ? editor.selection.getStart(true) : e2.target;
    };
    var getAnchorType = function(editor, e2) {
      var selector = getAvoidOverlapSelector(editor);
      var anchorType = isTriggeredByKeyboard(editor, e2) ? "selection" : "point";
      if (isNotEmpty(selector)) {
        var target = getSelectedElement(editor, e2);
        var selectorExists = closest(SugarElement.fromDom(target), selector);
        return selectorExists ? "node" : anchorType;
      } else {
        return anchorType;
      }
    };
    var setup$5 = function(editor, lazySink, backstage) {
      var detection2 = detect$1();
      var isTouch2 = detection2.deviceType.isTouch;
      var contextmenu = build$1(InlineView.sketch({
        dom: { tag: "div" },
        lazySink,
        onEscape: function() {
          return editor.focus();
        },
        onShow: function() {
          return backstage.setContextMenuState(true);
        },
        onHide: function() {
          return backstage.setContextMenuState(false);
        },
        fireDismissalEventInstead: {},
        inlineBehaviours: derive$1([config("dismissContextMenu", [run$1(dismissRequested(), function(comp, _se) {
          Sandboxing.close(comp);
          editor.focus();
        })])])
      }));
      var hideContextMenu = function(_e2) {
        return InlineView.hide(contextmenu);
      };
      var showContextMenu = function(e2) {
        if (shouldNeverUseNative(editor)) {
          e2.preventDefault();
        }
        if (isNativeOverrideKeyEvent(editor, e2) || isContextMenuDisabled(editor)) {
          return;
        }
        var anchorType = getAnchorType(editor, e2);
        var buildMenu = function() {
          var selectedElement = getSelectedElement(editor, e2);
          var registry2 = editor.ui.registry.getAll();
          var menuConfig = getContextMenu(editor);
          return generateContextMenu(registry2.contextMenus, menuConfig, selectedElement);
        };
        var initAndShow$2 = isTouch2() ? initAndShow : initAndShow$1;
        initAndShow$2(editor, e2, buildMenu, backstage, contextmenu, anchorType);
      };
      editor.on("init", function() {
        var hideEvents = "ResizeEditor ScrollContent ScrollWindow longpresscancel" + (isTouch2() ? "" : " ResizeWindow");
        editor.on(hideEvents, hideContextMenu);
        editor.on("longpress contextmenu", showContextMenu);
      });
    };
    var adt = Adt.generate([
      {
        offset: [
          "x",
          "y"
        ]
      },
      {
        absolute: [
          "x",
          "y"
        ]
      },
      {
        fixed: [
          "x",
          "y"
        ]
      }
    ]);
    var subtract = function(change2) {
      return function(point2) {
        return point2.translate(-change2.left, -change2.top);
      };
    };
    var add3 = function(change2) {
      return function(point2) {
        return point2.translate(change2.left, change2.top);
      };
    };
    var transform = function(changes) {
      return function(x2, y2) {
        return foldl(changes, function(rest, f2) {
          return f2(rest);
        }, SugarPosition(x2, y2));
      };
    };
    var asFixed = function(coord, scroll, origin) {
      return coord.fold(transform([
        add3(origin),
        subtract(scroll)
      ]), transform([subtract(scroll)]), transform([]));
    };
    var asAbsolute = function(coord, scroll, origin) {
      return coord.fold(transform([add3(origin)]), transform([]), transform([add3(scroll)]));
    };
    var asOffset = function(coord, scroll, origin) {
      return coord.fold(transform([]), transform([subtract(origin)]), transform([
        add3(scroll),
        subtract(origin)
      ]));
    };
    var withinRange = function(coord1, coord2, xRange2, yRange2, scroll, origin) {
      var a1 = asAbsolute(coord1, scroll, origin);
      var a2 = asAbsolute(coord2, scroll, origin);
      return Math.abs(a1.left - a2.left) <= xRange2 && Math.abs(a1.top - a2.top) <= yRange2;
    };
    var getDeltas = function(coord1, coord2, xRange2, yRange2, scroll, origin) {
      var a1 = asAbsolute(coord1, scroll, origin);
      var a2 = asAbsolute(coord2, scroll, origin);
      var left3 = Math.abs(a1.left - a2.left);
      var top3 = Math.abs(a1.top - a2.top);
      return SugarPosition(left3, top3);
    };
    var toStyles = function(coord, scroll, origin) {
      var stylesOpt = coord.fold(function(x2, y2) {
        return {
          position: Optional.some("absolute"),
          left: Optional.some(x2 + "px"),
          top: Optional.some(y2 + "px")
        };
      }, function(x2, y2) {
        return {
          position: Optional.some("absolute"),
          left: Optional.some(x2 - origin.left + "px"),
          top: Optional.some(y2 - origin.top + "px")
        };
      }, function(x2, y2) {
        return {
          position: Optional.some("fixed"),
          left: Optional.some(x2 + "px"),
          top: Optional.some(y2 + "px")
        };
      });
      return __assign({
        right: Optional.none(),
        bottom: Optional.none()
      }, stylesOpt);
    };
    var translate = function(coord, deltaX, deltaY) {
      return coord.fold(function(x2, y2) {
        return offset2(x2 + deltaX, y2 + deltaY);
      }, function(x2, y2) {
        return absolute(x2 + deltaX, y2 + deltaY);
      }, function(x2, y2) {
        return fixed(x2 + deltaX, y2 + deltaY);
      });
    };
    var absorb = function(partialCoord, originalCoord, scroll, origin) {
      var absorbOne = function(stencil, nu2) {
        return function(optX, optY) {
          var original2 = stencil(originalCoord, scroll, origin);
          return nu2(optX.getOr(original2.left), optY.getOr(original2.top));
        };
      };
      return partialCoord.fold(absorbOne(asOffset, offset2), absorbOne(asAbsolute, absolute), absorbOne(asFixed, fixed));
    };
    var offset2 = adt.offset;
    var absolute = adt.absolute;
    var fixed = adt.fixed;
    var parseAttrToInt = function(element2, name2) {
      var value2 = get$d(element2, name2);
      return isUndefined(value2) ? NaN : parseInt(value2, 10);
    };
    var get = function(component, snapsInfo) {
      var element2 = component.element;
      var x2 = parseAttrToInt(element2, snapsInfo.leftAttr);
      var y2 = parseAttrToInt(element2, snapsInfo.topAttr);
      return isNaN(x2) || isNaN(y2) ? Optional.none() : Optional.some(SugarPosition(x2, y2));
    };
    var set2 = function(component, snapsInfo, pt2) {
      var element2 = component.element;
      set$8(element2, snapsInfo.leftAttr, pt2.left + "px");
      set$8(element2, snapsInfo.topAttr, pt2.top + "px");
    };
    var clear = function(component, snapsInfo) {
      var element2 = component.element;
      remove$7(element2, snapsInfo.leftAttr);
      remove$7(element2, snapsInfo.topAttr);
    };
    var getCoords = function(component, snapInfo, coord, delta) {
      return get(component, snapInfo).fold(function() {
        return coord;
      }, function(fixed$12) {
        return fixed(fixed$12.left + delta.left, fixed$12.top + delta.top);
      });
    };
    var moveOrSnap = function(component, snapInfo, coord, delta, scroll, origin) {
      var newCoord = getCoords(component, snapInfo, coord, delta);
      var snap2 = snapInfo.mustSnap ? findClosestSnap(component, snapInfo, newCoord, scroll, origin) : findSnap(component, snapInfo, newCoord, scroll, origin);
      var fixedCoord = asFixed(newCoord, scroll, origin);
      set2(component, snapInfo, fixedCoord);
      return snap2.fold(function() {
        return {
          coord: fixed(fixedCoord.left, fixedCoord.top),
          extra: Optional.none()
        };
      }, function(spanned) {
        return {
          coord: spanned.output,
          extra: spanned.extra
        };
      });
    };
    var stopDrag = function(component, snapInfo) {
      clear(component, snapInfo);
    };
    var findMatchingSnap = function(snaps, newCoord, scroll, origin) {
      return findMap(snaps, function(snap2) {
        var sensor = snap2.sensor;
        var inRange2 = withinRange(newCoord, sensor, snap2.range.left, snap2.range.top, scroll, origin);
        return inRange2 ? Optional.some({
          output: absorb(snap2.output, newCoord, scroll, origin),
          extra: snap2.extra
        }) : Optional.none();
      });
    };
    var findClosestSnap = function(component, snapInfo, newCoord, scroll, origin) {
      var snaps = snapInfo.getSnapPoints(component);
      var matchSnap = findMatchingSnap(snaps, newCoord, scroll, origin);
      return matchSnap.orThunk(function() {
        var bestSnap = foldl(snaps, function(acc, snap2) {
          var sensor = snap2.sensor;
          var deltas = getDeltas(newCoord, sensor, snap2.range.left, snap2.range.top, scroll, origin);
          return acc.deltas.fold(function() {
            return {
              deltas: Optional.some(deltas),
              snap: Optional.some(snap2)
            };
          }, function(bestDeltas) {
            var currAvg = (deltas.left + deltas.top) / 2;
            var bestAvg = (bestDeltas.left + bestDeltas.top) / 2;
            if (currAvg <= bestAvg) {
              return {
                deltas: Optional.some(deltas),
                snap: Optional.some(snap2)
              };
            } else {
              return acc;
            }
          });
        }, {
          deltas: Optional.none(),
          snap: Optional.none()
        });
        return bestSnap.snap.map(function(snap2) {
          return {
            output: absorb(snap2.output, newCoord, scroll, origin),
            extra: snap2.extra
          };
        });
      });
    };
    var findSnap = function(component, snapInfo, newCoord, scroll, origin) {
      var snaps = snapInfo.getSnapPoints(component);
      return findMatchingSnap(snaps, newCoord, scroll, origin);
    };
    var snapTo$1 = function(snap2, scroll, origin) {
      return {
        coord: absorb(snap2.output, snap2.output, scroll, origin),
        extra: snap2.extra
      };
    };
    var snapTo = function(component, dragConfig, _state, snap2) {
      var target = dragConfig.getTarget(component.element);
      if (dragConfig.repositionTarget) {
        var doc = owner$4(component.element);
        var scroll_1 = get$9(doc);
        var origin_1 = getOrigin(target);
        var snapPin = snapTo$1(snap2, scroll_1, origin_1);
        var styles = toStyles(snapPin.coord, scroll_1, origin_1);
        setOptions(target, styles);
      }
    };
    var DraggingApis = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      snapTo
    });
    var initialAttribute = "data-initial-z-index";
    var resetZIndex = function(blocker) {
      parent(blocker.element).filter(isElement$2).each(function(root) {
        getOpt(root, initialAttribute).fold(function() {
          return remove$6(root, "z-index");
        }, function(zIndex) {
          return set$7(root, "z-index", zIndex);
        });
        remove$7(root, initialAttribute);
      });
    };
    var changeZIndex = function(blocker) {
      parent(blocker.element).filter(isElement$2).each(function(root) {
        getRaw(root, "z-index").each(function(zindex) {
          set$8(root, initialAttribute, zindex);
        });
        set$7(root, "z-index", get$c(blocker.element, "z-index"));
      });
    };
    var instigate = function(anyComponent, blocker) {
      anyComponent.getSystem().addToGui(blocker);
      changeZIndex(blocker);
    };
    var discard = function(blocker) {
      resetZIndex(blocker);
      blocker.getSystem().removeFromGui(blocker);
    };
    var createComponent = function(component, blockerClass, blockerEvents) {
      return component.getSystem().build(Container.sketch({
        dom: {
          styles: {
            "left": "0px",
            "top": "0px",
            "width": "100%",
            "height": "100%",
            "position": "fixed",
            "z-index": "1000000000000000"
          },
          classes: [blockerClass]
        },
        events: blockerEvents
      }));
    };
    var SnapSchema = optionObjOf("snaps", [
      required$1("getSnapPoints"),
      onHandler("onSensor"),
      required$1("leftAttr"),
      required$1("topAttr"),
      defaulted("lazyViewport", win),
      defaulted("mustSnap", false)
    ]);
    var schema$6 = [
      defaulted("useFixed", never),
      required$1("blockerClass"),
      defaulted("getTarget", identity$1),
      defaulted("onDrag", noop3),
      defaulted("repositionTarget", true),
      defaulted("onDrop", noop3),
      defaultedFunction("getBounds", win),
      SnapSchema
    ];
    var getCurrentCoord = function(target) {
      return lift3(getRaw(target, "left"), getRaw(target, "top"), getRaw(target, "position"), function(left3, top3, position2) {
        var nu2 = position2 === "fixed" ? fixed : offset2;
        return nu2(parseInt(left3, 10), parseInt(top3, 10));
      }).getOrThunk(function() {
        var location2 = absolute$3(target);
        return absolute(location2.left, location2.top);
      });
    };
    var clampCoords = function(component, coords, scroll, origin, startData) {
      var bounds2 = startData.bounds;
      var absoluteCoord = asAbsolute(coords, scroll, origin);
      var newX = clamp$1(absoluteCoord.left, bounds2.x, bounds2.x + bounds2.width - startData.width);
      var newY = clamp$1(absoluteCoord.top, bounds2.y, bounds2.y + bounds2.height - startData.height);
      var newCoords = absolute(newX, newY);
      return coords.fold(function() {
        var offset$1 = asOffset(newCoords, scroll, origin);
        return offset2(offset$1.left, offset$1.top);
      }, constant$1(newCoords), function() {
        var fixed$12 = asFixed(newCoords, scroll, origin);
        return fixed(fixed$12.left, fixed$12.top);
      });
    };
    var calcNewCoord = function(component, optSnaps, currentCoord, scroll, origin, delta, startData) {
      var newCoord = optSnaps.fold(function() {
        var translated = translate(currentCoord, delta.left, delta.top);
        var fixedCoord = asFixed(translated, scroll, origin);
        return fixed(fixedCoord.left, fixedCoord.top);
      }, function(snapInfo) {
        var snapping = moveOrSnap(component, snapInfo, currentCoord, delta, scroll, origin);
        snapping.extra.each(function(extra) {
          snapInfo.onSensor(component, extra);
        });
        return snapping.coord;
      });
      return clampCoords(component, newCoord, scroll, origin, startData);
    };
    var dragBy = function(component, dragConfig, startData, delta) {
      var target = dragConfig.getTarget(component.element);
      if (dragConfig.repositionTarget) {
        var doc = owner$4(component.element);
        var scroll_1 = get$9(doc);
        var origin_1 = getOrigin(target);
        var currentCoord = getCurrentCoord(target);
        var newCoord = calcNewCoord(component, dragConfig.snaps, currentCoord, scroll_1, origin_1, delta, startData);
        var styles = toStyles(newCoord, scroll_1, origin_1);
        setOptions(target, styles);
      }
      dragConfig.onDrag(component, target, delta);
    };
    var calcStartData = function(dragConfig, comp) {
      return {
        bounds: dragConfig.getBounds(),
        height: getOuter$2(comp.element),
        width: getOuter$1(comp.element)
      };
    };
    var move = function(component, dragConfig, dragState, dragMode, event) {
      var delta = dragState.update(dragMode, event);
      var dragStartData = dragState.getStartData().getOrThunk(function() {
        return calcStartData(dragConfig, component);
      });
      delta.each(function(dlt) {
        dragBy(component, dragConfig, dragStartData, dlt);
      });
    };
    var stop = function(component, blocker, dragConfig, dragState) {
      blocker.each(discard);
      dragConfig.snaps.each(function(snapInfo) {
        stopDrag(component, snapInfo);
      });
      var target = dragConfig.getTarget(component.element);
      dragState.reset();
      dragConfig.onDrop(component, target);
    };
    var handlers = function(events2) {
      return function(dragConfig, dragState) {
        var updateStartState = function(comp) {
          dragState.setStartData(calcStartData(dragConfig, comp));
        };
        return derive$2(__spreadArray([run$1(windowScroll(), function(comp) {
          dragState.getStartData().each(function() {
            return updateStartState(comp);
          });
        })], events2(dragConfig, dragState, updateStartState), true));
      };
    };
    var init$2 = function(dragApi) {
      return derive$2([
        run$1(mousedown(), dragApi.forceDrop),
        run$1(mouseup(), dragApi.drop),
        run$1(mousemove(), function(comp, simulatedEvent) {
          dragApi.move(simulatedEvent.event);
        }),
        run$1(mouseout(), dragApi.delayDrop)
      ]);
    };
    var getData$1 = function(event) {
      return Optional.from(SugarPosition(event.x, event.y));
    };
    var getDelta$1 = function(old, nu2) {
      return SugarPosition(nu2.left - old.left, nu2.top - old.top);
    };
    var MouseData = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      getData: getData$1,
      getDelta: getDelta$1
    });
    var events$2 = function(dragConfig, dragState, updateStartState) {
      return [run$1(mousedown(), function(component, simulatedEvent) {
        var raw = simulatedEvent.event.raw;
        if (raw.button !== 0) {
          return;
        }
        simulatedEvent.stop();
        var stop$1 = function() {
          return stop(component, Optional.some(blocker), dragConfig, dragState);
        };
        var delayDrop = DelayedFunction(stop$1, 200);
        var dragApi = {
          drop: stop$1,
          delayDrop: delayDrop.schedule,
          forceDrop: stop$1,
          move: function(event) {
            delayDrop.cancel();
            move(component, dragConfig, dragState, MouseData, event);
          }
        };
        var blocker = createComponent(component, dragConfig.blockerClass, init$2(dragApi));
        var start4 = function() {
          updateStartState(component);
          instigate(component, blocker);
        };
        start4();
      })];
    };
    var schema$5 = __spreadArray(__spreadArray([], schema$6, true), [output$1("dragger", { handlers: handlers(events$2) })], false);
    var init$1 = function(dragApi) {
      return derive$2([
        run$1(touchstart(), dragApi.forceDrop),
        run$1(touchend(), dragApi.drop),
        run$1(touchcancel(), dragApi.drop),
        run$1(touchmove(), function(comp, simulatedEvent) {
          dragApi.move(simulatedEvent.event);
        })
      ]);
    };
    var getDataFrom = function(touches) {
      var touch2 = touches[0];
      return Optional.some(SugarPosition(touch2.clientX, touch2.clientY));
    };
    var getData = function(event) {
      var raw = event.raw;
      var touches = raw.touches;
      return touches.length === 1 ? getDataFrom(touches) : Optional.none();
    };
    var getDelta = function(old, nu2) {
      return SugarPosition(nu2.left - old.left, nu2.top - old.top);
    };
    var TouchData = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      getData,
      getDelta
    });
    var events$1 = function(dragConfig, dragState, updateStartState) {
      var blockerSingleton = value$1();
      var stopBlocking = function(component) {
        stop(component, blockerSingleton.get(), dragConfig, dragState);
        blockerSingleton.clear();
      };
      return [
        run$1(touchstart(), function(component, simulatedEvent) {
          simulatedEvent.stop();
          var stop2 = function() {
            return stopBlocking(component);
          };
          var dragApi = {
            drop: stop2,
            delayDrop: noop3,
            forceDrop: stop2,
            move: function(event) {
              move(component, dragConfig, dragState, TouchData, event);
            }
          };
          var blocker = createComponent(component, dragConfig.blockerClass, init$1(dragApi));
          blockerSingleton.set(blocker);
          var start4 = function() {
            updateStartState(component);
            instigate(component, blocker);
          };
          start4();
        }),
        run$1(touchmove(), function(component, simulatedEvent) {
          simulatedEvent.stop();
          move(component, dragConfig, dragState, TouchData, simulatedEvent.event);
        }),
        run$1(touchend(), function(component, simulatedEvent) {
          simulatedEvent.stop();
          stopBlocking(component);
        }),
        run$1(touchcancel(), stopBlocking)
      ];
    };
    var schema$4 = __spreadArray(__spreadArray([], schema$6, true), [output$1("dragger", { handlers: handlers(events$1) })], false);
    var events = function(dragConfig, dragState, updateStartState) {
      return __spreadArray(__spreadArray([], events$2(dragConfig, dragState, updateStartState), true), events$1(dragConfig, dragState, updateStartState), true);
    };
    var schema$3 = __spreadArray(__spreadArray([], schema$6, true), [output$1("dragger", { handlers: handlers(events) })], false);
    var mouse = schema$5;
    var touch = schema$4;
    var mouseOrTouch = schema$3;
    var DraggingBranches = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      mouse,
      touch,
      mouseOrTouch
    });
    var init = function() {
      var previous = Optional.none();
      var startData = Optional.none();
      var reset2 = function() {
        previous = Optional.none();
        startData = Optional.none();
      };
      var calculateDelta2 = function(mode, nu2) {
        var result = previous.map(function(old) {
          return mode.getDelta(old, nu2);
        });
        previous = Optional.some(nu2);
        return result;
      };
      var update = function(mode, dragEvent) {
        return mode.getData(dragEvent).bind(function(nuData) {
          return calculateDelta2(mode, nuData);
        });
      };
      var setStartData = function(data) {
        startData = Optional.some(data);
      };
      var getStartData = function() {
        return startData;
      };
      var readState = constant$1({});
      return nu$8({
        readState,
        reset: reset2,
        update,
        getStartData,
        setStartData
      });
    };
    var DragState = /* @__PURE__ */ Object.freeze({
      __proto__: null,
      init
    });
    var Dragging = createModes({
      branchKey: "mode",
      branches: DraggingBranches,
      name: "dragging",
      active: {
        events: function(dragConfig, dragState) {
          var dragger = dragConfig.dragger;
          return dragger.handlers(dragConfig, dragState);
        }
      },
      extra: {
        snap: function(sConfig) {
          return {
            sensor: sConfig.sensor,
            range: sConfig.range,
            output: sConfig.output,
            extra: Optional.from(sConfig.extra)
          };
        }
      },
      state: DragState,
      apis: DraggingApis
    });
    var snapWidth = 40;
    var snapOffset = snapWidth / 2;
    var calcSnap = function(selectorOpt, td, x2, y2, width2, height2) {
      return selectorOpt.fold(function() {
        return Dragging.snap({
          sensor: absolute(x2 - snapOffset, y2 - snapOffset),
          range: SugarPosition(width2, height2),
          output: absolute(Optional.some(x2), Optional.some(y2)),
          extra: { td }
        });
      }, function(selectorHandle) {
        var sensorLeft = x2 - snapOffset;
        var sensorTop = y2 - snapOffset;
        var sensorWidth = snapWidth;
        var sensorHeight = snapWidth;
        var rect2 = selectorHandle.element.dom.getBoundingClientRect();
        return Dragging.snap({
          sensor: absolute(sensorLeft, sensorTop),
          range: SugarPosition(sensorWidth, sensorHeight),
          output: absolute(Optional.some(x2 - rect2.width / 2), Optional.some(y2 - rect2.height / 2)),
          extra: { td }
        });
      });
    };
    var getSnapsConfig = function(getSnapPoints, cell, onChange) {
      var isSameCell = function(cellOpt, td) {
        return cellOpt.exists(function(currentTd) {
          return eq2(currentTd, td);
        });
      };
      return {
        getSnapPoints,
        leftAttr: "data-drag-left",
        topAttr: "data-drag-top",
        onSensor: function(component, extra) {
          var td = extra.td;
          if (!isSameCell(cell.get(), td)) {
            cell.set(td);
            onChange(td);
          }
        },
        mustSnap: true
      };
    };
    var createSelector = function(snaps) {
      return record(Button2.sketch({
        dom: {
          tag: "div",
          classes: ["tox-selector"]
        },
        buttonBehaviours: derive$1([
          Dragging.config({
            mode: "mouseOrTouch",
            blockerClass: "blocker",
            snaps
          }),
          Unselecting.config({})
        ]),
        eventOrder: {
          mousedown: [
            "dragging",
            "alloy.base.behaviour"
          ],
          touchstart: [
            "dragging",
            "alloy.base.behaviour"
          ]
        }
      }));
    };
    var setup$4 = function(editor, sink) {
      var tlTds = Cell([]);
      var brTds = Cell([]);
      var isVisible3 = Cell(false);
      var startCell = value$1();
      var finishCell = value$1();
      var getTopLeftSnap = function(td) {
        var box2 = absolute$2(td);
        return calcSnap(memTopLeft.getOpt(sink), td, box2.x, box2.y, box2.width, box2.height);
      };
      var getTopLeftSnaps = function() {
        return map$2(tlTds.get(), function(td) {
          return getTopLeftSnap(td);
        });
      };
      var getBottomRightSnap = function(td) {
        var box2 = absolute$2(td);
        return calcSnap(memBottomRight.getOpt(sink), td, box2.right, box2.bottom, box2.width, box2.height);
      };
      var getBottomRightSnaps = function() {
        return map$2(brTds.get(), function(td) {
          return getBottomRightSnap(td);
        });
      };
      var topLeftSnaps = getSnapsConfig(getTopLeftSnaps, startCell, function(start4) {
        finishCell.get().each(function(finish) {
          editor.fire("TableSelectorChange", {
            start: start4,
            finish
          });
        });
      });
      var bottomRightSnaps = getSnapsConfig(getBottomRightSnaps, finishCell, function(finish) {
        startCell.get().each(function(start4) {
          editor.fire("TableSelectorChange", {
            start: start4,
            finish
          });
        });
      });
      var memTopLeft = createSelector(topLeftSnaps);
      var memBottomRight = createSelector(bottomRightSnaps);
      var topLeft = build$1(memTopLeft.asSpec());
      var bottomRight = build$1(memBottomRight.asSpec());
      var showOrHideHandle = function(selector, cell, isAbove, isBelow) {
        var cellRect = cell.dom.getBoundingClientRect();
        remove$6(selector.element, "display");
        var viewportHeight = defaultView(SugarElement.fromDom(editor.getBody())).dom.innerHeight;
        var aboveViewport = isAbove(cellRect);
        var belowViewport = isBelow(cellRect, viewportHeight);
        if (aboveViewport || belowViewport) {
          set$7(selector.element, "display", "none");
        }
      };
      var snapTo2 = function(selector, cell, getSnapConfig, pos) {
        var snap2 = getSnapConfig(cell);
        Dragging.snapTo(selector, snap2);
        var isAbove = function(rect2) {
          return rect2[pos] < 0;
        };
        var isBelow = function(rect2, viewportHeight) {
          return rect2[pos] > viewportHeight;
        };
        showOrHideHandle(selector, cell, isAbove, isBelow);
      };
      var snapTopLeft = function(cell) {
        return snapTo2(topLeft, cell, getTopLeftSnap, "top");
      };
      var snapLastTopLeft = function() {
        return startCell.get().each(snapTopLeft);
      };
      var snapBottomRight = function(cell) {
        return snapTo2(bottomRight, cell, getBottomRightSnap, "bottom");
      };
      var snapLastBottomRight = function() {
        return finishCell.get().each(snapBottomRight);
      };
      if (detect$1().deviceType.isTouch()) {
        editor.on("TableSelectionChange", function(e2) {
          if (!isVisible3.get()) {
            attach(sink, topLeft);
            attach(sink, bottomRight);
            isVisible3.set(true);
          }
          startCell.set(e2.start);
          finishCell.set(e2.finish);
          e2.otherCells.each(function(otherCells) {
            tlTds.set(otherCells.upOrLeftCells);
            brTds.set(otherCells.downOrRightCells);
            snapTopLeft(e2.start);
            snapBottomRight(e2.finish);
          });
        });
        editor.on("ResizeEditor ResizeWindow ScrollContent", function() {
          snapLastTopLeft();
          snapLastBottomRight();
        });
        editor.on("TableSelectionClear", function() {
          if (isVisible3.get()) {
            detach(topLeft);
            detach(bottomRight);
            isVisible3.set(false);
          }
          startCell.clear();
          finishCell.clear();
        });
      }
    };
    var isHidden = function(elm) {
      if (elm.nodeType === 1) {
        if (elm.nodeName === "BR" || !!elm.getAttribute("data-mce-bogus")) {
          return true;
        }
        if (elm.getAttribute("data-mce-type") === "bookmark") {
          return true;
        }
      }
      return false;
    };
    var renderElementPath = function(editor, settings, providersBackstage) {
      if (!settings.delimiter) {
        settings.delimiter = "\xBB";
      }
      var getDataPath = function(data) {
        var parts2 = data || [];
        var newPathElements = map$2(parts2, function(part2, index) {
          return Button2.sketch({
            dom: {
              tag: "div",
              classes: ["tox-statusbar__path-item"],
              attributes: {
                "role": "button",
                "data-index": index,
                "tab-index": -1,
                "aria-level": index + 1
              },
              innerHtml: part2.name
            },
            action: function(_btn) {
              editor.focus();
              editor.selection.select(part2.element);
              editor.nodeChanged();
            },
            buttonBehaviours: derive$1([
              DisablingConfigs.button(providersBackstage.isDisabled),
              receivingConfig()
            ])
          });
        });
        var divider = {
          dom: {
            tag: "div",
            classes: ["tox-statusbar__path-divider"],
            attributes: { "aria-hidden": true },
            innerHtml: " " + settings.delimiter + " "
          }
        };
        return foldl(newPathElements.slice(1), function(acc, element2) {
          var newAcc = acc;
          newAcc.push(divider);
          newAcc.push(element2);
          return newAcc;
        }, [newPathElements[0]]);
      };
      var updatePath = function(parents) {
        var newPath = [];
        var i2 = parents.length;
        while (i2-- > 0) {
          var parent_1 = parents[i2];
          if (parent_1.nodeType === 1 && !isHidden(parent_1)) {
            var args = editor.fire("ResolveName", {
              name: parent_1.nodeName.toLowerCase(),
              target: parent_1
            });
            if (!args.isDefaultPrevented()) {
              newPath.push({
                name: args.name,
                element: parent_1
              });
            }
            if (args.isPropagationStopped()) {
              break;
            }
          }
        }
        return newPath;
      };
      return {
        dom: {
          tag: "div",
          classes: ["tox-statusbar__path"],
          attributes: { role: "navigation" }
        },
        behaviours: derive$1([
          Keying.config({
            mode: "flow",
            selector: "div[role=button]"
          }),
          Disabling.config({ disabled: providersBackstage.isDisabled }),
          receivingConfig(),
          Tabstopping.config({}),
          Replacing.config({}),
          config("elementPathEvents", [runOnAttached(function(comp, _e2) {
            editor.shortcuts.add("alt+F11", "focus statusbar elementpath", function() {
              return Keying.focusIn(comp);
            });
            editor.on("NodeChange", function(e2) {
              var newPath = updatePath(e2.parents);
              if (newPath.length > 0) {
                Replacing.set(comp, getDataPath(newPath));
              } else {
                Replacing.set(comp, []);
              }
            });
          })])
        ]),
        components: []
      };
    };
    var ResizeTypes;
    (function(ResizeTypes2) {
      ResizeTypes2[ResizeTypes2["None"] = 0] = "None";
      ResizeTypes2[ResizeTypes2["Both"] = 1] = "Both";
      ResizeTypes2[ResizeTypes2["Vertical"] = 2] = "Vertical";
    })(ResizeTypes || (ResizeTypes = {}));
    var getDimensions = function(editor, deltas, resizeType, originalHeight, originalWidth) {
      var dimensions = {};
      dimensions.height = calcCappedSize(originalHeight + deltas.top, getMinHeightSetting(editor), getMaxHeightSetting(editor));
      if (resizeType === ResizeTypes.Both) {
        dimensions.width = calcCappedSize(originalWidth + deltas.left, getMinWidthSetting(editor), getMaxWidthSetting(editor));
      }
      return dimensions;
    };
    var resize = function(editor, deltas, resizeType) {
      var container = SugarElement.fromDom(editor.getContainer());
      var dimensions = getDimensions(editor, deltas, resizeType, get$b(container), get$a(container));
      each2(dimensions, function(val, dim) {
        return set$7(container, dim, numToPx(val));
      });
      fireResizeEditor(editor);
    };
    var getResizeType = function(editor) {
      var fallback2 = !editor.hasPlugin("autoresize");
      var resize2 = editor.getParam("resize", fallback2);
      if (resize2 === false) {
        return ResizeTypes.None;
      } else if (resize2 === "both") {
        return ResizeTypes.Both;
      } else {
        return ResizeTypes.Vertical;
      }
    };
    var keyboardHandler = function(editor, resizeType, x2, y2) {
      var scale2 = 20;
      var delta = SugarPosition(x2 * scale2, y2 * scale2);
      resize(editor, delta, resizeType);
      return Optional.some(true);
    };
    var renderResizeHandler = function(editor, providersBackstage) {
      var resizeType = getResizeType(editor);
      if (resizeType === ResizeTypes.None) {
        return Optional.none();
      }
      return Optional.some(render$3("resize-handle", {
        tag: "div",
        classes: ["tox-statusbar__resize-handle"],
        attributes: { title: providersBackstage.translate("Resize") },
        behaviours: [
          Dragging.config({
            mode: "mouse",
            repositionTarget: false,
            onDrag: function(_comp, _target, delta) {
              return resize(editor, delta, resizeType);
            },
            blockerClass: "tox-blocker"
          }),
          Keying.config({
            mode: "special",
            onLeft: function() {
              return keyboardHandler(editor, resizeType, -1, 0);
            },
            onRight: function() {
              return keyboardHandler(editor, resizeType, 1, 0);
            },
            onUp: function() {
              return keyboardHandler(editor, resizeType, 0, -1);
            },
            onDown: function() {
              return keyboardHandler(editor, resizeType, 0, 1);
            }
          }),
          Tabstopping.config({}),
          Focusing.config({})
        ]
      }, providersBackstage.icons));
    };
    var renderWordCount = function(editor, providersBackstage) {
      var _a2;
      var replaceCountText = function(comp, count2, mode) {
        return Replacing.set(comp, [text(providersBackstage.translate([
          "{0} " + mode,
          count2[mode]
        ]))]);
      };
      return Button2.sketch({
        dom: {
          tag: "button",
          classes: ["tox-statusbar__wordcount"]
        },
        components: [],
        buttonBehaviours: derive$1([
          DisablingConfigs.button(providersBackstage.isDisabled),
          receivingConfig(),
          Tabstopping.config({}),
          Replacing.config({}),
          Representing.config({
            store: {
              mode: "memory",
              initialValue: {
                mode: "words",
                count: {
                  words: 0,
                  characters: 0
                }
              }
            }
          }),
          config("wordcount-events", [
            runOnExecute$1(function(comp) {
              var currentVal = Representing.getValue(comp);
              var newMode = currentVal.mode === "words" ? "characters" : "words";
              Representing.setValue(comp, {
                mode: newMode,
                count: currentVal.count
              });
              replaceCountText(comp, currentVal.count, newMode);
            }),
            runOnAttached(function(comp) {
              editor.on("wordCountUpdate", function(e2) {
                var mode = Representing.getValue(comp).mode;
                Representing.setValue(comp, {
                  mode,
                  count: e2.wordCount
                });
                replaceCountText(comp, e2.wordCount, mode);
              });
            })
          ])
        ]),
        eventOrder: (_a2 = {}, _a2[execute$5()] = [
          "disabling",
          "alloy.base.behaviour",
          "wordcount-events"
        ], _a2)
      });
    };
    var renderStatusbar = function(editor, providersBackstage) {
      var renderBranding = function() {
        var label = global$e.translate([
          "Powered by {0}",
          "Tiny"
        ]);
        var linkHtml = '<a href="https://www.tiny.cloud/?utm_campaign=editor_referral&amp;utm_medium=poweredby&amp;utm_source=tinymce&amp;utm_content=v5" rel="noopener" target="_blank" tabindex="-1" aria-label="' + label + '">' + label + "</a>";
        return {
          dom: {
            tag: "span",
            classes: ["tox-statusbar__branding"],
            innerHtml: linkHtml
          }
        };
      };
      var getTextComponents = function() {
        var components2 = [];
        if (editor.getParam("elementpath", true, "boolean")) {
          components2.push(renderElementPath(editor, {}, providersBackstage));
        }
        if (editor.hasPlugin("wordcount")) {
          components2.push(renderWordCount(editor, providersBackstage));
        }
        if (editor.getParam("branding", true, "boolean")) {
          components2.push(renderBranding());
        }
        if (components2.length > 0) {
          return [{
            dom: {
              tag: "div",
              classes: ["tox-statusbar__text-container"]
            },
            components: components2
          }];
        }
        return [];
      };
      var getComponents = function() {
        var components2 = getTextComponents();
        var resizeHandler = renderResizeHandler(editor, providersBackstage);
        return components2.concat(resizeHandler.toArray());
      };
      return {
        dom: {
          tag: "div",
          classes: ["tox-statusbar"]
        },
        components: getComponents()
      };
    };
    var setup$3 = function(editor) {
      var _a2;
      var isInline = editor.inline;
      var mode = isInline ? Inline : Iframe;
      var header = isStickyToolbar(editor) ? StickyHeader : StaticHeader;
      var lazyOuterContainer = Optional.none();
      var platform2 = detect$1();
      var isIE = platform2.browser.isIE();
      var platformClasses = isIE ? ["tox-platform-ie"] : [];
      var isTouch2 = platform2.deviceType.isTouch();
      var touchPlatformClass = "tox-platform-touch";
      var deviceClasses = isTouch2 ? [touchPlatformClass] : [];
      var isToolbarBottom = isToolbarLocationBottom(editor);
      var uiContainer = getUiContainer(editor);
      var dirAttributes = global$e.isRtl() ? { attributes: { dir: "rtl" } } : {};
      var verticalDirAttributes = { attributes: (_a2 = {}, _a2[Attribute] = isToolbarBottom ? AttributeValue.BottomToTop : AttributeValue.TopToBottom, _a2) };
      var lazyHeader = function() {
        return lazyOuterContainer.bind(OuterContainer.getHeader);
      };
      var isHeaderDocked = function() {
        return header.isDocked(lazyHeader);
      };
      var resizeUiMothership = function() {
        set$7(uiMothership.element, "width", document.body.clientWidth + "px");
      };
      var makeSinkDefinition = function() {
        var isGridUiContainer = eq2(body(), uiContainer) && get$c(uiContainer, "display") === "grid";
        var sinkSpec = {
          dom: __assign({
            tag: "div",
            classes: [
              "tox",
              "tox-silver-sink",
              "tox-tinymce-aux"
            ].concat(platformClasses).concat(deviceClasses)
          }, dirAttributes),
          behaviours: derive$1([Positioning.config({
            useFixed: function() {
              return isHeaderDocked();
            }
          })])
        };
        var reactiveWidthSpec = {
          dom: { styles: { width: document.body.clientWidth + "px" } },
          events: derive$2([run$1(windowResize(), resizeUiMothership)])
        };
        return deepMerge(sinkSpec, isGridUiContainer ? reactiveWidthSpec : {});
      };
      var sink = build$1(makeSinkDefinition());
      var lazySink = function() {
        return Result.value(sink);
      };
      var memAnchorBar = record({
        dom: {
          tag: "div",
          classes: ["tox-anchorbar"]
        }
      });
      var lazyAnchorBar = function() {
        return lazyOuterContainer.bind(function(container) {
          return memAnchorBar.getOpt(container);
        }).getOrDie("Could not find a anchor bar element");
      };
      var lazyToolbar = function() {
        return lazyOuterContainer.bind(function(container) {
          return OuterContainer.getToolbar(container);
        }).getOrDie("Could not find more toolbar element");
      };
      var lazyThrobber = function() {
        return lazyOuterContainer.bind(function(container) {
          return OuterContainer.getThrobber(container);
        }).getOrDie("Could not find throbber element");
      };
      var backstage = init$7(sink, editor, lazyAnchorBar);
      var partMenubar2 = OuterContainer.parts.menubar({
        dom: {
          tag: "div",
          classes: ["tox-menubar"]
        },
        backstage,
        onEscape: function() {
          editor.focus();
        }
      });
      var toolbarMode = getToolbarMode(editor);
      var partToolbar2 = OuterContainer.parts.toolbar(__assign({
        dom: {
          tag: "div",
          classes: ["tox-toolbar"]
        },
        getSink: lazySink,
        providers: backstage.shared.providers,
        onEscape: function() {
          editor.focus();
        },
        type: toolbarMode,
        lazyToolbar,
        lazyHeader: function() {
          return lazyHeader().getOrDie("Could not find header element");
        }
      }, verticalDirAttributes));
      var partMultipleToolbar2 = OuterContainer.parts["multiple-toolbar"]({
        dom: {
          tag: "div",
          classes: ["tox-toolbar-overlord"]
        },
        providers: backstage.shared.providers,
        onEscape: function() {
          editor.focus();
        },
        type: toolbarMode
      });
      var partSocket2 = OuterContainer.parts.socket({
        dom: {
          tag: "div",
          classes: ["tox-edit-area"]
        }
      });
      var partSidebar2 = OuterContainer.parts.sidebar({
        dom: {
          tag: "div",
          classes: ["tox-sidebar"]
        }
      });
      var partThrobber2 = OuterContainer.parts.throbber({
        dom: {
          tag: "div",
          classes: ["tox-throbber"]
        },
        backstage
      });
      var sb = editor.getParam("statusbar", true, "boolean");
      var statusbar = sb && !isInline ? Optional.some(renderStatusbar(editor, backstage.shared.providers)) : Optional.none();
      var socketSidebarContainer = {
        dom: {
          tag: "div",
          classes: ["tox-sidebar-wrap"]
        },
        components: [
          partSocket2,
          partSidebar2
        ]
      };
      var hasMultipleToolbar = isMultipleToolbars(editor);
      var hasToolbar = isToolbarEnabled(editor);
      var hasMenubar = isMenubarEnabled(editor);
      var getPartToolbar = function() {
        if (hasMultipleToolbar) {
          return [partMultipleToolbar2];
        } else if (hasToolbar) {
          return [partToolbar2];
        } else {
          return [];
        }
      };
      var partHeader2 = OuterContainer.parts.header({
        dom: __assign({
          tag: "div",
          classes: ["tox-editor-header"]
        }, verticalDirAttributes),
        components: flatten([
          hasMenubar ? [partMenubar2] : [],
          getPartToolbar(),
          useFixedContainer(editor) ? [] : [memAnchorBar.asSpec()]
        ]),
        sticky: isStickyToolbar(editor),
        editor,
        sharedBackstage: backstage.shared
      });
      var editorComponents = flatten([
        isToolbarBottom ? [] : [partHeader2],
        isInline ? [] : [socketSidebarContainer],
        isToolbarBottom ? [partHeader2] : []
      ]);
      var editorContainer = {
        dom: {
          tag: "div",
          classes: ["tox-editor-container"]
        },
        components: editorComponents
      };
      var containerComponents = flatten([
        [editorContainer],
        isInline ? [] : statusbar.toArray(),
        [partThrobber2]
      ]);
      var isHidden2 = isDistractionFree(editor);
      var attributes = __assign(__assign({ role: "application" }, global$e.isRtl() ? { dir: "rtl" } : {}), isHidden2 ? { "aria-hidden": "true" } : {});
      var outerContainer = build$1(OuterContainer.sketch({
        dom: {
          tag: "div",
          classes: [
            "tox",
            "tox-tinymce"
          ].concat(isInline ? ["tox-tinymce-inline"] : []).concat(isToolbarBottom ? ["tox-tinymce--toolbar-bottom"] : []).concat(deviceClasses).concat(platformClasses),
          styles: __assign({ visibility: "hidden" }, isHidden2 ? {
            opacity: "0",
            border: "0"
          } : {}),
          attributes
        },
        components: containerComponents,
        behaviours: derive$1([
          receivingConfig(),
          Disabling.config({ disableClass: "tox-tinymce--disabled" }),
          Keying.config({
            mode: "cyclic",
            selector: ".tox-menubar, .tox-toolbar, .tox-toolbar__primary, .tox-toolbar__overflow--open, .tox-sidebar__overflow--open, .tox-statusbar__path, .tox-statusbar__wordcount, .tox-statusbar__branding a, .tox-statusbar__resize-handle"
          })
        ])
      }));
      lazyOuterContainer = Optional.some(outerContainer);
      editor.shortcuts.add("alt+F9", "focus menubar", function() {
        OuterContainer.focusMenubar(outerContainer);
      });
      editor.shortcuts.add("alt+F10", "focus toolbar", function() {
        OuterContainer.focusToolbar(outerContainer);
      });
      editor.addCommand("ToggleToolbarDrawer", function() {
        OuterContainer.toggleToolbarDrawer(outerContainer);
      });
      editor.addQueryStateHandler("ToggleToolbarDrawer", function() {
        return OuterContainer.isToolbarDrawerToggled(outerContainer);
      });
      var mothership = takeover(outerContainer);
      var uiMothership = takeover(sink);
      setup$b(editor, mothership, uiMothership);
      var getUi = function() {
        var channels = {
          broadcastAll: uiMothership.broadcast,
          broadcastOn: uiMothership.broadcastOn,
          register: noop3
        };
        return { channels };
      };
      var setEditorSize = function() {
        var parsedHeight = numToPx(getHeightWithFallback(editor));
        var parsedWidth = numToPx(getWidthWithFallback(editor));
        if (!editor.inline) {
          if (isValidValue("div", "width", parsedWidth)) {
            set$7(outerContainer.element, "width", parsedWidth);
          }
          if (isValidValue("div", "height", parsedHeight)) {
            set$7(outerContainer.element, "height", parsedHeight);
          } else {
            set$7(outerContainer.element, "height", "200px");
          }
        }
        return parsedHeight;
      };
      var renderUI = function() {
        header.setup(editor, backstage.shared, lazyHeader);
        setup$6(editor, backstage);
        setup$5(editor, lazySink, backstage);
        setup$8(editor);
        setup$7(editor, lazyThrobber, backstage.shared);
        map$12(getToolbarGroups(editor), function(toolbarGroupButtonConfig, name2) {
          editor.ui.registry.addGroupToolbarButton(name2, toolbarGroupButtonConfig);
        });
        var _a3 = editor.ui.registry.getAll(), buttons = _a3.buttons, menuItems = _a3.menuItems, contextToolbars = _a3.contextToolbars, sidebars = _a3.sidebars;
        var toolbarOpt = getMultipleToolbarsSetting(editor);
        var rawUiConfig = {
          menuItems,
          menus: getMenus(editor),
          menubar: getMenubar(editor),
          toolbar: toolbarOpt.getOrThunk(function() {
            return getToolbar(editor);
          }),
          allowToolbarGroups: toolbarMode === ToolbarMode.floating,
          buttons,
          sidebar: sidebars
        };
        register$7(editor, contextToolbars, sink, { backstage });
        setup$4(editor, sink);
        var elm = editor.getElement();
        var height2 = setEditorSize();
        var uiComponents = {
          mothership,
          uiMothership,
          outerContainer
        };
        var args = {
          targetNode: elm,
          height: height2
        };
        return mode.render(editor, uiComponents, rawUiConfig, backstage, args);
      };
      return {
        mothership,
        uiMothership,
        backstage,
        renderUI,
        getUi
      };
    };
    var describedBy = function(describedElement, describeElement) {
      var describeId = Optional.from(get$d(describedElement, "id")).fold(function() {
        var id2 = generate$6("dialog-describe");
        set$8(describeElement, "id", id2);
        return id2;
      }, identity$1);
      set$8(describedElement, "aria-describedby", describeId);
    };
    var labelledBy = function(labelledElement, labelElement) {
      var labelId = getOpt(labelledElement, "id").fold(function() {
        var id2 = generate$6("dialog-label");
        set$8(labelElement, "id", id2);
        return id2;
      }, identity$1);
      set$8(labelledElement, "aria-labelledby", labelId);
    };
    var schema$2 = constant$1([
      required$1("lazySink"),
      option("dragBlockClass"),
      defaultedFunction("getBounds", win),
      defaulted("useTabstopAt", always),
      defaulted("eventOrder", {}),
      field("modalBehaviours", [Keying]),
      onKeyboardHandler("onExecute"),
      onStrictKeyboardHandler("onEscape")
    ]);
    var basic = { sketch: identity$1 };
    var parts$2 = constant$1([
      optional({
        name: "draghandle",
        overrides: function(detail, spec) {
          return {
            behaviours: derive$1([Dragging.config({
              mode: "mouse",
              getTarget: function(handle2) {
                return ancestor(handle2, '[role="dialog"]').getOr(handle2);
              },
              blockerClass: detail.dragBlockClass.getOrDie(new Error("The drag blocker class was not specified for a dialog with a drag handle: \n" + JSON.stringify(spec, null, 2)).message),
              getBounds: detail.getDragBounds
            })])
          };
        }
      }),
      required({
        schema: [required$1("dom")],
        name: "title"
      }),
      required({
        factory: basic,
        schema: [required$1("dom")],
        name: "close"
      }),
      required({
        factory: basic,
        schema: [required$1("dom")],
        name: "body"
      }),
      optional({
        factory: basic,
        schema: [required$1("dom")],
        name: "footer"
      }),
      external$1({
        factory: {
          sketch: function(spec, detail) {
            return __assign(__assign({}, spec), {
              dom: detail.dom,
              components: detail.components
            });
          }
        },
        schema: [
          defaulted("dom", {
            tag: "div",
            styles: {
              position: "fixed",
              left: "0px",
              top: "0px",
              right: "0px",
              bottom: "0px"
            }
          }),
          defaulted("components", [])
        ],
        name: "blocker"
      })
    ]);
    var factory$4 = function(detail, components2, spec, externals) {
      var _a2;
      var dialogComp = value$1();
      var showDialog = function(dialog) {
        dialogComp.set(dialog);
        var sink = detail.lazySink(dialog).getOrDie();
        var externalBlocker = externals.blocker();
        var blocker = sink.getSystem().build(__assign(__assign({}, externalBlocker), {
          components: externalBlocker.components.concat([premade(dialog)]),
          behaviours: derive$1([
            Focusing.config({}),
            config("dialog-blocker-events", [runOnSource(focusin(), function() {
              Keying.focusIn(dialog);
            })])
          ])
        }));
        attach(sink, blocker);
        Keying.focusIn(dialog);
      };
      var hideDialog = function(dialog) {
        dialogComp.clear();
        parent(dialog.element).each(function(blockerDom) {
          dialog.getSystem().getByDom(blockerDom).each(function(blocker) {
            detach(blocker);
          });
        });
      };
      var getDialogBody = function(dialog) {
        return getPartOrDie(dialog, detail, "body");
      };
      var getDialogFooter = function(dialog) {
        return getPartOrDie(dialog, detail, "footer");
      };
      var setBusy = function(dialog, getBusySpec2) {
        Blocking.block(dialog, getBusySpec2);
      };
      var setIdle = function(dialog) {
        Blocking.unblock(dialog);
      };
      var modalEventsId = generate$6("modal-events");
      var eventOrder = __assign(__assign({}, detail.eventOrder), (_a2 = {}, _a2[attachedToDom()] = [modalEventsId].concat(detail.eventOrder["alloy.system.attached"] || []), _a2));
      return {
        uid: detail.uid,
        dom: detail.dom,
        components: components2,
        apis: {
          show: showDialog,
          hide: hideDialog,
          getBody: getDialogBody,
          getFooter: getDialogFooter,
          setIdle,
          setBusy
        },
        eventOrder,
        domModification: {
          attributes: {
            "role": "dialog",
            "aria-modal": "true"
          }
        },
        behaviours: augment(detail.modalBehaviours, [
          Replacing.config({}),
          Keying.config({
            mode: "cyclic",
            onEnter: detail.onExecute,
            onEscape: detail.onEscape,
            useTabstopAt: detail.useTabstopAt
          }),
          Blocking.config({ getRoot: dialogComp.get }),
          config(modalEventsId, [runOnAttached(function(c2) {
            labelledBy(c2.element, getPartOrDie(c2, detail, "title").element);
            describedBy(c2.element, getPartOrDie(c2, detail, "body").element);
          })])
        ])
      };
    };
    var ModalDialog = composite({
      name: "ModalDialog",
      configFields: schema$2(),
      partFields: parts$2(),
      factory: factory$4,
      apis: {
        show: function(apis, dialog) {
          apis.show(dialog);
        },
        hide: function(apis, dialog) {
          apis.hide(dialog);
        },
        getBody: function(apis, dialog) {
          return apis.getBody(dialog);
        },
        getFooter: function(apis, dialog) {
          return apis.getFooter(dialog);
        },
        setBusy: function(apis, dialog, getBusySpec2) {
          apis.setBusy(dialog, getBusySpec2);
        },
        setIdle: function(apis, dialog) {
          apis.setIdle(dialog);
        }
      }
    });
    var dialogToggleMenuItemSchema = objOf([
      requiredString("type"),
      requiredString("name")
    ].concat(commonMenuItemFields));
    var dialogToggleMenuItemDataProcessor = boolean;
    var baseFooterButtonFields = [
      field$1("name", "name", defaultedThunk(function() {
        return generate$6("button-name");
      }), string),
      optionString("icon"),
      defaultedStringEnum("align", "end", [
        "start",
        "end"
      ]),
      defaultedBoolean("primary", false),
      defaultedBoolean("disabled", false)
    ];
    var dialogFooterButtonFields = __spreadArray(__spreadArray([], baseFooterButtonFields, true), [requiredString("text")], false);
    var normalFooterButtonFields = __spreadArray([requiredStringEnum("type", [
      "submit",
      "cancel",
      "custom"
    ])], dialogFooterButtonFields, true);
    var menuFooterButtonFields = __spreadArray([
      requiredStringEnum("type", ["menu"]),
      optionString("text"),
      optionString("tooltip"),
      optionString("icon"),
      requiredArrayOf("items", dialogToggleMenuItemSchema)
    ], baseFooterButtonFields, true);
    var dialogFooterButtonSchema = choose$1("type", {
      submit: normalFooterButtonFields,
      cancel: normalFooterButtonFields,
      custom: normalFooterButtonFields,
      menu: menuFooterButtonFields
    });
    var alertBannerFields = [
      requiredString("type"),
      requiredString("text"),
      requiredStringEnum("level", [
        "info",
        "warn",
        "error",
        "success"
      ]),
      requiredString("icon"),
      defaulted("url", "")
    ];
    var alertBannerSchema = objOf(alertBannerFields);
    var createBarFields = function(itemsField) {
      return [
        requiredString("type"),
        itemsField
      ];
    };
    var buttonFields = [
      requiredString("type"),
      requiredString("text"),
      defaultedBoolean("disabled", false),
      defaultedBoolean("primary", false),
      field$1("name", "name", defaultedThunk(function() {
        return generate$6("button-name");
      }), string),
      optionString("icon"),
      defaultedBoolean("borderless", false)
    ];
    var buttonSchema = objOf(buttonFields);
    var checkboxFields = [
      requiredString("type"),
      requiredString("name"),
      requiredString("label"),
      defaultedBoolean("disabled", false)
    ];
    var checkboxSchema = objOf(checkboxFields);
    var checkboxDataProcessor = boolean;
    var formComponentFields = [
      requiredString("type"),
      requiredString("name")
    ];
    var formComponentWithLabelFields = formComponentFields.concat([optionString("label")]);
    var collectionFields = formComponentWithLabelFields.concat([defaulted("columns", "auto")]);
    var collectionSchema = objOf(collectionFields);
    var collectionDataProcessor = arrOfObj([
      requiredString("value"),
      requiredString("text"),
      requiredString("icon")
    ]);
    var colorInputFields = formComponentWithLabelFields;
    var colorInputSchema = objOf(colorInputFields);
    var colorInputDataProcessor = string;
    var colorPickerFields = formComponentWithLabelFields;
    var colorPickerSchema = objOf(colorPickerFields);
    var colorPickerDataProcessor = string;
    var customEditorFields = formComponentFields.concat([
      defaultedString("tag", "textarea"),
      requiredString("scriptId"),
      requiredString("scriptUrl"),
      defaultedPostMsg("settings", void 0)
    ]);
    var customEditorFieldsOld = formComponentFields.concat([
      defaultedString("tag", "textarea"),
      requiredFunction("init")
    ]);
    var customEditorSchema = valueOf(function(v2) {
      return asRaw("customeditor.old", objOfOnly(customEditorFieldsOld), v2).orThunk(function() {
        return asRaw("customeditor.new", objOfOnly(customEditorFields), v2);
      });
    });
    var customEditorDataProcessor = string;
    var dropZoneFields = formComponentWithLabelFields;
    var dropZoneSchema = objOf(dropZoneFields);
    var dropZoneDataProcessor = arrOfVal();
    var createGridFields = function(itemsField) {
      return [
        requiredString("type"),
        requiredNumber("columns"),
        itemsField
      ];
    };
    var htmlPanelFields = [
      requiredString("type"),
      requiredString("html"),
      defaultedStringEnum("presets", "presentation", [
        "presentation",
        "document"
      ])
    ];
    var htmlPanelSchema = objOf(htmlPanelFields);
    var iframeFields = formComponentWithLabelFields.concat([defaultedBoolean("sandboxed", true)]);
    var iframeSchema = objOf(iframeFields);
    var iframeDataProcessor = string;
    var imageToolsFields = formComponentWithLabelFields.concat([requiredOf("currentState", objOf([
      required$1("blob"),
      requiredString("url")
    ]))]);
    var imageToolsSchema = objOf(imageToolsFields);
    var inputFields = formComponentWithLabelFields.concat([
      optionString("inputMode"),
      optionString("placeholder"),
      defaultedBoolean("maximized", false),
      defaultedBoolean("disabled", false)
    ]);
    var inputSchema = objOf(inputFields);
    var inputDataProcessor = string;
    var createLabelFields = function(itemsField) {
      return [
        requiredString("type"),
        requiredString("label"),
        itemsField
      ];
    };
    var listBoxSingleItemFields = [
      requiredString("text"),
      requiredString("value")
    ];
    var listBoxNestedItemFields = [
      requiredString("text"),
      requiredArrayOf("items", thunkOf("items", function() {
        return listBoxItemSchema;
      }))
    ];
    var listBoxItemSchema = oneOf([
      objOf(listBoxSingleItemFields),
      objOf(listBoxNestedItemFields)
    ]);
    var listBoxFields = formComponentWithLabelFields.concat([
      requiredArrayOf("items", listBoxItemSchema),
      defaultedBoolean("disabled", false)
    ]);
    var listBoxSchema = objOf(listBoxFields);
    var listBoxDataProcessor = string;
    var selectBoxFields = formComponentWithLabelFields.concat([
      requiredArrayOfObj("items", [
        requiredString("text"),
        requiredString("value")
      ]),
      defaultedNumber("size", 1),
      defaultedBoolean("disabled", false)
    ]);
    var selectBoxSchema = objOf(selectBoxFields);
    var selectBoxDataProcessor = string;
    var sizeInputFields = formComponentWithLabelFields.concat([
      defaultedBoolean("constrain", true),
      defaultedBoolean("disabled", false)
    ]);
    var sizeInputSchema = objOf(sizeInputFields);
    var sizeInputDataProcessor = objOf([
      requiredString("width"),
      requiredString("height")
    ]);
    var tableFields = [
      requiredString("type"),
      requiredArrayOf("header", string),
      requiredArrayOf("cells", arrOf(string))
    ];
    var tableSchema = objOf(tableFields);
    var textAreaFields = formComponentWithLabelFields.concat([
      optionString("placeholder"),
      defaultedBoolean("maximized", false),
      defaultedBoolean("disabled", false)
    ]);
    var textAreaSchema = objOf(textAreaFields);
    var textAreaDataProcessor = string;
    var urlInputFields = formComponentWithLabelFields.concat([
      defaultedStringEnum("filetype", "file", [
        "image",
        "media",
        "file"
      ]),
      defaulted("disabled", false)
    ]);
    var urlInputSchema = objOf(urlInputFields);
    var urlInputDataProcessor = objOf([
      requiredString("value"),
      defaulted("meta", {})
    ]);
    var createItemsField = function(name2) {
      return field$1("items", "items", required$2(), arrOf(valueOf(function(v2) {
        return asRaw("Checking item of " + name2, itemSchema, v2).fold(function(sErr) {
          return Result.error(formatError(sErr));
        }, function(passValue) {
          return Result.value(passValue);
        });
      })));
    };
    var itemSchema = valueThunk(function() {
      return choose$2("type", {
        alertbanner: alertBannerSchema,
        bar: objOf(createBarFields(createItemsField("bar"))),
        button: buttonSchema,
        checkbox: checkboxSchema,
        colorinput: colorInputSchema,
        colorpicker: colorPickerSchema,
        dropzone: dropZoneSchema,
        grid: objOf(createGridFields(createItemsField("grid"))),
        iframe: iframeSchema,
        input: inputSchema,
        listbox: listBoxSchema,
        selectbox: selectBoxSchema,
        sizeinput: sizeInputSchema,
        textarea: textAreaSchema,
        urlinput: urlInputSchema,
        customeditor: customEditorSchema,
        htmlpanel: htmlPanelSchema,
        imagetools: imageToolsSchema,
        collection: collectionSchema,
        label: objOf(createLabelFields(createItemsField("label"))),
        table: tableSchema,
        panel: panelSchema
      });
    });
    var panelFields = [
      requiredString("type"),
      defaulted("classes", []),
      requiredArrayOf("items", itemSchema)
    ];
    var panelSchema = objOf(panelFields);
    var tabFields = [
      field$1("name", "name", defaultedThunk(function() {
        return generate$6("tab-name");
      }), string),
      requiredString("title"),
      requiredArrayOf("items", itemSchema)
    ];
    var tabPanelFields = [
      requiredString("type"),
      requiredArrayOfObj("tabs", tabFields)
    ];
    var tabPanelSchema = objOf(tabPanelFields);
    var dialogButtonFields = dialogFooterButtonFields;
    var dialogButtonSchema = dialogFooterButtonSchema;
    var dialogSchema = objOf([
      requiredString("title"),
      requiredOf("body", choose$2("type", {
        panel: panelSchema,
        tabpanel: tabPanelSchema
      })),
      defaultedString("size", "normal"),
      requiredArrayOf("buttons", dialogButtonSchema),
      defaulted("initialData", {}),
      defaultedFunction("onAction", noop3),
      defaultedFunction("onChange", noop3),
      defaultedFunction("onSubmit", noop3),
      defaultedFunction("onClose", noop3),
      defaultedFunction("onCancel", noop3),
      defaulted("onTabChange", noop3)
    ]);
    var createDialog = function(spec) {
      return asRaw("dialog", dialogSchema, spec);
    };
    var urlDialogButtonSchema = objOf(__spreadArray([requiredStringEnum("type", [
      "cancel",
      "custom"
    ])], dialogButtonFields, true));
    var urlDialogSchema = objOf([
      requiredString("title"),
      requiredString("url"),
      optionNumber("height"),
      optionNumber("width"),
      optionArrayOf("buttons", urlDialogButtonSchema),
      defaultedFunction("onAction", noop3),
      defaultedFunction("onCancel", noop3),
      defaultedFunction("onClose", noop3),
      defaultedFunction("onMessage", noop3)
    ]);
    var createUrlDialog = function(spec) {
      return asRaw("dialog", urlDialogSchema, spec);
    };
    var getAllObjects = function(obj) {
      if (isObject2(obj)) {
        return [obj].concat(bind$3(values(obj), getAllObjects));
      } else if (isArray2(obj)) {
        return bind$3(obj, getAllObjects);
      } else {
        return [];
      }
    };
    var isNamedItem = function(obj) {
      return isString(obj.type) && isString(obj.name);
    };
    var dataProcessors = {
      checkbox: checkboxDataProcessor,
      colorinput: colorInputDataProcessor,
      colorpicker: colorPickerDataProcessor,
      dropzone: dropZoneDataProcessor,
      input: inputDataProcessor,
      iframe: iframeDataProcessor,
      sizeinput: sizeInputDataProcessor,
      selectbox: selectBoxDataProcessor,
      listbox: listBoxDataProcessor,
      size: sizeInputDataProcessor,
      textarea: textAreaDataProcessor,
      urlinput: urlInputDataProcessor,
      customeditor: customEditorDataProcessor,
      collection: collectionDataProcessor,
      togglemenuitem: dialogToggleMenuItemDataProcessor
    };
    var getDataProcessor = function(item2) {
      return Optional.from(dataProcessors[item2.type]);
    };
    var getNamedItems = function(structure) {
      return filter$2(getAllObjects(structure), isNamedItem);
    };
    var createDataValidator = function(structure) {
      var namedItems = getNamedItems(structure);
      var fields = bind$3(namedItems, function(item2) {
        return getDataProcessor(item2).fold(function() {
          return [];
        }, function(schema2) {
          return [requiredOf(item2.name, schema2)];
        });
      });
      return objOf(fields);
    };
    var extract = function(structure) {
      var internalDialog = getOrDie(createDialog(structure));
      var dataValidator = createDataValidator(structure);
      var initialData = structure.initialData;
      return {
        internalDialog,
        dataValidator,
        initialData
      };
    };
    var DialogManager = {
      open: function(factory2, structure) {
        var extraction = extract(structure);
        return factory2(extraction.internalDialog, extraction.initialData, extraction.dataValidator);
      },
      openUrl: function(factory2, structure) {
        var internalDialog = getOrDie(createUrlDialog(structure));
        return factory2(internalDialog);
      },
      redial: function(structure) {
        return extract(structure);
      }
    };
    var toValidValues = function(values2) {
      var errors = [];
      var result = {};
      each2(values2, function(value2, name2) {
        value2.fold(function() {
          errors.push(name2);
        }, function(v2) {
          result[name2] = v2;
        });
      });
      return errors.length > 0 ? Result.error(errors) : Result.value(result);
    };
    var renderBodyPanel = function(spec, backstage) {
      var memForm = record(Form.sketch(function(parts2) {
        return {
          dom: {
            tag: "div",
            classes: ["tox-form"].concat(spec.classes)
          },
          components: map$2(spec.items, function(item2) {
            return interpretInForm(parts2, item2, backstage);
          })
        };
      }));
      return {
        dom: {
          tag: "div",
          classes: ["tox-dialog__body"]
        },
        components: [{
          dom: {
            tag: "div",
            classes: ["tox-dialog__body-content"]
          },
          components: [memForm.asSpec()]
        }],
        behaviours: derive$1([
          Keying.config({
            mode: "acyclic",
            useTabstopAt: not(isPseudoStop)
          }),
          ComposingConfigs.memento(memForm),
          RepresentingConfigs.memento(memForm, {
            postprocess: function(formValue) {
              return toValidValues(formValue).fold(function(err) {
                console.error(err);
                return {};
              }, identity$1);
            }
          })
        ])
      };
    };
    var factory$3 = function(detail, _spec) {
      return {
        uid: detail.uid,
        dom: detail.dom,
        components: detail.components,
        events: events$a(detail.action),
        behaviours: augment(detail.tabButtonBehaviours, [
          Focusing.config({}),
          Keying.config({
            mode: "execution",
            useSpace: true,
            useEnter: true
          }),
          Representing.config({
            store: {
              mode: "memory",
              initialValue: detail.value
            }
          })
        ]),
        domModification: detail.domModification
      };
    };
    var TabButton = single({
      name: "TabButton",
      configFields: [
        defaulted("uid", void 0),
        required$1("value"),
        field$1("dom", "dom", mergeWithThunk(function() {
          return {
            attributes: {
              "role": "tab",
              "id": generate$6("aria"),
              "aria-selected": "false"
            }
          };
        }), anyValue()),
        option("action"),
        defaulted("domModification", {}),
        field("tabButtonBehaviours", [
          Focusing,
          Keying,
          Representing
        ]),
        required$1("view")
      ],
      factory: factory$3
    });
    var schema$1 = constant$1([
      required$1("tabs"),
      required$1("dom"),
      defaulted("clickToDismiss", false),
      field("tabbarBehaviours", [
        Highlighting,
        Keying
      ]),
      markers$1([
        "tabClass",
        "selectedClass"
      ])
    ]);
    var tabsPart = group({
      factory: TabButton,
      name: "tabs",
      unit: "tab",
      overrides: function(barDetail) {
        var dismissTab$1 = function(tabbar, button2) {
          Highlighting.dehighlight(tabbar, button2);
          emitWith(tabbar, dismissTab(), {
            tabbar,
            button: button2
          });
        };
        var changeTab$1 = function(tabbar, button2) {
          Highlighting.highlight(tabbar, button2);
          emitWith(tabbar, changeTab(), {
            tabbar,
            button: button2
          });
        };
        return {
          action: function(button2) {
            var tabbar = button2.getSystem().getByUid(barDetail.uid).getOrDie();
            var activeButton = Highlighting.isHighlighted(tabbar, button2);
            var response = function() {
              if (activeButton && barDetail.clickToDismiss) {
                return dismissTab$1;
              } else if (!activeButton) {
                return changeTab$1;
              } else {
                return noop3;
              }
            }();
            response(tabbar, button2);
          },
          domModification: { classes: [barDetail.markers.tabClass] }
        };
      }
    });
    var parts$1 = constant$1([tabsPart]);
    var factory$2 = function(detail, components2, _spec, _externals) {
      return {
        "uid": detail.uid,
        "dom": detail.dom,
        components: components2,
        "debug.sketcher": "Tabbar",
        "domModification": { attributes: { role: "tablist" } },
        "behaviours": augment(detail.tabbarBehaviours, [
          Highlighting.config({
            highlightClass: detail.markers.selectedClass,
            itemClass: detail.markers.tabClass,
            onHighlight: function(tabbar, tab) {
              set$8(tab.element, "aria-selected", "true");
            },
            onDehighlight: function(tabbar, tab) {
              set$8(tab.element, "aria-selected", "false");
            }
          }),
          Keying.config({
            mode: "flow",
            getInitial: function(tabbar) {
              return Highlighting.getHighlighted(tabbar).map(function(tab) {
                return tab.element;
              });
            },
            selector: "." + detail.markers.tabClass,
            executeOnMove: true
          })
        ])
      };
    };
    var Tabbar = composite({
      name: "Tabbar",
      configFields: schema$1(),
      partFields: parts$1(),
      factory: factory$2
    });
    var factory$1 = function(detail, _spec) {
      return {
        uid: detail.uid,
        dom: detail.dom,
        behaviours: augment(detail.tabviewBehaviours, [Replacing.config({})]),
        domModification: { attributes: { role: "tabpanel" } }
      };
    };
    var Tabview = single({
      name: "Tabview",
      configFields: [field("tabviewBehaviours", [Replacing])],
      factory: factory$1
    });
    var schema = constant$1([
      defaulted("selectFirst", true),
      onHandler("onChangeTab"),
      onHandler("onDismissTab"),
      defaulted("tabs", []),
      field("tabSectionBehaviours", [])
    ]);
    var barPart = required({
      factory: Tabbar,
      schema: [
        required$1("dom"),
        requiredObjOf("markers", [
          required$1("tabClass"),
          required$1("selectedClass")
        ])
      ],
      name: "tabbar",
      defaults: function(detail) {
        return { tabs: detail.tabs };
      }
    });
    var viewPart = required({
      factory: Tabview,
      name: "tabview"
    });
    var parts = constant$1([
      barPart,
      viewPart
    ]);
    var factory = function(detail, components2, _spec, _externals) {
      var changeTab$1 = function(button2) {
        var tabValue = Representing.getValue(button2);
        getPart(button2, detail, "tabview").each(function(tabview) {
          var tabWithValue = find$5(detail.tabs, function(t3) {
            return t3.value === tabValue;
          });
          tabWithValue.each(function(tabData) {
            var panel = tabData.view();
            getOpt(button2.element, "id").each(function(id2) {
              set$8(tabview.element, "aria-labelledby", id2);
            });
            Replacing.set(tabview, panel);
            detail.onChangeTab(tabview, button2, panel);
          });
        });
      };
      var changeTabBy = function(section, byPred) {
        getPart(section, detail, "tabbar").each(function(tabbar) {
          byPred(tabbar).each(emitExecute);
        });
      };
      return {
        uid: detail.uid,
        dom: detail.dom,
        components: components2,
        behaviours: get$2(detail.tabSectionBehaviours),
        events: derive$2(flatten([
          detail.selectFirst ? [runOnAttached(function(section, _simulatedEvent) {
            changeTabBy(section, Highlighting.getFirst);
          })] : [],
          [
            run$1(changeTab(), function(section, simulatedEvent) {
              var button2 = simulatedEvent.event.button;
              changeTab$1(button2);
            }),
            run$1(dismissTab(), function(section, simulatedEvent) {
              var button2 = simulatedEvent.event.button;
              detail.onDismissTab(section, button2);
            })
          ]
        ])),
        apis: {
          getViewItems: function(section) {
            return getPart(section, detail, "tabview").map(function(tabview) {
              return Replacing.contents(tabview);
            }).getOr([]);
          },
          showTab: function(section, tabKey) {
            var getTabIfNotActive = function(tabbar) {
              var candidates = Highlighting.getCandidates(tabbar);
              var optTab = find$5(candidates, function(c2) {
                return Representing.getValue(c2) === tabKey;
              });
              return optTab.filter(function(tab) {
                return !Highlighting.isHighlighted(tabbar, tab);
              });
            };
            changeTabBy(section, getTabIfNotActive);
          }
        }
      };
    };
    var TabSection = composite({
      name: "TabSection",
      configFields: schema(),
      partFields: parts(),
      factory,
      apis: {
        getViewItems: function(apis, component) {
          return apis.getViewItems(component);
        },
        showTab: function(apis, component, tabKey) {
          apis.showTab(component, tabKey);
        }
      }
    });
    var measureHeights = function(allTabs, tabview, tabviewComp) {
      return map$2(allTabs, function(_tab, i2) {
        Replacing.set(tabviewComp, allTabs[i2].view());
        var rect2 = tabview.dom.getBoundingClientRect();
        Replacing.set(tabviewComp, []);
        return rect2.height;
      });
    };
    var getMaxHeight = function(heights) {
      return head(sort(heights, function(a2, b3) {
        if (a2 > b3) {
          return -1;
        } else if (a2 < b3) {
          return 1;
        } else {
          return 0;
        }
      }));
    };
    var getMaxTabviewHeight = function(dialog, tabview, tablist) {
      var documentElement$1 = documentElement(dialog).dom;
      var rootElm = ancestor(dialog, ".tox-dialog-wrap").getOr(dialog);
      var isFixed = get$c(rootElm, "position") === "fixed";
      var maxHeight;
      if (isFixed) {
        maxHeight = Math.max(documentElement$1.clientHeight, window.innerHeight);
      } else {
        maxHeight = Math.max(documentElement$1.offsetHeight, documentElement$1.scrollHeight);
      }
      var tabviewHeight = get$b(tabview);
      var isTabListBeside = tabview.dom.offsetLeft >= tablist.dom.offsetLeft + get$a(tablist);
      var currentTabHeight = isTabListBeside ? Math.max(get$b(tablist), tabviewHeight) : tabviewHeight;
      var dialogTopMargin = parseInt(get$c(dialog, "margin-top"), 10) || 0;
      var dialogBottomMargin = parseInt(get$c(dialog, "margin-bottom"), 10) || 0;
      var dialogHeight = get$b(dialog) + dialogTopMargin + dialogBottomMargin;
      var chromeHeight = dialogHeight - currentTabHeight;
      return maxHeight - chromeHeight;
    };
    var showTab = function(allTabs, comp) {
      head(allTabs).each(function(tab) {
        return TabSection.showTab(comp, tab.value);
      });
    };
    var setTabviewHeight = function(tabview, height2) {
      set$7(tabview, "height", height2 + "px");
      if (!detect$1().browser.isIE()) {
        set$7(tabview, "flex-basis", height2 + "px");
      } else {
        remove$6(tabview, "flex-basis");
      }
    };
    var updateTabviewHeight = function(dialogBody, tabview, maxTabHeight) {
      ancestor(dialogBody, '[role="dialog"]').each(function(dialog) {
        descendant(dialog, '[role="tablist"]').each(function(tablist) {
          maxTabHeight.get().map(function(height2) {
            set$7(tabview, "height", "0");
            set$7(tabview, "flex-basis", "0");
            return Math.min(height2, getMaxTabviewHeight(dialog, tabview, tablist));
          }).each(function(height2) {
            setTabviewHeight(tabview, height2);
          });
        });
      });
    };
    var getTabview = function(dialog) {
      return descendant(dialog, '[role="tabpanel"]');
    };
    var setMode = function(allTabs) {
      var smartTabHeight = function() {
        var maxTabHeight = value$1();
        var extraEvents = [
          runOnAttached(function(comp) {
            var dialog = comp.element;
            getTabview(dialog).each(function(tabview) {
              set$7(tabview, "visibility", "hidden");
              comp.getSystem().getByDom(tabview).toOptional().each(function(tabviewComp) {
                var heights = measureHeights(allTabs, tabview, tabviewComp);
                var maxTabHeightOpt = getMaxHeight(heights);
                maxTabHeightOpt.fold(maxTabHeight.clear, maxTabHeight.set);
              });
              updateTabviewHeight(dialog, tabview, maxTabHeight);
              remove$6(tabview, "visibility");
              showTab(allTabs, comp);
              global$f.requestAnimationFrame(function() {
                updateTabviewHeight(dialog, tabview, maxTabHeight);
              });
            });
          }),
          run$1(windowResize(), function(comp) {
            var dialog = comp.element;
            getTabview(dialog).each(function(tabview) {
              updateTabviewHeight(dialog, tabview, maxTabHeight);
            });
          }),
          run$1(formResizeEvent, function(comp, _se) {
            var dialog = comp.element;
            getTabview(dialog).each(function(tabview) {
              var oldFocus = active(getRootNode(tabview));
              set$7(tabview, "visibility", "hidden");
              var oldHeight = getRaw(tabview, "height").map(function(h3) {
                return parseInt(h3, 10);
              });
              remove$6(tabview, "height");
              remove$6(tabview, "flex-basis");
              var newHeight = tabview.dom.getBoundingClientRect().height;
              var hasGrown2 = oldHeight.forall(function(h3) {
                return newHeight > h3;
              });
              if (hasGrown2) {
                maxTabHeight.set(newHeight);
                updateTabviewHeight(dialog, tabview, maxTabHeight);
              } else {
                oldHeight.each(function(h3) {
                  setTabviewHeight(tabview, h3);
                });
              }
              remove$6(tabview, "visibility");
              oldFocus.each(focus$3);
            });
          })
        ];
        var selectFirst = false;
        return {
          extraEvents,
          selectFirst
        };
      }();
      var naiveTabHeight = function() {
        var extraEvents = [];
        var selectFirst = true;
        return {
          extraEvents,
          selectFirst
        };
      }();
      return {
        smartTabHeight,
        naiveTabHeight
      };
    };
    var SendDataToSectionChannel = "send-data-to-section";
    var SendDataToViewChannel = "send-data-to-view";
    var renderTabPanel = function(spec, backstage) {
      var storedValue = Cell({});
      var updateDataWithForm = function(form) {
        var formData = Representing.getValue(form);
        var validData = toValidValues(formData).getOr({});
        var currentData = storedValue.get();
        var newData = deepMerge(currentData, validData);
        storedValue.set(newData);
      };
      var setDataOnForm = function(form) {
        var tabData = storedValue.get();
        Representing.setValue(form, tabData);
      };
      var oldTab = Cell(null);
      var allTabs = map$2(spec.tabs, function(tab) {
        return {
          value: tab.name,
          dom: {
            tag: "div",
            classes: ["tox-dialog__body-nav-item"],
            innerHtml: backstage.shared.providers.translate(tab.title)
          },
          view: function() {
            return [Form.sketch(function(parts2) {
              return {
                dom: {
                  tag: "div",
                  classes: ["tox-form"]
                },
                components: map$2(tab.items, function(item2) {
                  return interpretInForm(parts2, item2, backstage);
                }),
                formBehaviours: derive$1([
                  Keying.config({
                    mode: "acyclic",
                    useTabstopAt: not(isPseudoStop)
                  }),
                  config("TabView.form.events", [
                    runOnAttached(setDataOnForm),
                    runOnDetached(updateDataWithForm)
                  ]),
                  Receiving.config({
                    channels: wrapAll([
                      {
                        key: SendDataToSectionChannel,
                        value: { onReceive: updateDataWithForm }
                      },
                      {
                        key: SendDataToViewChannel,
                        value: { onReceive: setDataOnForm }
                      }
                    ])
                  })
                ])
              };
            })];
          }
        };
      });
      var tabMode = setMode(allTabs).smartTabHeight;
      return TabSection.sketch({
        dom: {
          tag: "div",
          classes: ["tox-dialog__body"]
        },
        onChangeTab: function(section, button2, _viewItems) {
          var name2 = Representing.getValue(button2);
          emitWith(section, formTabChangeEvent, {
            name: name2,
            oldName: oldTab.get()
          });
          oldTab.set(name2);
        },
        tabs: allTabs,
        components: [
          TabSection.parts.tabbar({
            dom: {
              tag: "div",
              classes: ["tox-dialog__body-nav"]
            },
            components: [Tabbar.parts.tabs({})],
            markers: {
              tabClass: "tox-tab",
              selectedClass: "tox-dialog__body-nav-item--active"
            },
            tabbarBehaviours: derive$1([Tabstopping.config({})])
          }),
          TabSection.parts.tabview({
            dom: {
              tag: "div",
              classes: ["tox-dialog__body-content"]
            }
          })
        ],
        selectFirst: tabMode.selectFirst,
        tabSectionBehaviours: derive$1([
          config("tabpanel", tabMode.extraEvents),
          Keying.config({ mode: "acyclic" }),
          Composing.config({
            find: function(comp) {
              return head(TabSection.getViewItems(comp));
            }
          }),
          Representing.config({
            store: {
              mode: "manual",
              getValue: function(tsection) {
                tsection.getSystem().broadcastOn([SendDataToSectionChannel], {});
                return storedValue.get();
              },
              setValue: function(tsection, value2) {
                storedValue.set(value2);
                tsection.getSystem().broadcastOn([SendDataToViewChannel], {});
              }
            }
          })
        ])
      });
    };
    var dialogChannel = generate$6("update-dialog");
    var titleChannel = generate$6("update-title");
    var bodyChannel = generate$6("update-body");
    var footerChannel = generate$6("update-footer");
    var bodySendMessageChannel = generate$6("body-send-message");
    var renderBody = function(spec, id2, backstage, ariaAttrs) {
      var renderComponents2 = function(incoming) {
        switch (incoming.body.type) {
          case "tabpanel": {
            return [renderTabPanel(incoming.body, backstage)];
          }
          default: {
            return [renderBodyPanel(incoming.body, backstage)];
          }
        }
      };
      var updateState = function(_comp, incoming) {
        return Optional.some({
          isTabPanel: function() {
            return incoming.body.type === "tabpanel";
          }
        });
      };
      var ariaAttributes = { "aria-live": "polite" };
      return {
        dom: {
          tag: "div",
          classes: ["tox-dialog__content-js"],
          attributes: __assign(__assign({}, id2.map(function(x2) {
            return { id: x2 };
          }).getOr({})), ariaAttrs ? ariaAttributes : {})
        },
        components: [],
        behaviours: derive$1([
          ComposingConfigs.childAt(0),
          Reflecting.config({
            channel: bodyChannel,
            updateState,
            renderComponents: renderComponents2,
            initialData: spec
          })
        ])
      };
    };
    var renderInlineBody = function(spec, contentId, backstage, ariaAttrs) {
      return renderBody(spec, Optional.some(contentId), backstage, ariaAttrs);
    };
    var renderModalBody = function(spec, backstage) {
      var bodySpec = renderBody(spec, Optional.none(), backstage, false);
      return ModalDialog.parts.body(bodySpec);
    };
    var renderIframeBody = function(spec) {
      var bodySpec = {
        dom: {
          tag: "div",
          classes: ["tox-dialog__content-js"]
        },
        components: [{
          dom: {
            tag: "div",
            classes: ["tox-dialog__body-iframe"]
          },
          components: [craft({
            dom: {
              tag: "iframe",
              attributes: { src: spec.url }
            },
            behaviours: derive$1([
              Tabstopping.config({}),
              Focusing.config({})
            ])
          })]
        }],
        behaviours: derive$1([Keying.config({
          mode: "acyclic",
          useTabstopAt: not(isPseudoStop)
        })])
      };
      return ModalDialog.parts.body(bodySpec);
    };
    var isTouch = global$9.deviceType.isTouch();
    var hiddenHeader = function(title, close2) {
      return {
        dom: {
          tag: "div",
          styles: { display: "none" },
          classes: ["tox-dialog__header"]
        },
        components: [
          title,
          close2
        ]
      };
    };
    var pClose = function(onClose, providersBackstage) {
      return ModalDialog.parts.close(Button2.sketch({
        dom: {
          tag: "button",
          classes: [
            "tox-button",
            "tox-button--icon",
            "tox-button--naked"
          ],
          attributes: {
            "type": "button",
            "aria-label": providersBackstage.translate("Close")
          }
        },
        action: onClose,
        buttonBehaviours: derive$1([Tabstopping.config({})])
      }));
    };
    var pUntitled = function() {
      return ModalDialog.parts.title({
        dom: {
          tag: "div",
          classes: ["tox-dialog__title"],
          innerHtml: "",
          styles: { display: "none" }
        }
      });
    };
    var pBodyMessage = function(message, providersBackstage) {
      return ModalDialog.parts.body({
        dom: {
          tag: "div",
          classes: ["tox-dialog__body"]
        },
        components: [{
          dom: {
            tag: "div",
            classes: ["tox-dialog__body-content"]
          },
          components: [{ dom: fromHtml("<p>" + providersBackstage.translate(message) + "</p>") }]
        }]
      });
    };
    var pFooter = function(buttons) {
      return ModalDialog.parts.footer({
        dom: {
          tag: "div",
          classes: ["tox-dialog__footer"]
        },
        components: buttons
      });
    };
    var pFooterGroup = function(startButtons, endButtons) {
      return [
        Container.sketch({
          dom: {
            tag: "div",
            classes: ["tox-dialog__footer-start"]
          },
          components: startButtons
        }),
        Container.sketch({
          dom: {
            tag: "div",
            classes: ["tox-dialog__footer-end"]
          },
          components: endButtons
        })
      ];
    };
    var renderDialog$1 = function(spec) {
      var _a2;
      var dialogClass = "tox-dialog";
      var blockerClass = dialogClass + "-wrap";
      var blockerBackdropClass = blockerClass + "__backdrop";
      var scrollLockClass = dialogClass + "__disable-scroll";
      return ModalDialog.sketch({
        lazySink: spec.lazySink,
        onEscape: function(comp) {
          spec.onEscape(comp);
          return Optional.some(true);
        },
        useTabstopAt: function(elem) {
          return !isPseudoStop(elem);
        },
        dom: {
          tag: "div",
          classes: [dialogClass].concat(spec.extraClasses),
          styles: __assign({ position: "relative" }, spec.extraStyles)
        },
        components: __spreadArray([
          spec.header,
          spec.body
        ], spec.footer.toArray(), true),
        parts: {
          blocker: {
            dom: fromHtml('<div class="' + blockerClass + '"></div>'),
            components: [{
              dom: {
                tag: "div",
                classes: isTouch ? [
                  blockerBackdropClass,
                  blockerBackdropClass + "--opaque"
                ] : [blockerBackdropClass]
              }
            }]
          }
        },
        dragBlockClass: blockerClass,
        modalBehaviours: derive$1(__spreadArray([
          Focusing.config({}),
          config("dialog-events", spec.dialogEvents.concat([runOnSource(focusin(), function(comp, _se) {
            Keying.focusIn(comp);
          })])),
          config("scroll-lock", [
            runOnAttached(function() {
              add$2(body(), scrollLockClass);
            }),
            runOnDetached(function() {
              remove$2(body(), scrollLockClass);
            })
          ])
        ], spec.extraBehaviours, true)),
        eventOrder: __assign((_a2 = {}, _a2[execute$5()] = ["dialog-events"], _a2[attachedToDom()] = [
          "scroll-lock",
          "dialog-events",
          "alloy.base.behaviour"
        ], _a2[detachedFromDom()] = [
          "alloy.base.behaviour",
          "dialog-events",
          "scroll-lock"
        ], _a2), spec.eventOrder)
      });
    };
    var renderClose = function(providersBackstage) {
      return Button2.sketch({
        dom: {
          tag: "button",
          classes: [
            "tox-button",
            "tox-button--icon",
            "tox-button--naked"
          ],
          attributes: {
            "type": "button",
            "aria-label": providersBackstage.translate("Close"),
            "title": providersBackstage.translate("Close")
          }
        },
        components: [render$3("close", {
          tag: "div",
          classes: ["tox-icon"]
        }, providersBackstage.icons)],
        action: function(comp) {
          emit(comp, formCancelEvent);
        }
      });
    };
    var renderTitle = function(spec, id2, providersBackstage) {
      var renderComponents2 = function(data) {
        return [text(providersBackstage.translate(data.title))];
      };
      return {
        dom: {
          tag: "div",
          classes: ["tox-dialog__title"],
          attributes: __assign({}, id2.map(function(x2) {
            return { id: x2 };
          }).getOr({}))
        },
        components: renderComponents2(spec),
        behaviours: derive$1([Reflecting.config({
          channel: titleChannel,
          renderComponents: renderComponents2
        })])
      };
    };
    var renderDragHandle = function() {
      return { dom: fromHtml('<div class="tox-dialog__draghandle"></div>') };
    };
    var renderInlineHeader = function(spec, titleId, providersBackstage) {
      return Container.sketch({
        dom: fromHtml('<div class="tox-dialog__header"></div>'),
        components: [
          renderTitle(spec, Optional.some(titleId), providersBackstage),
          renderDragHandle(),
          renderClose(providersBackstage)
        ],
        containerBehaviours: derive$1([Dragging.config({
          mode: "mouse",
          blockerClass: "blocker",
          getTarget: function(handle2) {
            return closest$1(handle2, '[role="dialog"]').getOrDie();
          },
          snaps: {
            getSnapPoints: function() {
              return [];
            },
            leftAttr: "data-drag-left",
            topAttr: "data-drag-top"
          }
        })])
      });
    };
    var renderModalHeader = function(spec, providersBackstage) {
      var pTitle = ModalDialog.parts.title(renderTitle(spec, Optional.none(), providersBackstage));
      var pHandle = ModalDialog.parts.draghandle(renderDragHandle());
      var pClose2 = ModalDialog.parts.close(renderClose(providersBackstage));
      var components2 = [pTitle].concat(spec.draggable ? [pHandle] : []).concat([pClose2]);
      return Container.sketch({
        dom: fromHtml('<div class="tox-dialog__header"></div>'),
        components: components2
      });
    };
    var getHeader = function(title, backstage) {
      return renderModalHeader({
        title: backstage.shared.providers.translate(title),
        draggable: backstage.dialog.isDraggableModal()
      }, backstage.shared.providers);
    };
    var getBusySpec = function(message, bs, providers) {
      return {
        dom: {
          tag: "div",
          classes: ["tox-dialog__busy-spinner"],
          attributes: { "aria-label": providers.translate(message) },
          styles: {
            left: "0px",
            right: "0px",
            bottom: "0px",
            top: "0px",
            position: "absolute"
          }
        },
        behaviours: bs,
        components: [{ dom: fromHtml('<div class="tox-spinner"><div></div><div></div><div></div></div>') }]
      };
    };
    var getEventExtras = function(lazyDialog, providers, extra) {
      return {
        onClose: function() {
          return extra.closeWindow();
        },
        onBlock: function(blockEvent) {
          ModalDialog.setBusy(lazyDialog(), function(_comp, bs) {
            return getBusySpec(blockEvent.message, bs, providers);
          });
        },
        onUnblock: function() {
          ModalDialog.setIdle(lazyDialog());
        }
      };
    };
    var renderModalDialog = function(spec, initialData, dialogEvents, backstage) {
      var _a2;
      var updateState = function(_comp, incoming) {
        return Optional.some(incoming);
      };
      return build$1(renderDialog$1(__assign(__assign({}, spec), {
        lazySink: backstage.shared.getSink,
        extraBehaviours: __spreadArray([
          Reflecting.config({
            channel: dialogChannel,
            updateState,
            initialData
          }),
          RepresentingConfigs.memory({})
        ], spec.extraBehaviours, true),
        onEscape: function(comp) {
          emit(comp, formCancelEvent);
        },
        dialogEvents,
        eventOrder: (_a2 = {}, _a2[receive()] = [
          Reflecting.name(),
          Receiving.name()
        ], _a2[attachedToDom()] = [
          "scroll-lock",
          Reflecting.name(),
          "messages",
          "dialog-events",
          "alloy.base.behaviour"
        ], _a2[detachedFromDom()] = [
          "alloy.base.behaviour",
          "dialog-events",
          "messages",
          Reflecting.name(),
          "scroll-lock"
        ], _a2)
      })));
    };
    var mapMenuButtons = function(buttons) {
      var mapItems = function(button2) {
        var items = map$2(button2.items, function(item2) {
          var cell = Cell(false);
          return __assign(__assign({}, item2), { storage: cell });
        });
        return __assign(__assign({}, button2), { items });
      };
      return map$2(buttons, function(button2) {
        if (button2.type === "menu") {
          return mapItems(button2);
        }
        return button2;
      });
    };
    var extractCellsToObject = function(buttons) {
      return foldl(buttons, function(acc, button2) {
        if (button2.type === "menu") {
          var menuButton = button2;
          return foldl(menuButton.items, function(innerAcc, item2) {
            innerAcc[item2.name] = item2.storage;
            return innerAcc;
          }, acc);
        }
        return acc;
      }, {});
    };
    var initCommonEvents = function(fireApiEvent, extras) {
      return [
        runWithTarget(focusin(), onFocus),
        fireApiEvent(formCloseEvent, function(_api, spec) {
          extras.onClose();
          spec.onClose();
        }),
        fireApiEvent(formCancelEvent, function(api2, spec, _event, self2) {
          spec.onCancel(api2);
          emit(self2, formCloseEvent);
        }),
        run$1(formUnblockEvent, function(_c, _se) {
          return extras.onUnblock();
        }),
        run$1(formBlockEvent, function(_c, se2) {
          return extras.onBlock(se2.event);
        })
      ];
    };
    var initUrlDialog = function(getInstanceApi, extras) {
      var fireApiEvent = function(eventName, f2) {
        return run$1(eventName, function(c2, se2) {
          withSpec(c2, function(spec, _c) {
            f2(getInstanceApi(), spec, se2.event, c2);
          });
        });
      };
      var withSpec = function(c2, f2) {
        Reflecting.getState(c2).get().each(function(currentDialog) {
          f2(currentDialog, c2);
        });
      };
      return __spreadArray(__spreadArray([], initCommonEvents(fireApiEvent, extras), true), [fireApiEvent(formActionEvent, function(api2, spec, event) {
        spec.onAction(api2, { name: event.name });
      })], false);
    };
    var initDialog = function(getInstanceApi, extras, getSink2) {
      var fireApiEvent = function(eventName, f2) {
        return run$1(eventName, function(c2, se2) {
          withSpec(c2, function(spec, _c) {
            f2(getInstanceApi(), spec, se2.event, c2);
          });
        });
      };
      var withSpec = function(c2, f2) {
        Reflecting.getState(c2).get().each(function(currentDialogInit) {
          f2(currentDialogInit.internalDialog, c2);
        });
      };
      return __spreadArray(__spreadArray([], initCommonEvents(fireApiEvent, extras), true), [
        fireApiEvent(formSubmitEvent, function(api2, spec) {
          return spec.onSubmit(api2);
        }),
        fireApiEvent(formChangeEvent, function(api2, spec, event) {
          spec.onChange(api2, { name: event.name });
        }),
        fireApiEvent(formActionEvent, function(api2, spec, event, component) {
          var focusIn2 = function() {
            return Keying.focusIn(component);
          };
          var isDisabled3 = function(focused) {
            return has$1(focused, "disabled") || getOpt(focused, "aria-disabled").exists(function(val) {
              return val === "true";
            });
          };
          var rootNode = getRootNode(component.element);
          var current = active(rootNode);
          spec.onAction(api2, {
            name: event.name,
            value: event.value
          });
          active(rootNode).fold(focusIn2, function(focused) {
            if (isDisabled3(focused)) {
              focusIn2();
            } else if (current.exists(function(cur) {
              return contains2(focused, cur) && isDisabled3(cur);
            })) {
              focusIn2();
            } else {
              getSink2().toOptional().filter(function(sink) {
                return !contains2(sink.element, focused);
              }).each(focusIn2);
            }
          });
        }),
        fireApiEvent(formTabChangeEvent, function(api2, spec, event) {
          spec.onTabChange(api2, {
            newTabName: event.name,
            oldTabName: event.oldName
          });
        }),
        runOnDetached(function(component) {
          var api2 = getInstanceApi();
          Representing.setValue(component, api2.getData());
        })
      ], false);
    };
    var SilverDialogEvents = {
      initUrlDialog,
      initDialog
    };
    var makeButton = function(button2, backstage) {
      return renderFooterButton(button2, button2.type, backstage);
    };
    var lookup = function(compInSystem, footerButtons, buttonName) {
      return find$5(footerButtons, function(button2) {
        return button2.name === buttonName;
      }).bind(function(memButton) {
        return memButton.memento.getOpt(compInSystem);
      });
    };
    var renderComponents = function(_data, state) {
      var footerButtons = state.map(function(s2) {
        return s2.footerButtons;
      }).getOr([]);
      var buttonGroups = partition$3(footerButtons, function(button2) {
        return button2.align === "start";
      });
      var makeGroup = function(edge2, buttons) {
        return Container.sketch({
          dom: {
            tag: "div",
            classes: ["tox-dialog__footer-" + edge2]
          },
          components: map$2(buttons, function(button2) {
            return button2.memento.asSpec();
          })
        });
      };
      var startButtons = makeGroup("start", buttonGroups.pass);
      var endButtons = makeGroup("end", buttonGroups.fail);
      return [
        startButtons,
        endButtons
      ];
    };
    var renderFooter = function(initSpec, backstage) {
      var updateState = function(_comp, data) {
        var footerButtons = map$2(data.buttons, function(button2) {
          var memButton = record(makeButton(button2, backstage));
          return {
            name: button2.name,
            align: button2.align,
            memento: memButton
          };
        });
        var lookupByName = function(compInSystem, buttonName) {
          return lookup(compInSystem, footerButtons, buttonName);
        };
        return Optional.some({
          lookupByName,
          footerButtons
        });
      };
      return {
        dom: fromHtml('<div class="tox-dialog__footer"></div>'),
        components: [],
        behaviours: derive$1([Reflecting.config({
          channel: footerChannel,
          initialData: initSpec,
          updateState,
          renderComponents
        })])
      };
    };
    var renderInlineFooter = function(initSpec, backstage) {
      return renderFooter(initSpec, backstage);
    };
    var renderModalFooter = function(initSpec, backstage) {
      return ModalDialog.parts.footer(renderFooter(initSpec, backstage));
    };
    var getCompByName = function(access, name2) {
      var root = access.getRoot();
      if (root.getSystem().isConnected()) {
        var form_1 = Composing.getCurrent(access.getFormWrapper()).getOr(access.getFormWrapper());
        return Form.getField(form_1, name2).fold(function() {
          var footer = access.getFooter();
          var footerState = Reflecting.getState(footer);
          return footerState.get().bind(function(f2) {
            return f2.lookupByName(form_1, name2);
          });
        }, function(comp) {
          return Optional.some(comp);
        });
      } else {
        return Optional.none();
      }
    };
    var validateData$1 = function(access, data) {
      var root = access.getRoot();
      return Reflecting.getState(root).get().map(function(dialogState) {
        return getOrDie(asRaw("data", dialogState.dataValidator, data));
      }).getOr(data);
    };
    var getDialogApi = function(access, doRedial, menuItemStates) {
      var withRoot = function(f2) {
        var root = access.getRoot();
        if (root.getSystem().isConnected()) {
          f2(root);
        }
      };
      var getData2 = function() {
        var root = access.getRoot();
        var valueComp = root.getSystem().isConnected() ? access.getFormWrapper() : root;
        var representedValues = Representing.getValue(valueComp);
        var menuItemCurrentState = map$12(menuItemStates, function(cell) {
          return cell.get();
        });
        return __assign(__assign({}, representedValues), menuItemCurrentState);
      };
      var setData = function(newData) {
        withRoot(function(_2) {
          var prevData = instanceApi.getData();
          var mergedData = __assign(__assign({}, prevData), newData);
          var newInternalData = validateData$1(access, mergedData);
          var form = access.getFormWrapper();
          Representing.setValue(form, newInternalData);
          each2(menuItemStates, function(v2, k2) {
            if (has$2(mergedData, k2)) {
              v2.set(mergedData[k2]);
            }
          });
        });
      };
      var disable3 = function(name2) {
        getCompByName(access, name2).each(Disabling.disable);
      };
      var enable3 = function(name2) {
        getCompByName(access, name2).each(Disabling.enable);
      };
      var focus2 = function(name2) {
        getCompByName(access, name2).each(Focusing.focus);
      };
      var block2 = function(message) {
        if (!isString(message)) {
          throw new Error("The dialogInstanceAPI.block function should be passed a blocking message of type string as an argument");
        }
        withRoot(function(root) {
          emitWith(root, formBlockEvent, { message });
        });
      };
      var unblock2 = function() {
        withRoot(function(root) {
          emit(root, formUnblockEvent);
        });
      };
      var showTab2 = function(name2) {
        withRoot(function(_2) {
          var body2 = access.getBody();
          var bodyState = Reflecting.getState(body2);
          if (bodyState.get().exists(function(b3) {
            return b3.isTabPanel();
          })) {
            Composing.getCurrent(body2).each(function(tabSection) {
              TabSection.showTab(tabSection, name2);
            });
          }
        });
      };
      var redial = function(d2) {
        withRoot(function(root) {
          var dialogInit = doRedial(d2);
          root.getSystem().broadcastOn([dialogChannel], dialogInit);
          root.getSystem().broadcastOn([titleChannel], dialogInit.internalDialog);
          root.getSystem().broadcastOn([bodyChannel], dialogInit.internalDialog);
          root.getSystem().broadcastOn([footerChannel], dialogInit.internalDialog);
          instanceApi.setData(dialogInit.initialData);
        });
      };
      var close2 = function() {
        withRoot(function(root) {
          emit(root, formCloseEvent);
        });
      };
      var instanceApi = {
        getData: getData2,
        setData,
        disable: disable3,
        enable: enable3,
        focus: focus2,
        block: block2,
        unblock: unblock2,
        showTab: showTab2,
        redial,
        close: close2
      };
      return instanceApi;
    };
    var getDialogSizeClasses = function(size) {
      switch (size) {
        case "large":
          return ["tox-dialog--width-lg"];
        case "medium":
          return ["tox-dialog--width-md"];
        default:
          return [];
      }
    };
    var renderDialog = function(dialogInit, extra, backstage) {
      var header = getHeader(dialogInit.internalDialog.title, backstage);
      var body2 = renderModalBody({ body: dialogInit.internalDialog.body }, backstage);
      var storagedMenuButtons = mapMenuButtons(dialogInit.internalDialog.buttons);
      var objOfCells = extractCellsToObject(storagedMenuButtons);
      var footer = renderModalFooter({ buttons: storagedMenuButtons }, backstage);
      var dialogEvents = SilverDialogEvents.initDialog(function() {
        return instanceApi;
      }, getEventExtras(function() {
        return dialog;
      }, backstage.shared.providers, extra), backstage.shared.getSink);
      var dialogSize = getDialogSizeClasses(dialogInit.internalDialog.size);
      var spec = {
        header,
        body: body2,
        footer: Optional.some(footer),
        extraClasses: dialogSize,
        extraBehaviours: [],
        extraStyles: {}
      };
      var dialog = renderModalDialog(spec, dialogInit, dialogEvents, backstage);
      var modalAccess = function() {
        var getForm = function() {
          var outerForm = ModalDialog.getBody(dialog);
          return Composing.getCurrent(outerForm).getOr(outerForm);
        };
        return {
          getRoot: constant$1(dialog),
          getBody: function() {
            return ModalDialog.getBody(dialog);
          },
          getFooter: function() {
            return ModalDialog.getFooter(dialog);
          },
          getFormWrapper: getForm
        };
      }();
      var instanceApi = getDialogApi(modalAccess, extra.redial, objOfCells);
      return {
        dialog,
        instanceApi
      };
    };
    var renderInlineDialog = function(dialogInit, extra, backstage, ariaAttrs) {
      var _a2, _b;
      var dialogLabelId = generate$6("dialog-label");
      var dialogContentId = generate$6("dialog-content");
      var updateState = function(_comp, incoming) {
        return Optional.some(incoming);
      };
      var memHeader = record(renderInlineHeader({
        title: dialogInit.internalDialog.title,
        draggable: true
      }, dialogLabelId, backstage.shared.providers));
      var memBody = record(renderInlineBody({ body: dialogInit.internalDialog.body }, dialogContentId, backstage, ariaAttrs));
      var storagedMenuButtons = mapMenuButtons(dialogInit.internalDialog.buttons);
      var objOfCells = extractCellsToObject(storagedMenuButtons);
      var memFooter = record(renderInlineFooter({ buttons: storagedMenuButtons }, backstage));
      var dialogEvents = SilverDialogEvents.initDialog(function() {
        return instanceApi;
      }, {
        onBlock: function(event) {
          Blocking.block(dialog, function(_comp, bs) {
            return getBusySpec(event.message, bs, backstage.shared.providers);
          });
        },
        onUnblock: function() {
          Blocking.unblock(dialog);
        },
        onClose: function() {
          return extra.closeWindow();
        }
      }, backstage.shared.getSink);
      var dialog = build$1({
        dom: {
          tag: "div",
          classes: [
            "tox-dialog",
            "tox-dialog-inline"
          ],
          attributes: (_a2 = { role: "dialog" }, _a2["aria-labelledby"] = dialogLabelId, _a2["aria-describedby"] = dialogContentId, _a2)
        },
        eventOrder: (_b = {}, _b[receive()] = [
          Reflecting.name(),
          Receiving.name()
        ], _b[execute$5()] = ["execute-on-form"], _b[attachedToDom()] = [
          "reflecting",
          "execute-on-form"
        ], _b),
        behaviours: derive$1([
          Keying.config({
            mode: "cyclic",
            onEscape: function(c2) {
              emit(c2, formCloseEvent);
              return Optional.some(true);
            },
            useTabstopAt: function(elem) {
              return !isPseudoStop(elem) && (name$2(elem) !== "button" || get$d(elem, "disabled") !== "disabled");
            }
          }),
          Reflecting.config({
            channel: dialogChannel,
            updateState,
            initialData: dialogInit
          }),
          Focusing.config({}),
          config("execute-on-form", dialogEvents.concat([runOnSource(focusin(), function(comp, _se) {
            Keying.focusIn(comp);
          })])),
          Blocking.config({
            getRoot: function() {
              return Optional.some(dialog);
            }
          }),
          Replacing.config({}),
          RepresentingConfigs.memory({})
        ]),
        components: [
          memHeader.asSpec(),
          memBody.asSpec(),
          memFooter.asSpec()
        ]
      });
      var instanceApi = getDialogApi({
        getRoot: constant$1(dialog),
        getFooter: function() {
          return memFooter.get(dialog);
        },
        getBody: function() {
          return memBody.get(dialog);
        },
        getFormWrapper: function() {
          var body2 = memBody.get(dialog);
          return Composing.getCurrent(body2).getOr(body2);
        }
      }, extra.redial, objOfCells);
      return {
        dialog,
        instanceApi
      };
    };
    var global$1 = tinymce.util.Tools.resolve("tinymce.util.URI");
    var getUrlDialogApi = function(root) {
      var withRoot = function(f2) {
        if (root.getSystem().isConnected()) {
          f2(root);
        }
      };
      var block2 = function(message) {
        if (!isString(message)) {
          throw new Error("The urlDialogInstanceAPI.block function should be passed a blocking message of type string as an argument");
        }
        withRoot(function(root2) {
          emitWith(root2, formBlockEvent, { message });
        });
      };
      var unblock2 = function() {
        withRoot(function(root2) {
          emit(root2, formUnblockEvent);
        });
      };
      var close2 = function() {
        withRoot(function(root2) {
          emit(root2, formCloseEvent);
        });
      };
      var sendMessage = function(data) {
        withRoot(function(root2) {
          root2.getSystem().broadcastOn([bodySendMessageChannel], data);
        });
      };
      return {
        block: block2,
        unblock: unblock2,
        close: close2,
        sendMessage
      };
    };
    var SUPPORTED_MESSAGE_ACTIONS = [
      "insertContent",
      "setContent",
      "execCommand",
      "close",
      "block",
      "unblock"
    ];
    var isSupportedMessage = function(data) {
      return isObject2(data) && SUPPORTED_MESSAGE_ACTIONS.indexOf(data.mceAction) !== -1;
    };
    var isCustomMessage = function(data) {
      return !isSupportedMessage(data) && isObject2(data) && has$2(data, "mceAction");
    };
    var handleMessage = function(editor, api2, data) {
      switch (data.mceAction) {
        case "insertContent":
          editor.insertContent(data.content);
          break;
        case "setContent":
          editor.setContent(data.content);
          break;
        case "execCommand":
          var ui2 = isBoolean(data.ui) ? data.ui : false;
          editor.execCommand(data.cmd, ui2, data.value);
          break;
        case "close":
          api2.close();
          break;
        case "block":
          api2.block(data.message);
          break;
        case "unblock":
          api2.unblock();
          break;
      }
    };
    var renderUrlDialog = function(internalDialog, extra, editor, backstage) {
      var _a2;
      var header = getHeader(internalDialog.title, backstage);
      var body2 = renderIframeBody(internalDialog);
      var footer = internalDialog.buttons.bind(function(buttons) {
        if (buttons.length === 0) {
          return Optional.none();
        } else {
          return Optional.some(renderModalFooter({ buttons }, backstage));
        }
      });
      var dialogEvents = SilverDialogEvents.initUrlDialog(function() {
        return instanceApi;
      }, getEventExtras(function() {
        return dialog;
      }, backstage.shared.providers, extra));
      var styles = __assign(__assign({}, internalDialog.height.fold(function() {
        return {};
      }, function(height2) {
        return {
          "height": height2 + "px",
          "max-height": height2 + "px"
        };
      })), internalDialog.width.fold(function() {
        return {};
      }, function(width2) {
        return {
          "width": width2 + "px",
          "max-width": width2 + "px"
        };
      }));
      var classes2 = internalDialog.width.isNone() && internalDialog.height.isNone() ? ["tox-dialog--width-lg"] : [];
      var iframeUri = new global$1(internalDialog.url, { base_uri: new global$1(window.location.href) });
      var iframeDomain = iframeUri.protocol + "://" + iframeUri.host + (iframeUri.port ? ":" + iframeUri.port : "");
      var messageHandlerUnbinder = unbindable();
      var extraBehaviours = [
        config("messages", [
          runOnAttached(function() {
            var unbind2 = bind(SugarElement.fromDom(window), "message", function(e2) {
              if (iframeUri.isSameOrigin(new global$1(e2.raw.origin))) {
                var data = e2.raw.data;
                if (isSupportedMessage(data)) {
                  handleMessage(editor, instanceApi, data);
                } else if (isCustomMessage(data)) {
                  internalDialog.onMessage(instanceApi, data);
                }
              }
            });
            messageHandlerUnbinder.set(unbind2);
          }),
          runOnDetached(messageHandlerUnbinder.clear)
        ]),
        Receiving.config({
          channels: (_a2 = {}, _a2[bodySendMessageChannel] = {
            onReceive: function(comp, data) {
              descendant(comp.element, "iframe").each(function(iframeEle) {
                var iframeWin = iframeEle.dom.contentWindow;
                iframeWin.postMessage(data, iframeDomain);
              });
            }
          }, _a2)
        })
      ];
      var spec = {
        header,
        body: body2,
        footer,
        extraClasses: classes2,
        extraBehaviours,
        extraStyles: styles
      };
      var dialog = renderModalDialog(spec, internalDialog, dialogEvents, backstage);
      var instanceApi = getUrlDialogApi(dialog);
      return {
        dialog,
        instanceApi
      };
    };
    var setup$2 = function(extras) {
      var sharedBackstage = extras.backstage.shared;
      var open2 = function(message, callback2) {
        var closeDialog = function() {
          ModalDialog.hide(alertDialog);
          callback2();
        };
        var memFooterClose = record(renderFooterButton({
          name: "close-alert",
          text: "OK",
          primary: true,
          align: "end",
          disabled: false,
          icon: Optional.none()
        }, "cancel", extras.backstage));
        var titleSpec = pUntitled();
        var closeSpec = pClose(closeDialog, sharedBackstage.providers);
        var alertDialog = build$1(renderDialog$1({
          lazySink: function() {
            return sharedBackstage.getSink();
          },
          header: hiddenHeader(titleSpec, closeSpec),
          body: pBodyMessage(message, sharedBackstage.providers),
          footer: Optional.some(pFooter(pFooterGroup([], [memFooterClose.asSpec()]))),
          onEscape: closeDialog,
          extraClasses: ["tox-alert-dialog"],
          extraBehaviours: [],
          extraStyles: {},
          dialogEvents: [run$1(formCancelEvent, closeDialog)],
          eventOrder: {}
        }));
        ModalDialog.show(alertDialog);
        var footerCloseButton = memFooterClose.get(alertDialog);
        Focusing.focus(footerCloseButton);
      };
      return { open: open2 };
    };
    var setup$1 = function(extras) {
      var sharedBackstage = extras.backstage.shared;
      var open2 = function(message, callback2) {
        var closeDialog = function(state) {
          ModalDialog.hide(confirmDialog);
          callback2(state);
        };
        var memFooterYes = record(renderFooterButton({
          name: "yes",
          text: "Yes",
          primary: true,
          align: "end",
          disabled: false,
          icon: Optional.none()
        }, "submit", extras.backstage));
        var footerNo = renderFooterButton({
          name: "no",
          text: "No",
          primary: false,
          align: "end",
          disabled: false,
          icon: Optional.none()
        }, "cancel", extras.backstage);
        var titleSpec = pUntitled();
        var closeSpec = pClose(function() {
          return closeDialog(false);
        }, sharedBackstage.providers);
        var confirmDialog = build$1(renderDialog$1({
          lazySink: function() {
            return sharedBackstage.getSink();
          },
          header: hiddenHeader(titleSpec, closeSpec),
          body: pBodyMessage(message, sharedBackstage.providers),
          footer: Optional.some(pFooter(pFooterGroup([], [
            footerNo,
            memFooterYes.asSpec()
          ]))),
          onEscape: function() {
            return closeDialog(false);
          },
          extraClasses: ["tox-confirm-dialog"],
          extraBehaviours: [],
          extraStyles: {},
          dialogEvents: [
            run$1(formCancelEvent, function() {
              return closeDialog(false);
            }),
            run$1(formSubmitEvent, function() {
              return closeDialog(true);
            })
          ],
          eventOrder: {}
        }));
        ModalDialog.show(confirmDialog);
        var footerYesButton = memFooterYes.get(confirmDialog);
        Focusing.focus(footerYesButton);
      };
      return { open: open2 };
    };
    var validateData = function(data, validator) {
      return getOrDie(asRaw("data", validator, data));
    };
    var isAlertOrConfirmDialog = function(target) {
      return closest(target, ".tox-alert-dialog") || closest(target, ".tox-confirm-dialog");
    };
    var inlineAdditionalBehaviours = function(editor, isStickyToolbar2, isToolbarLocationTop) {
      if (isStickyToolbar2 && isToolbarLocationTop) {
        return [];
      } else {
        return [Docking.config({
          contextual: {
            lazyContext: function() {
              return Optional.some(box$1(SugarElement.fromDom(editor.getContentAreaContainer())));
            },
            fadeInClass: "tox-dialog-dock-fadein",
            fadeOutClass: "tox-dialog-dock-fadeout",
            transitionClass: "tox-dialog-dock-transition"
          },
          modes: ["top"]
        })];
      }
    };
    var setup = function(extras) {
      var backstage = extras.backstage;
      var editor = extras.editor;
      var isStickyToolbar$1 = isStickyToolbar(editor);
      var alertDialog = setup$2(extras);
      var confirmDialog = setup$1(extras);
      var open2 = function(config2, params, closeWindow) {
        if (params !== void 0 && params.inline === "toolbar") {
          return openInlineDialog(config2, backstage.shared.anchors.inlineDialog(), closeWindow, params.ariaAttrs);
        } else if (params !== void 0 && params.inline === "cursor") {
          return openInlineDialog(config2, backstage.shared.anchors.cursor(), closeWindow, params.ariaAttrs);
        } else {
          return openModalDialog(config2, closeWindow);
        }
      };
      var openUrl = function(config2, closeWindow) {
        return openModalUrlDialog(config2, closeWindow);
      };
      var openModalUrlDialog = function(config2, closeWindow) {
        var factory2 = function(contents2) {
          var dialog = renderUrlDialog(contents2, {
            closeWindow: function() {
              ModalDialog.hide(dialog.dialog);
              closeWindow(dialog.instanceApi);
            }
          }, editor, backstage);
          ModalDialog.show(dialog.dialog);
          return dialog.instanceApi;
        };
        return DialogManager.openUrl(factory2, config2);
      };
      var openModalDialog = function(config2, closeWindow) {
        var factory2 = function(contents2, internalInitialData, dataValidator) {
          var initialData = internalInitialData;
          var dialogInit = {
            dataValidator,
            initialData,
            internalDialog: contents2
          };
          var dialog = renderDialog(dialogInit, {
            redial: DialogManager.redial,
            closeWindow: function() {
              ModalDialog.hide(dialog.dialog);
              closeWindow(dialog.instanceApi);
            }
          }, backstage);
          ModalDialog.show(dialog.dialog);
          dialog.instanceApi.setData(initialData);
          return dialog.instanceApi;
        };
        return DialogManager.open(factory2, config2);
      };
      var openInlineDialog = function(config$1, anchor2, closeWindow, ariaAttrs) {
        var factory2 = function(contents2, internalInitialData, dataValidator) {
          var initialData = validateData(internalInitialData, dataValidator);
          var inlineDialog = value$1();
          var isToolbarLocationTop = backstage.shared.header.isPositionedAtTop();
          var dialogInit = {
            dataValidator,
            initialData,
            internalDialog: contents2
          };
          var refreshDocking = function() {
            return inlineDialog.on(function(dialog) {
              InlineView.reposition(dialog);
              Docking.refresh(dialog);
            });
          };
          var dialogUi = renderInlineDialog(dialogInit, {
            redial: DialogManager.redial,
            closeWindow: function() {
              inlineDialog.on(InlineView.hide);
              editor.off("ResizeEditor", refreshDocking);
              inlineDialog.clear();
              closeWindow(dialogUi.instanceApi);
            }
          }, backstage, ariaAttrs);
          var inlineDialogComp = build$1(InlineView.sketch(__assign(__assign({
            lazySink: backstage.shared.getSink,
            dom: {
              tag: "div",
              classes: []
            },
            fireDismissalEventInstead: {}
          }, isToolbarLocationTop ? {} : { fireRepositionEventInstead: {} }), {
            inlineBehaviours: derive$1(__spreadArray([config("window-manager-inline-events", [run$1(dismissRequested(), function(_comp, _se) {
              emit(dialogUi.dialog, formCancelEvent);
            })])], inlineAdditionalBehaviours(editor, isStickyToolbar$1, isToolbarLocationTop), true)),
            isExtraPart: function(_comp, target) {
              return isAlertOrConfirmDialog(target);
            }
          })));
          inlineDialog.set(inlineDialogComp);
          InlineView.showWithin(inlineDialogComp, premade(dialogUi.dialog), { anchor: anchor2 }, Optional.some(body()));
          if (!isStickyToolbar$1 || !isToolbarLocationTop) {
            Docking.refresh(inlineDialogComp);
            editor.on("ResizeEditor", refreshDocking);
          }
          dialogUi.instanceApi.setData(initialData);
          Keying.focusIn(dialogUi.dialog);
          return dialogUi.instanceApi;
        };
        return DialogManager.open(factory2, config$1);
      };
      var confirm2 = function(message, callback2) {
        confirmDialog.open(message, function(state) {
          callback2(state);
        });
      };
      var alert2 = function(message, callback2) {
        alertDialog.open(message, function() {
          callback2();
        });
      };
      var close2 = function(instanceApi) {
        instanceApi.close();
      };
      return {
        open: open2,
        openUrl,
        alert: alert2,
        close: close2,
        confirm: confirm2
      };
    };
    function Theme() {
      global$g.add("silver", function(editor) {
        var _a2 = setup$3(editor), uiMothership = _a2.uiMothership, backstage = _a2.backstage, renderUI = _a2.renderUI, getUi = _a2.getUi;
        Autocompleter.register(editor, backstage.shared);
        var windowMgr = setup({
          editor,
          backstage
        });
        return {
          renderUI,
          getWindowManagerImpl: constant$1(windowMgr),
          getNotificationManagerImpl: function() {
            return NotificationManagerImpl(editor, { backstage }, uiMothership);
          },
          ui: getUi()
        };
      });
    }
    Theme();
  })();

  // jquery.js
  var import_jquery = __toESM(require_jquery());
  window.jQuery = import_jquery.default;
  window.$ = import_jquery.default;

  // application-esbuild.js
  Turbo.setProgressBarDelay(300);
  window.bootstrap = bootstrap_esm_exports;
  require_rails_ujs().start();
  require_activestorage().start();
  require_channels();
})();
/*!
  * Bootstrap v5.1.3 (https://getbootstrap.com/)
  * Copyright 2011-2021 The Bootstrap Authors (https://github.com/twbs/bootstrap/graphs/contributors)
  * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
  */
/*!
 * @kurkle/color v0.1.9
 * https://github.com/kurkle/color#readme
 * (c) 2020 Jukka Kurkela
 * Released under the MIT License
 */
/*!
 * Chart.js v3.5.0
 * https://www.chartjs.org
 * (c) 2021 Chart.js Contributors
 * Released under the MIT License
 */
/*!
 * Chartkick.js
 * Create beautiful charts with one line of JavaScript
 * https://github.com/ankane/chartkick.js
 * v4.0.5
 * MIT License
 */
/*!
 * chartjs-adapter-date-fns v2.0.0
 * https://www.chartjs.org
 * (c) 2021 chartjs-adapter-date-fns Contributors
 * Released under the MIT license
 */
/*!
 * jQuery JavaScript Library v3.6.0
 * https://jquery.com/
 *
 * Includes Sizzle.js
 * https://sizzlejs.com/
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license
 * https://jquery.org/license
 *
 * Date: 2021-03-02T17:08Z
 */
/*!
Turbo 8.0.3
Copyright © 2024 37signals LLC
 */;
